How to Manage state between tabs in Flutter App

2020-07-22 10:11发布

I am using TabBar in my application where I need to get Input in first tab and show
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?

I solved the above problem using AutomaticKeepAliveClientMixin as described in the answer below.

2条回答
Bombasti
2楼-- · 2020-07-22 10:44

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
  2. Scoped model library to hold app state and notify Widgets of Updates
  3. Redux library to manage app state and update Widgets
  4. Business Logic Components (BLoC)

Check out this article. Check this GitHub repository with different architecture examples

查看更多
狗以群分
3楼-- · 2020-07-22 10:45

I think what you may be after is AutomaticKeepAliveClientMixin. I always add that to my screen widgets within 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).

查看更多
登录 后发表回答