fluttersmith/tipsGitHub ↗
Learning path · 7 tips, in order

Cleaner widget code

Small habits that make build methods shorter, layouts more predictable and rebuilds cheaper.

  1. 017Replace Container with the widgets it wrapsContainer is a bundle of Padding, ColoredBox, DecoratedBox, Align and SizedBox. Use those directly and the whole subtree can be const.widgets
  2. 002Column(spacing:) replaces a SizedBox between every childRow, Column and Flex take a spacing value, so you no longer need a SizedBox or the gap package between children.layout
  3. 011Return SizedBox.shrink() when there is nothing to showA build method must return a widget. For "nothing", return const SizedBox.shrink(), not an empty Container.widgets
  4. 015Give buttons the same width with IntrinsicWidthWrap a Column in IntrinsicWidth and stretch its children, and every button matches the widest one, whatever the text size.layout
  5. 007Use MediaQuery.sizeOf instead of MediaQuery.ofMediaQuery.of rebuilds your widget when anything changes. MediaQuery.sizeOf and friends rebuild only when the value you read changes.performance
  6. 004Check context.mounted after every awaitA BuildContext can go stale while you await. Check context.mounted before you use it again, or grab what you need first.context
  7. 029Style an ElevatedButton with styleFrom and themesUse ElevatedButton.styleFrom for one button, ElevatedButtonThemeData for all of them, and WidgetStateProperty when a style depends on state.buttons