我想知道为什么 showDialog 没有在稍微不同的上下文中显示,似乎在很多情况下,路线上的几层上下文不应阻止对话框的显示。特别是在显式传递导航器上下文时。以下是最小的可重复样本。我也尝试过使用
最终的全局密钥?导航键
并经过
navigatorKey.currentContext
到 showDialog 方法,这也不起作用。我知道这可能是因为 itemBuilder 中的上下文,但是有人对为什么 onTap 不会显示对话框有更好的解释吗?
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:PopupMenuButton(
icon: Icon(Icons.more_vert),
onSelected: (value){
if (value == "val1") {
// works
// showADialog(context);
}
if (value == "val2"){
showADialog(context);
}
},
itemBuilder: (context) {
return [
PopupMenuItem(
onTap: (){
// doesn't work
showADialog(context);
},
value: "val1",
child: Text("val1")),
PopupMenuItem(
value:"val2",
child: Text("val2"))
];
})
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
showADialog(BuildContext context){
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("A Dialog"));});
}
通过这种方式传递上下文;
return Scaffold(
body: Center(
child: PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
onSelected: (value) {
if (value == "val2") {
showPopupDialog(context);
}
},
itemBuilder: (context) {
return [
PopupMenuItem(
value: "val1",
child: GestureDetector(
onTap: () => showPopupDialog(context), // Pass context here
child: const Text("val1"),
),
),
const PopupMenuItem(
value: "val2",
child: Text("val2"),
),
];
},
),
),
);