What is the best way to organize Flutter widgets? What is the best way to organize Flutter widgets? flutter flutter

What is the best way to organize Flutter widgets?


As for:

  1. create a final variable and store the customized widget on it

Using a class variable to hold your widget such as

final Widget foo = new Foo();

may be unnecessary or may point to some other issues. I think you are better off creating a function that returns your widget such as

Widget _buildFoo() {  return new Foo();}

And then you can use this in, for example, your build() method such as (I'm adding MaterialApp Scaffold to provide more context):

@override  Widget build(BuildContext context) {    return new Scaffold(      appBar: new AppBar(        title: new Text("My App"),      ),      body: _buildFoo(),    );  }

Take a look at other example apps on the web such as the Flutter Examples for ideas on structuring your widgets.

As for:

  1. create a new widget as a template

I am going to interpret this as creating another file to hold your widget class e.g. foo.dart. This may not be what you are asking, but creating new dart files for each widget can become a good idea as your app grows. For simple apps, especially most example apps you see, leaving the classes in the same dart file (e.g. main.dart) works just fine. Again, I may not be addressing your question.

Getting back to:

best way to make my code more readable

So, in summary, using private functions that return different sections of your widget tree (i.e functions that just return a widget and any sub widgets that it may include) is generally better than storing widgets as class instance variables. You may want to use a class variable if you need to later reference or interact with the widget; however, this is probably a bad practice and may point to a better way to handle the changing of states and the structure of your widget tree (for example, Flutter's Stateful and Inherited widgets are great for handling state change with needing to make an imperative call on an object reference).