gpt4 book ai didi

flutter - 如何在 Flutter 中的选项卡(TabBar)之间保持状态?

转载 作者:行者123 更新时间:2023-12-03 18:36:33 25 4
gpt4 key购买 nike

我有一个 TabBarView与 3 TabBar .当我在选项卡 1 中时我做了一些事情,然后当我回到选项卡 1 时导航到选项卡 2 我希望选项卡 1 的先前状态不会改变。

我如何在 Flutter 中实现这一点?

下面是我的代码截图

class _LandingPageState extends State<LandingPage> with SingleTickerProviderStateMixin {
int _selectedIndex = 0;
PageController pageController;
TabController tabController;

@override
void initState() {
tabController = TabController(length: 3, vsync: this, initialIndex: 0);
pageController = PageController(initialPage: 0)
..addListener(() {
setState(() {
_selectedIndex = pageController.page.floor();
});
});
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedIndex,
onTap: (index) {
setState(() {
_selectedIndex = index;
tabController.animateTo(index,
duration: Duration(microseconds: 300),
curve: Curves.bounceIn);
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.assignment), title: Text("Các yêu cầu")),
BottomNavigationBarItem(
icon: Icon(Icons.history), title: Text("Lịch sử")),
BottomNavigationBarItem(
icon: Icon(Icons.person), title: Text("Hồ sơ")),
]),
body: TabBarView(
controller: tabController,
children: [
RequestPage(key: PageStorageKey<String>("request_page"),),
HistoryPage(key: PageStorageKey<String>("history_page")),
ProfilePage(key: PageStorageKey<String>("profile_page"))])
),
);
}

enter image description here

最佳答案

确保您所有的 TabBarView children 是StatefulWidgets然后添加一个 AutomaticKeepAliveClientMixin就像所有这些一样,例如,对于您的 RequestPage ,它应该是这样的:

class RequestPage extends StatefulWidget {
RequestPage({Key key}) : super(key: key);

@override
_RequestPageState createState() => _RequestPageState();
}

class _RequestPageState extends State<RequestPage> with AutomaticKeepAliveClientMixin{
@override
Widget build(BuildContext context) {
super.build(context);
return // Your widget tree
}

@override
bool get wantKeepAlive => true;
}

关于flutter - 如何在 Flutter 中的选项卡(TabBar)之间保持状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61383732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com