【问题标题】:Change selected tab in TabView given state change in ChangeNotifier给定 ChangeNotifier 中的状态更改,更改 TabView 中的选定选项卡
【发布时间】:2019-06-10 15:59:55
【问题描述】:

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

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 2015-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多