Khaled Mahmoud
Khaled Mahmoud

Reputation: 302

share data between tabs in one screen in flutter?

In a screen with 3 tabs, first tab with textFields to input data and store in CutomClass, the other two tabs use data stored in the CustomClass to view results.

How can i share CustomClass data between the tabs such that any update from tab1 reflects to tab2 & tab3 when the user switches to one of them.

Code below is for the screen with 3 tabs in TabBarView as 3 stateful widgets. I was thinking of saving data to CustomClass and rebuild the other 2 tabs ever time they are switched to using updated CustomClass data, but don't know how to achieve that.

any advice, thoughts or examples?!

class ScreenWithTabs extends StatefulWidget {
  @override
  _ScreenWithTabsState createState() => _ScreenWithTabsState();
}

class _ScreenWithTabsState extends State<ScreenWithTabs> {
  CustomClass customClass;

  @override
  void initState() {super.initState();}

  @override
  DefaultTabController build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          bottom: TabBar(tabs: [
            Tab(text: 'input tab',),
            Tab(text: 'output tab 1',),
            Tab(text: 'output tab 2',),
          ]),
          ),
        ),
        body: TabBarView(
          children: [
            InputTab(),
            OutputTab1(),
            OutputTab2(),
          ],
        ),
      ),
    );
  }
}

Upvotes: 1

Views: 1642

Answers (1)

Ardeshir ojan
Ardeshir ojan

Reputation: 2419

if you dont know any stateMangement like provider there is an easy approch you can create a callback function in each of those tabs and everytime something you desire happens call that variable back store it in a variable ScreenWithTabs and setState and send it to another tab you desire

int x;

TabBarView(
            children: [
              ComplatedOrdersTab(number:x),
              CartTab(
                refreshCallback: (int result) {
                  x = result;
                  setState(() {});
                },
              ),
            ],
          ),

if you are not familiar with the implementation of the callback

class CartTab extends StatefulWidget {

Function(int result) refreshCallback;

CartTab({
  this.refreshCallback,
});

and if you want to use it

onTap: () {
                  widget.refreshCallback(1);
              },

Upvotes: 2

Related Questions