我有一個使用 a 中的值ChangeNotifierProvider來顯示螢屏內容的螢屏。正如預期的那樣,當這些值發生變化時,螢屏構建方法被觸發并更新螢屏內容。
我希望如果其中一個值從false變為true,則在該螢屏上打開一個對話框。
我想出打開此對話框的唯一方法是在值更改并呼叫新構建時從構建方法啟動它。
我知道這showDialog是一個異步方法,而 build 是同步的,它是一種從 build 方法內部管理這些副作用的反模式。我不知道何時會呼叫構建方法,這可能導致每次呼叫構建時都會打開幾個對話框。
因此,到目前為止,我只能從 build 方法打開對話框并使用記憶體中的布爾標志來控制對話框是否打開。像這樣:
class MyScreen extends StatefulWidget {
const MyScreen();
@override
State<StatefulWidget> createState() => _MyScreenState();
}
class _MyScreenState extends State<MyScreen> {
late final myModel = Provider.of<MyModel?>(context);
bool _isDialogShowing = false;
@override
void initState() {
super.initState();
...
}
void _showMyDialog(BuildContext ctx) {
showDialog(
context: ctx,
barrierDismissible: false,
builder: (context) => AlertDialog(
content: const Text("Hello I am a dialog"),
),
).then((val) {
// The dialog has been closed
_isDialogShowing = true;
});
}
@override
Widget build(BuildContext context) {
// Open dialog if value from `ChangeNotifierProvider` has changed
if (myModel?.hasToShowDialog == true && _isDialogShowing == false) {
_isDialogShowing = true;
Future.delayed(
Duration.zero,
() {
_showMyDialog(context);
},
);
}
return Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
children: [
.....
],
),
],
);
}
}
你知道當值改變時如何正確觸發對話框打開事件ChangeNotifierProvider嗎?非常感謝你!!!
uj5u.com熱心網友回復:
您可以做的是將偵聽器添加到您的ChangeNotifier:
late final myModel = Provider.of<MyModel?>(context);
bool _isDialogShowing = false;
@override
void initState() {
super.initState();
myModel.addListener(_showDialog);
}
@override
void dipose() {
myModel.removeListener(_showDialog);
super.dispose();
}
Future<void> _showDialog() async {
if (_isDialogShowing || !mounted) return;
// `hasToShowDialog` could be a getter and not a variable.
if (myModel?.hasToShowDialog != true) return;
_isDialogShowing = true;
await showDialog(
context: context,
barrierDismissible: false,
builder: (context) => AlertDialog(
content: const Text("Hello I am a dialog"),
),
);
_isDialogShowing = false;
}
我不知道你的MyModel樣子,所以很難知道你還能做什么。hasToShowDialog正如您在問題中建議的那樣,可能是吸氣劑而不是變數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/471926.html
