简体   繁体   English

如何在Flutter App中管理选项卡之间的状态

[英]How to Manage state between tabs in Flutter App

I am using TabBar in my application where I need to get Input in first tab and show 我在应用程序中使用TabBar,我需要在第一个标签中获取Input并显示
output based on some calculation on other tab. 输出基于其他选项卡上的一些计算。

I am able to get input in first tab but when I click on second tab, my state is lost. 我可以在第一个选项卡中获得输入,但是当我单击第二个选项卡时,我的状态将会丢失。 I am not sure if I have to make it a Stateful widget at root level. 我不确定是否必须在根级别将其设置为有状态的小部件。

I am relatively new in Mobile App. 我在移动应用程序中相对较新。 Can someone help me out here? 有人可以帮我吗?

EDIT: 编辑:

Now I am able to achieve what I said above, but when I am trying to access the list of items from first tab, it throws null exception in second tab? 现在,我可以实现上面所说的内容,但是当我尝试从第一个选项卡访问项目列表时,它在第二个选项卡中引发null异常吗?

I solved the above problem using AutomaticKeepAliveClientMixin as described in the answer below. 如下面的答案所述,我使用AutomaticKeepAliveClientMixin解决了上述问题。

I think what you may be after is AutomaticKeepAliveClientMixin . 我认为您可能想要的是AutomaticKeepAliveClientMixin I always add that to my screen widgets within TabBarView . 我总是将其添加到TabBarView屏幕小部件中。 This way when a user enters data into fields in one tab and navigates to other tabs and back the data is still there as you would expect. 这样,当用户在一个选项卡中的字段中输入数据并导航到其他选项卡并返回数据时,数据仍然如您所愿。 Then when the user performs an action like "save" I deal with state management (BLoC etc). 然后,当用户执行“保存”之类的操作时,我将处理状态管理(BLoC等)。

You may want to use architecture for managing and sharing states. 您可能要使用体系结构来管理和共享状态。 There are many approaches to manage state: 有很多方法可以管理状态:

  1. InheritedWidget to pass app state down the widget hierarchy InheritedWidget沿小部件层次结构传递应用程序状态
  2. Scoped model library to hold app state and notify Widgets of Updates 作用域模型库可保存应用程序状态并通知小部件更新
  3. Redux library to manage app state and update Widgets Redux库用于管理应用程序状态和更新小部件
  4. Business Logic Components (BLoC) 业务逻辑组件(BLoC)

Check out this article . 查看这篇文章 Check this GitHub repository with different architecture examples 使用不同的架构示例检查此GitHub存储库

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

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