DEV Community

Cover image for 🦋Flutter - Manage Widget Permissions
Luciano Jung
Luciano Jung

Posted on • Updated on

🦋Flutter - Manage Widget Permissions

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
Enter fullscreen mode Exit fullscreen mode

a constructor ...

 AuthorizationWidget(
      {this.key,
      this.children,
      this.role,
      [...]
      })
      : assert(role != null),
        super(key: key);
Enter fullscreen mode Exit fullscreen mode

and uses an Animated Switcher in the build method.

@override
  Widget build(BuildContext context) {
    return AnimatedSwitcher(
      key: key ?? GlobalKey(),
      [...]
      child: _getWidget(),
    );
  }
Enter fullscreen mode Exit fullscreen mode

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

Alt Text

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

Top comments (2)

Collapse
 
jayasubin_flutter profile image
Jayasubin J • Edited

That's simple and neat;
How would you suggest doing it if the exact role that the current user has, is unknown to the frontend?

Collapse
 
lucianojung profile image
Luciano Jung

I think i dont understand your question right. Do you ask how to handle the UI If the Backend only knows the User role. You can't! You can only pass a variable from the Backend and Access IT to determine the Interfaces appearance. Otherwise how would you knows.