Conditional rendering in Flutter means building different widgets depending on a condition, such as application state, user input, or data availability. Instead of hiding UI elements, Flutter decides which widgets exist in the widget tree during the build() phase.
Because Flutter UI is written in pure Dart, conditional rendering uses standard Dart control flow rather than templates.
Conditional rendering affects:
Because Flutter rebuilds widgets frequently, choosing the right conditional pattern improves performance and prevents subtle UI bugs.
Flutter relies on Dart language features:
if statements inside widget lists (children: [])condition ? A : B)build()Example with collection if (recommended):
Column(
children: [
const Text('Profile'),
if (isAdmin) const Icon(Icons.shield),
],
);Example with ternary operator (single slot):
child: isLoading
? const CircularProgressIndicator()
: const SizedBox.shrink(),Use it when:
For large UI differences, returning early from build() keeps code readable:
if (error != null) {
return ErrorView(error!);
}Avoid conditional rendering when you want to temporarily hide UI but keep its state.
Using if removes the widget from the tree, which resets state such as:
TextFieldIn those cases, prefer Visibility(maintainState: true) or Offstage.
Several issues appear frequently:
if in lists.if removes widget state.SizedBox.shrink() is not inherently bad, but context matters.
children:):if to add or remove widgets. Avoid returning empty widgets.child:, builder:):SizedBox.shrink() is the correct and lightweight choice, better than Container().To keep conditional rendering clean:
if in lists whenever possibleUsed correctly, conditional rendering keeps Flutter UIs predictable, performant, and easy to maintain.
12 min • Jul 27, 2023
Read about the LeanCode approach to Flutter architecture. We highlight some of the design decisions that should be made when developing a feature in mobile apps. This includes our approach to dependency injection, state management, widget lifecycle, and data fetching.
20 min. • Feb 9, 2024
In a recent project, we embarked on the exciting task of enhancing an existing app with dynamic social media elements. Choosing Stream as our ally, we navigated through challenges and came up with strategies that helped us overcome them, resulting in the successful delivery of a news feed feature. Read our complex article.