Proper way to create a Widget?

Viewed 63

Beginner question... Flutter materials say to extend stateless or stateful widget class... but in the tutorials there were a couple examples where widgets were not defined as classes.

Widget buttonSection = Container(
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: [
      ...
    ],
  ),
);

https://flutter.dev/docs/development/ui/layout/tutorial#step-0-create-the-app-base-code

vs

class ButtonSection extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return (...)
}

Should small simple widgets just be variables inside your class? or their own class that extends stateful or stateless parent class.

2 Answers

You are creating instance of a class on the top code and class on the bottom. It is like you have an item on top and a blueprint at the bottom code.

This is very subjective, to decide how you split your widgets. Here is how I divide and create widgets.

  1. There will always be a screen, which comprises of multiple interactive (Buttons) and non-interactive (Text, Image) elements.
  2. Usually if you working on a product/project, you will have a UI. So can create generic widgets which can be used throughout the app.
  3. Now comes the widgets which are screen-specific widgets that will not be used on other screens.
  4. Let's say, you have a screen that has a carousel you can create a separate class for it and all the functionality related to it inside that class.
  5. For small sections on the screen like an item inside a list view, you can create a class function say _renderUserItem(String name, String mail, String avatar, bool isActive) and return a Container or ListViewTile() based on your UI requirement.
  6. Call this function inside your build() function.

Conclusion -

  • Keep bigger elements in a separate class to handle any functionality.
  • Any UI section which is kind of small (50 lines of code) and static enough, can be kept in the same class.

PS - It is subjective in nature. But it is always advisable to keep your widget as Dumb as possible.

Related