flutter - 给定 ChangeNotifier 中的状态更改,更改 TabView 中的选定选项卡
问题描述
我有以下课程来保持我的状态:
import 'package:flutter/foundation.dart';
enum ActiveProduct {
HOME,
BURGUNDY,
VIRTUAL
}
class ActiveProductModel extends ChangeNotifier {
ActiveProduct _activeProduct = ActiveProduct.HOME;
ActiveProduct get value => _activeProduct;
void set(ActiveProduct newValue) {
_activeProduct = newValue;
notifyListeners();
}
}
每当“ActiveProduct”更改时,我想更改 TabView 中选定的选项卡。
目前我已经设置了这样的应用程序:
class MainScaffold extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
body: TabBarView(
children: [
Text("hello! abc"),
Text("hello! sdsadsa"),
Text("hello! 231321"),
],
),
),
);
}
}
当 ActiveProduct 更改时,如何更改 TabBarView 中选定的选项卡?
我尝试将 MainScaffold 包装在 Consumer 中并设置 DefaultTabController 的 initialIndex 值。然而这并没有奏效。
我正在使用 Provider 包进行状态管理。
解决方案
我要做的是将你的MainScaffold
转换为a StatelessWidget
,然后,我不会使用a DefaultTabController
,而是使用aTabController
并将其作为参数传递给TabBarView。
然后在 的initState
中,每当有东西被触发时MainScaffoldState
,我都会听ActiveProductModel
并使用。tabController.animateTo(yourpage)
我不确定我的解释是否很清楚,所以这里有一个例子:
class MainScaffold extends StatefulWidget {
@override
_MainScaffoldState createState() => _MainScaffoldState();
}
class _MainScaffoldState extends State<MainScaffold> with SingleTickerProviderStateMixin {
TabController tabController;
/// Just for the example
ActiveProductModel activeProductModel = ActiveProductModel();
@override
void initState() {
// Initiate the tabController
tabController = TabController(vsync: this, length: 3);
activeProductModel.addListener(() {
if (mounted)
/// Here you can do whatever you want, just going to page 2 for the example.
tabController.animateTo(2);
});
super.initState();
}
@override
void dispose() {
tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: TabBarView(
controller: tabController,
children: <Widget>[
Text("hello! abc"),
Text("hello! sdsadsa"),
Text("hello! 231321"),
],
),
);
}
}
推荐阅读
- python-3.x - GroupByKey() 与 Apache Beam
- javascript - 将类添加到javascript中的最后四个“a”元素
- javascript - `==` 仍然被称为“抽象相等运算符”吗?
- python - 根据 csv 中的图像标签创建子文件夹
- android - 如何映射 StateFlow 值并通过数据绑定将其传递给视图
- service-accounts - 如何解决 Sage Error 3004 文件系统错误?
- excel - Power Query 中的相对源文件引用
- azure - 使用图形 API 配置 GCP 的 Azure AD saml 配置“登录 URL”
- blazor - 您如何使用 Blazor WebAssembly 开发 PWA 以更快地查看您对离线模式的更改?
- r - 如何确保参数是按名称而不是按位置调用的?