我只是在玩 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但我不确定如何让 Provider 控制我的 eduTabController,因为除了 TestTab.dart 本身之外,我无法在任何地方初始化它。
最佳答案
自 controller
MotionTabView
中需要而不是 MotionTabBar
移动_eduTabController
至Education
类(class)。现在定义选项卡选择所需的函数,即 onTabItemSelected
在Education
类并将其作为参数传递给 TestTab
.
这样您就可以避免 _eduTabController
在TestTab
并在 MotionTabView
中使用它存在于 Education
.
这是一个粗略的实现:
// 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
// ...
);
}
}
关于flutter - 将 Provider 与 TickerProviderStateMixin 一起使用 : Where can I initialise my controller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63202933/