I was told by someone who seemed quite good at flutter that building widgets inside functions then passing them back to the build function was inefficient as it didn’t allow flutter to skip the build process for widgets that haven’t changed.
for example:
/// bad
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFF7F7F7),
appBar: _buildAppBar(),
body: _buildContent(),
);
}
PreferredSizeWidget _buildAppBar() {
return AppBar(...);
}
Widget _buildContent() {
return Stack(
children: [
SafeArea(
child: Column(
children: [
Expanded(
child: ...,
),
...
],
),
),
],
);
}
...
/// good
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFF7F7F7),
appBar: AppBar(...),
body: Stack(
children: [
SafeArea(
child: Column(
children: [
Expanded(
child: ...,
),
...,
],
),
),
],
),
);
}
Is this true? I believed them until I came across the very example shown above in the dart documentation at https://docs.flutter.dev/cookbook/effects/drag-a-widget. Now my whole world is upside down and I just don’t know what to believe anymore.
Does breaking the build functions into smaller functions hurt performance by not allowing the framework to cache or detect unchanged widgets properly?
3
Answers
If you think about it, if it does, it really does not affect much on performance. As the build method is called, it will compile and redirect to where the function is pointed, after the returned object, it continues to where it left of within the build method. The specific classes you use (that changes or not) defines the performance.
Separating your widgets in a function is not a bad idea at all. It is actually one way of organizing a code. But this doesn’t improve performance because you just separated it into a function for clarity and readability. But if you’re looking to separate widgets to improve performance, then creating it as a separate widget is the best way to do it.
Saying that one method is bad and the other is good is irrelevant, when you can’t create a fixed widget structure if your build methods are dynamic.
Whether most agree or not, creating methods for managing widgets is the way to go.
The app becomes more manageable, and visually it is more pleasant and easy to identify sections to improve.
Just think about how many libraries you already use in your projects, and how you call them within your project, and imagine if all of those existed in a single monolithic structure.
Which one of these do you prefer?
or this: