gpt4 book ai didi

flutter - 给定 ChangeNotifier 中的状态更改,更改 TabView 中的选定选项卡

转载 作者:IT王子 更新时间:2023-10-29 07:18:36 25 4
gpt4 key购买 nike

我有以下类来保持我的状态:

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 转换为 StatelessWidget 然后,我不会使用 DefaultTabController 而是使用TabController 并将其作为参数传递给 TabBarView。

然后在 MainScaffoldStateinitState 中,我将监听 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"),
],
),
);
}
}

关于flutter - 给定 ChangeNotifier 中的状态更改,更改 TabView 中的选定选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56529764/

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