Visibility vs conditional widget

Viewed 879

I have a multilevel user app in which I have implemented role based widget. Such as;

final user=Provider.of<UserNotifier>(context).getRole(); //returns role string

(user=="Admin")?SomeWidget():Container(),

There is another option such as:

Visibility (
                  visible: (user=="Admin"),
                  child: SomeWidget()
                ),

Which would be the best approach among this two?

3 Answers

I would say, first option(following) is best option.

(user=="Admin")?SomeWidget():Container(),

As can be seen from code it only build widget which is required. For Example, if condition is true then it will build SomeWidget otherwise it build Container.

Main benefit id that it will improve app performance, it will not build SomeWidget if it is not require. Suppose your SomeWidget is really big widget in which you are getting data from server and all that, in this case it will continue doing all that think even that widget is not displaying. So we can say that all the request we are doing is not worthy.

While in Second case, it will keep doing all that thing that's why i think that way is not good.

Ternary is always the best way to decide that, why we should add extra code and widgets in the tree if we can avoid that.

Also, We should use ternary wherever possible as that code is much more readable to use.

You want to use the Ternary operation here, since the user's role won't be changing when interacting with the app, We use Visibility to change it to true in case we want the user to see the widget but in your case the visible items seem to be tied to the role and won't be changing.

Related