我有 2 个相同小部件的实例(w1 和 w2),带有一个按钮和一个 onPressed 函数。我知道通过设置空值来禁用 onPress,到目前为止一切顺利。手头的问题是解决如何在单击 w1 时禁用 w2 onPress 并在再次单击时重新启用它。
即使我发送了一个包含 if widget 已按下的变量,禁用也不会发生,因为我无法从外部(包含我的 2 个实例的 Widget)分别触发每个小部件的 setState。
答案 0 :(得分:1)
您有几个解决方案。您可以使用更复杂的状态管理系统(例如 Provider 或 Bloc),但尝试“提升状态”可能更简单。
“提升状态”是指从子节点中拉出状态并将其移动到父节点。
不是让孩子有状态,他们可以变成无状态,包含它们的小部件将成为有状态的,并会跟踪哪些按钮已启用,哪些未启用。
// example button, actual implementation may be different
class MyButton extends StatelessWidget {
final VoidCallback? onPressed;
final String text;
const MyButton({Key? key, this.onPressed, required this.text,}) : super(key: key);
@override
Widget build(BuildContext context) => ElevatedButton(
onPressed: onPressed,
child: Text(text),
);
}
class ButtonContainer extends StatefulWidget {
// boilerplate
}
class ButtonContainerState extends State<ButtonContainer> {
bool isSecondButtonEnabled = true;
void toggleSecondButton() => setState(() => isSecondButtonEnabled = !isSecondButtonEnabled);
@override
Widget build(BuildContext context) => Row(
children: [
MyButton(
text: "Button 1",
onPressed: toggleSecondButton,
),
MyButton(
text: "Button 2",
onPressed: isSecondButtonEnabled ? someOtherFunction : null,
)
],
);
}