Flutter
Published in

Flutter

Managing visibility in Flutter

How hiding widgets can also hide inefficiency in your code

By Marian (https://www.flickr.com/photos/lescientist/8430282209) (CC BY-NC-SA 2.0)

Visible

Invisible

Offscreen

Gone

List<Widget> views = [];
if (shouldBeIncluded) {
views.add(myView);
}
// use views later
  • Will the condition for displaying my widget never be met for certain cases? An example is when you have a first time experience, on-boarding, etc. If you have a condition where you only show it the first time the app starts then you won’t want to include it ever again. So, this one is easy. In this case you should not include your widget in the first place. You can use a Gone strategy.
  • Do I need to keep the widget in place or should the rest of the UI adapt to fill the missing space? If you need to keep it in place and do a swap or something similar then you can use an Invisible strategy and toggle the visibility as needed. If you need to eliminate the “white space”, then you can use Offscreen.
  • Do I need to still factor in the size of my widget even if it isn’t visible? Use Offscreen but read the above point first :)
  • For Visible: we don’t do anything special.
  • For Invisible: we wrap the widget in an IgnorePointer widget and an Opacity widget with the value zero. This limits your ability to interact with the widget and hides it but will keep it in place. So, you will see empty space wherever the widget is inserted.
  • For Offscreen: we wrap the widget in an Offstage widget which will render the widget off screen so that it won’t be visible and it won’t take up any screen real estate. However, it is still being rendered so it won’t be zero cost. Beware.
  • For Gone: we provide a way for you to render a different widget (defaulting to a Container with no size). If you want to render a placeholder, an icon or something else, this is your place to do it. It still isn’t zero cost, but it shouldn’t be too awful for most cases. For true Gone, use the strategies described above.
  • As mentioned above, there are real costs associated with this approach so be careful and where possible just don’t include your original widget. I sound like a broken record but you shouldn’t forget it. There is no tree shaking here.
  • Opacity widgets can be super expensive so use Invisible sparingly.

--

--

Flutter is Google's mobile UI framework for crafting high-quality native interfaces on iOS, Android, web, and desktop. Flutter works with existing code, is used by developers and organizations around the world, and is free and open source. Learn more at https://flutter.dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store