Delegate Widget Design
Using the widely used builder pattern in Flutter can help you build complex UI more cleanly.
When is that useful?
Imagine you are creating a list of items, like a list of radio buttons or checkboxes in a ListView
. You don't want the main widget to handle the design details of each item inside the list. That gets messy.
How Delegation Works
Instead of the main widget building every single child item directly, you can use a concept called delegation. You provide a separate function or object, often called a "builder", that takes care of creating the design for each item.
The Builder Pattern
The image shows an example using a typedef
for the builder function:
typedef OptionBuilder = Widget Function(String key, bool selected);
This OptionBuilder
is a function that knows how to build a single item widget based on a key
(maybe the text) and whether it's selected
or not.
Using the Builder
The main widget (like RadioQuestion
in the example) receives this OptionBuilder
as a parameter:
final OptionBuilder optionBuilder;
Then, when it needs to display an item, it just calls this optionBuilder
function, passing the necessary data for that specific item:
widget.optionBuilder(widget.keys[index], _selectedIndex == index)
This way, the main widget focuses on managing the list structure and data (keys
, _selectedIndex
), while the builder function focuses solely on how each individual item looks. This makes your code easier to read, maintain, and reuse.