首页 > 解决方案 > 给定 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 包进行状态管理。

标签: flutter

解决方案


我要做的是将你的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"),
        ],
      ),
    );
  }
}

推荐阅读