将 Provider 与 TickerProviderStateMixin 一起使用:我可以在哪里初始化我的控制器?

Using Provider with with TickerProviderStateMixin: Where can I initialise my controller?

我只是在玩 Flutter,我 运行 遇到了一些问题 -> 这是我的回购协议:https://github.com/LuckyRon88/FlutterWebCV

我正在使用 https://pub.dev/packages/motion_tab_bar/example 创建底部导航栏作为堆栈的子项。我将在多个页面上使用这个底部导航栏来更改屏幕上的小部件,因此我重构了我的代码以获得 BottomNavigation.dart.

我正在使用提供程序作为我的状态管理解决方案。

这是标签栏https://github.com/LuckyRon88/FlutterWebCV/blob/master/lib/Components/TestTab.dart

我想在 https://github.com/LuckyRon88/FlutterWebCV/blob/master/lib/Screens/Education.dart 上使用它,但我需要能够从 Education.dart 访问 eduTabController(来自 TestTab.dart)以更改同一页面上的一些信息。

我已经有一个提供者模型 https://github.com/LuckyRon88/FlutterWebCV/blob/master/lib/ProviderPack/PageController.dart,但我不确定如何让提供者控制我的 eduTabController,因为我无法在任何地方初始化它,只能在 TestTab.dart 本身上进行初始化。

由于 MotionTabView 中需要 controllerMotionTabBar 中不需要,因此将 _eduTabController 移动到 Education class。现在定义选项卡选择所需的函数,即 Education class 中的 onTabItemSelected 并将其作为参数传递给 TestTab.

这样你就可以避免在 TestTab 中使用 _eduTabController 并在存在于 Education.

中的 MotionTabView 中使用它

这是一个粗略的实现:

// convert Education to StatefulWidget
class Education extends StatefulWidget {

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

// Requires SingleTickerProviderStateMixin
class _EducationState extends State<Education> with SingleTickerProviderStateMixin {
  final MotionTabController _eduTabController; // have your controller here

  @override
  void initState() {
    super.initState();
    // initialize controller
    _eduTabController = MotionTabController(initialIndex: 1, vsync: this);
  }

  @override
  void dispose() {
    super.dispose();
    // dispose controller
    _eduTabController?.dispose();
  }

  // Extract your function from TestTab
  void onTabItemSelected(int value) {
    setState(() {
      _eduTabController.index = value;
    });
  },
  
  @override
  Widget build(BuildContext context) {
    //...

         Align(
           alignment: Alignment.bottomCenter,
           child: TestTab(
             // don't pass the controller
             onTabItemSelected: onTabItemSelected, // pass the function instead
           ), 
         ),

         MotionTabBarView(
           controller: _eduTabController,
           // ...
         ),

    //...
  }

}
// This should be a StatelessWidget (because it has no state)
// Change to StatefulWidget if your requirements change
class TestTab extends StatefulWidget {
  final Function onTabItemSelected;

  TestTab({this.onTabItemSelected}); // receive your function here

  @override
  Widget build(BuildContext context) {
    return MotionTabBar(
      // ...

      onTabItemSelected: onTabItemSelected, // use the function here

      // ...
    );
  }
}