简体   繁体   English

在 flutter 的一个屏幕中的选项卡之间共享数据?

[英]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.在具有 3 个选项卡的屏幕中,第一个选项卡使用 textFields 输入数据并存储在 CutomClass 中,其他两个选项卡使用存储在CustomClass中的数据来查看结果。

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.如何在选项卡之间共享CustomClass数据,以便当用户切换到其中一个时,来自 tab1 的任何更新都会反映到 tab2 和 tab3。

Code below is for the screen with 3 tabs in TabBarView as 3 stateful widgets.下面的代码适用于在 TabBarView 中有 3 个选项卡作为 3 个有状态小部件的屏幕。 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.我正在考虑将数据保存到CustomClass并在其他 2 个选项卡切换到使用更新的 CustomClass 数据时重建它们,但不知道如何实现。

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(),
          ],
        ),
      ),
    );
  }
}

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如果您不知道任何类似提供程序的 stateMangement 有一个简单的方法,您可以在每个选项卡中创建回调 function 并且每次发生您想要的事情时调用该变量将其存储在变量 ScreenWithTabs 和 setState 并将其发送到您想要的另一个选项卡

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);
              },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM