我需要将值
isBottomBarVisible
从A类传递到B类。如果isBottomBarVisible
为true,则将其与顶部中心对齐;否则,将其与 Flutter 中的中心对齐。
class ClassA extends StatelessWidget {
bool isBottomBarVisible = false;
@override
Widget build(BuildContext context) {
// Create an instance of ClassA
return Container(
// Your UI widgets here
);
void _showBottomSheet() {
setState(() {
isBottomSheetVisible = true;
});
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return Container(
height: 200,
child: Center(
child: Text("This is a bottom sheet"),
),
);
},
).whenComplete(() {
setState(() {
isBottomSheetVisible = false;
});
});
}
}
}
class ClassB extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
// Your UI widgets here
child: AnimatedContainer(
duration: Duration(milliseconds: 500),
alignment: isKeyboardVisible || isBottomSheetVisible // how to get value
? Alignment.topCenter
: Alignment.center,
);
}
}
解决问题的唯一方法是使用状态管理器; 有很多状态管理器,例如 Bloc、Riverpod、Getx 等等......
我建议您使用 flutter-bloc(cubit) 作为状态管理器,因为它简单且组织良好,但如果您想使用简单且更易于访问的状态管理器,请使用 getx。
如果您有任何疑问,请告诉我。
在这种情况下,状态管理是你的朋友。 您可以实现任何您想要的状态管理(Bloc、GetX 等)来实现此目标。
如果您不关心设计模式或类似的东西,您可以在 GetX 中实现最简单的反应式小部件(Obx 与 Rx)。
示例:
class AppGlobalRxService {
static RxBool isBottomSheetVisible = false.obs;
}
在小部件中的使用
Obx(() => Container(
color: AppGlobalRxService.isBottomSheetVisible.value ? Colors.red : Colors.blue,
))
更新变量将触发 UI 中
Obx
的重建。
AppGlobalRxService.isBottomSheetVisible.value = true
注意:考虑为您的项目设计最合适的文件和服务结构。上面的代码只是一个例子。
如果两个类都在一个文件中,您可以使用全局变量来解决您的问题。如果没有,则使用参数构造函数或静态变量(MaterialPageRoute)
更新你的 ClassB 代码,添加结构
class ClassB extends StatelessWidget {
final bool isBottomSheetVisible;
const ClassB({
super.key,
required this.isBottomSheetVisible,
});
@override
Widget build(BuildContext context) {
return Container(
// Your UI widgets here
child: AnimatedContainer(
duration: Duration(milliseconds: 500),
alignment: isKeyboardVisible || isBottomSheetVisible // how to get value
? Alignment.topCenter
: Alignment.center,
),
);
}
}
现在,无论您在何处调用 ClassB,例如在将 ClassA 导航到 ClassB 时,您都必须像这样传递 ClassB 中的值 - ClassB(isBottomSheetVisible: isBottomSheetVisible).
这样你的 isBottomSheetVisible 值从 A 传递到 B。