我正在尝试在 OverlayEntry 中显示一些小部件,例如 CheckBox 或 Switch。叠加层是在点击事件中构建的。问题是 bool _value 仅在我第一次点击覆盖层内的 CheckBox 时更新,但 CheckBox 不会更新其状态。奇怪的是(仅第一次点击)点击更新了覆盖层外的复选框,而不是覆盖层内的复选框。我在这里错过了什么?
下面是一个完整的片段来重现这一点。
谢谢你的时间!
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _value = true;
_buildOverlay() {
OverlayEntry _overlayEntry;
OverlayState _overlayState = Overlay.of(context);
_overlayEntry = OverlayEntry(
builder: (BuildContext context) {
return Stack(
children: <Widget>[
Material(
child: Container(
padding: EdgeInsets.all(100),
color: Colors.lightBlue,
child: Checkbox(
value: _value,
onChanged: (bool value) { print("$value $_value"); setState(() => _value = value); },
),
),
),
],
);
},
);
_overlayState.insert(_overlayEntry);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(""),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
children: <Widget>[
FloatingActionButton(
onPressed: () {_buildOverlay();},
child: Icon(Icons.add),
),
Checkbox(
value: _value,
onChanged: (bool value) { print("$value $_value"); setState(() => _value = value); },
),
],
),
],
),
),
);
}
}
更新:
除了 anmol.majhail 解决方案,使用ValueListenableBuilder可能是另一种解决方案,而无需执行 StatefulWidget。
的声明_value变为:
var _value = ValueNotifier<bool>(false);
这里是 _buildOverlay() 函数中的 _overlayEntry:
_overlayEntry = OverlayEntry(
builder: (BuildContext context) {
return Material(
child: Container(
padding: EdgeInsets.all(100),
color: Colors.lightBlue,
child: ValueListenableBuilder<bool>(
valueListenable: _value,
builder: (context, value, child) {
return Checkbox(
value: _value.value,
onChanged: (bool value) {
print("$value $_value");
setState(() => _value.value = value);
},
);
},
),
),
);
},
);