Junior — Middle
How do you evaluate the approach to creating a widget using methods?
sobes.tech AI
Answer from AI
When creating a widget in Flutter, I prefer to use methods to structure the code and improve readability. For example, if a widget is complex, I break it down into several private methods, each returning a part of the interface.
This helps avoid bulky build methods and enhances code maintainability. Methods can also be reused within the widget, reducing duplication.
Example:
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: [
_buildHeader(),
_buildContent(),
],
);
}
Widget _buildHeader() {
return Text('Header', style: TextStyle(fontSize: 24));
}
Widget _buildContent() {
return Text('Main content');
}
}
This approach improves readability and makes code maintenance easier, especially in large widgets.