gpt4 book ai didi

tabs - Flutter:使用AutomaticKeepAliveClientMixin动态添加选项卡并保持状态

转载 作者:行者123 更新时间:2023-12-03 03:41:56 24 4
gpt4 key购买 nike

我正在尝试创建带有标签的表单。在每个选项卡中,我都有TextFormField。选项卡具有AutomaticKeepAliveClientMixin来保持其状态。标签可以动态创建。创建新选项卡后,它会插入到选项卡列表的中间。

问题:插入新选项卡时,其TextFormField保持下一个选项卡的状态,依此类推。似乎状态从1到n保持有序。有什么办法可以保持选项卡的正确状态?

提前致谢。

import 'package:flutter/material.dart';

class TabTesting extends StatefulWidget {
@override
_TabTestingState createState() => _TabTestingState();
}

class _TabTestingState extends State<TabTesting> with TickerProviderStateMixin {

List<MyTab> _tabs = [
MyTab(TabData("1", "1")),
MyTab(TabData("3", "3")),
];

TabController _tabController;

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

_tabController = new TabController(vsync: this, length: _tabs.length);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("TabTesting"),
bottom: TabBar(
controller: _tabController,
labelPadding: EdgeInsets.symmetric(vertical: 16.0),
tabs: _tabs.map((tab) => Text(tab.tabData.name)).toList(),
),
),
body: Container(
padding: EdgeInsets.all(32.0),
child: TabBarView(
controller: _tabController,
children: _tabs,
),
),
persistentFooterButtons: <Widget>[
RaisedButton(
child: Text("Add tab"),
onPressed: () {
final newTab = MyTab(TabData("2", "2"));
final newTabs = _tabs;
newTabs.insert(1, newTab);
final index = _tabController.index;
setState(() {
_tabs = newTabs;
_tabController = TabController(
vsync: this,
length: newTabs.length,
initialIndex: index);
});
},
),
],
);
}
}

class MyTab extends StatefulWidget {

final tabData;

MyTab(this.tabData);

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

class _MyTabState extends State<MyTab> with AutomaticKeepAliveClientMixin {

@override
bool get wantKeepAlive => true;

@override
Widget build(BuildContext context) {
return Tab(
child: TextFormField(
decoration: InputDecoration(labelText: widget.tabData.name),
initialValue: widget.tabData.data,
),
);
}
}

class TabData {
String name;
String data;

TabData(this.name, this.data);
}

最佳答案

您忘记按照documentation of AutomaticKeepAliveClientMixin的建议添加super.build(context);

@override
Widget build(BuildContext context) {
super.build(context);
return Tab(
child: TextFormField(
decoration: InputDecoration(labelText: widget.tabData.name),
initialValue: widget.tabData.data,
),
);
}

关于tabs - Flutter:使用AutomaticKeepAliveClientMixin动态添加选项卡并保持状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53997942/

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