In Flutter, you don’t always want to display the same widget. In many cases, the widget to display depends on the current user.
Stay tuned to learn how you can easily display widgets depending on the current user role. use the widget ->
The widget that solves the problem
To solve this problem I created a widget that takes the user’s current role and an authorization. The authorization basically contains all valid roles. If the passed role is valid for one given widget, the expected widget is displayed. If the role cannot be assigned to an authorization, nothing ( or rather an empty SizedBox widget) is displayed. The central authorization widget is a stateless widget that uses an AnimatedSwitcher to generate a smooth overflow when roles are changed.
The final widget contains the following attributes…
final List<Tuple2<Authorization, Widget>> children;
final String role;
... and all attributes for an AnimatedSwitcher-Widget
a constructor …
AuthorizationWidget(
{this.key,
this.children,
this.role,
[...]
})
: assert(role != null),
super(key: key);
and uses an Animated Switcher in the build method.
@override
Widget build(BuildContext context) {
return AnimatedSwitcher(
key: key ?? GlobalKey(),
[...]
child: _getWidget(),
);
}
The children attribute contains a list of two-tuples (Tuple2). These tuples assign an authorization object to a widget based on the key value principle. If the current role is found in an authorization object, the corresponding widget is displayed. (Please note that only the first widget that matches the criterion is displayed.)
Result
The resulting widget is available online on Github and pub.dev and can be integrated into every Flutter project: See the source code on Github Integrate in a Flutter Project using pub.dev
Feedback
If you have any ideas or suggestions on how to better implement the widget, feel free to comment on this post. If you want to learn more about Flutter and its mechanisms in the future feel free to follow my profile on Dev.to or on Github