gpt4 book ai didi

flutter - 获取 "' 上下文 != null' : is not true"error when trying to showDialogue after a MaterialPageRoute in Flutter?

转载 作者:行者123 更新时间:2023-12-03 03:09:31 25 4
gpt4 key购买 nike

我目前可以将 MaterialRoute 从 Flutter 中的 Home App 路由到页面,并显示一个弹出对话框。但是,从第二页路由到第三页(其中包含一个应该显示对话的按钮)时,我收到此错误:[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: 'package:flutter/src/widgets/localizations.dart': Failed assertion: line 446 pos 12: 'context != null': is not true.

触发该错误的 showDialogue 如下所示:


class ThirdPageWidgetState extends State<ThirdPageWidget> {

StreamSubscription<ScanResult> scanSubscription;

@override
void initState() {
super.initState();
}
Future<void> alert(deviceName) async {
return showDialog<void>(
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: Text('Button Pressed!'),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('test'),
],
),
),
actions: <Widget>[
FlatButton(
child: Text('Ok'),
),
],
);
},
);
}

'Build function omitted'
}

第二页到第三页的路由如下所示:
void routeAppToThirdPage() async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ThirdPageWidget(),
),
);
}

最佳答案

标准 Flutter 对话框需要 BuildContext。您可以按参数发送,您将不再有错误。但是,如果您想节省开发时间或不喜欢按参数发送上下文的想法,您可以简单地使用这个库,它允许您从代码中的任何位置导航路线、打开对话框和 snackbar ,而无需上下文。

https://pub.dev/packages/get

在您的示例中,您的代码也会更精简:

要导航到下一条路线:

Get.to(ThirdPageWidget());

打开对话框:
   Get.dialog(
AlertDialog(
title: Text('Button Pressed!'),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('test'),
],
))),
barrierDismissible: false,
);

关于flutter - 获取 "' 上下文 != null' : is not true"error when trying to showDialogue after a MaterialPageRoute in Flutter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61297219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com