Flutter design: make your theme homogeneous
///
/// Defines the card's [Material.shape].
///
/// If this property is null then [CardTheme.shape] of [ThemeData.cardTheme]
/// is used. If that's null then the shape will be a [RoundedRectangleBorder]
/// with a circular corner radius of 4.0.
final ShapeBorder? shape;
final base = ThemeData.dark();
final mainColor = Colors.lightBlue;
return base.copyWith(
cardColor: Color.lerp(mainColor, Colors.white, 0.2),
cardTheme: base.cardTheme?.copyWith(
color: Color.lerp(mainColor, Colors.black, 0.1),
margin: EdgeInsets.all(20.0),
elevation: 0.0,
shape: BeveledRectangleBorder(
borderRadius: BorderRadius.circular(14.0),
side: BorderSide(color: Colors.white24, width: 1)),
),
);
}
itemBuilder: (context, index) {
final value = elements[index];
return ListTile(
selected: value == selected,
title: Text(value.title),
subtitle: Text(value.message),
leading: Icon(value.icon),
onTap: () => setState(() => selected = value),
);
},
itemCount: elements.length,
);
As you can see in the code, there is nothing related to the design. It as the advantage to avoid code noises, making it succinct and easier to understand. Also, one thing I like is in the fact that all my methods are small (less than 30 lines).
Conclusion
In this article, we saw how to centralize the application design into the ThemeData object. As you may understood, you may have to read a lot of the Flutter SDK code documentation for that purpose, but benefits will come when you or another colleague will have to maintain it:
Avoid code duplication
Less code in your pages, making code easier to be read and understood
Ensure design consistency
But as you may have seen, the ThemeData object is a really big structure, in constant evolution. So keep an eye on it !
To go further more…
Two more little tips for you! First, if you want to have a specific design for one of your component, instead of customizing it inside the build method, you can wrap your widget into the Theme widget.
When you design a new widget, you may want to imitate the SDK widgets, by retrieving theme information from the ThemeData. You may have seen that inheritate from ThemeData is not the right way. Instead, you can “extends” it through InheritedTheme widget, and imitate how it’s implemented like in ListTileTheme widget.