Home > Mobile >  How to reuse build method code in Flutter?
How to reuse build method code in Flutter?

Time:12-12

In my app I have five pages where each of them can have 2-4 tabs with content. So every page will have the same code in build method, which in my case is:

...

List<Tab> tabs - list of tabs
List<Widget> tabsViews - list of widgets with view content

...

build(BuildContext build){
...
return DefaultTabController(
      length: tabs.length,
      child: SafeArea(
        child: Column(
          children: [
            SizedBox(
              child: TabBar(
                tabs: tabs,
              ),
            ),
            Expanded(
              child: TabBarView(
                children: tabBarViewChildren,
              ),
            ),
          ],
        ),
      ),
    );
}

How should I solve code reusability problem ?

  • option 1: create a global function like a buildPageWithTabs(List<Tab> tabs, List<Widget> tabsViews) and in every screen I should call it in build``` method with parameters
  • option 2: create e.g. TabbedPage class with constructor that takes tabs & tabsViews and instantiate it with parameters in navigator or any other place which switch me to the this view.
  • option 3: Copy paste this code to every build method ?

CodePudding user response:

Option (2) is the best solution.

Using the below Page class you can create any number of instances(Pages) from it.

class Page extends StatelessWidget {
  const Page({Key? key, required this.tabs, required this.tabBarViewChildren})
      : super(key: key);

  final List<Tab> tabs;
  final List<Widget> tabBarViewChildren;

  @override
  build(BuildContext context) {
    return DefaultTabController(
      length: tabs.length,
      child: SafeArea(
        child: Column(
          children: [
            SizedBox(
              child: TabBar(
                tabs: tabs,
              ),
            ),
            Expanded(
              child: TabBarView(
                children: tabBarViewChildren,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

In Option(1) using functions can do the same thing, but it has a number of disadvantages over classes.

Read this StackOverflow to know the difference: What is the difference between functions and classes to create reusable widgets?

watch this video from the flutter youtube channel : Widgets vs helper methods

  • Related