提问人:Eng.ALi 提问时间:10/18/2023 更新时间:11/1/2023 访问量:51
推送返回的 Null 值
Null value return from push
问:
当我点击按钮时 该值是 Navigator.push() - 方法的返回值。 “因为按下返回 null 的 Button 不会使 Future 变为 null,而是它的内容。这导致了无意的行为”
在此处输入图像描述 主屏幕
PopupMenuButton(
icon: Icon(Icons.more_vert,color: Colors.black,),
offset: Offset(0, 40),
itemBuilder: (context) => [
PopupMenuItem(
child: Text('View Cart'),
onTap: () async {
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CartScreen(cart: cart)),
) ;
if(result)
{
setState(() {
});
}
},
),
购物车屏幕
WillPopScope(
onWillPop: () {
Navigator.pop(context,true);
return new Future(() => false);;
},
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
iconTheme: IconThemeData(color: Colors.black),
elevation: 0,
),
当我单击按钮导航页面时
答:
例如,我有这样的例子:
主页
await Navigator.of(context).pushNamed(
PageNames.routeTest,
).then(
(result) {
if (result != null && result as bool) {
[...do something...]
}
}
},
);
测试页面
可能只是一个
/// Could be just like :
Navigator.of(context).pop(true);
/// Or
onWillPop: () {
Navigator.of(context).pop(true);
return true;
},
尝试在以后使用函数并使用。告诉我这是否有效.then
Navigator.of(context).pop
Flutter 无法识别 的类型,并将其转换为 。为了避免这种情况,我建议您更改以下内容:result
dynamic
final result = await Navigator.push(
context,
MaterialPageRoute<bool>(
builder: (context) => CartScreen(cart: cart)),
) ;
if(result == null) return ...;
if(result)
{
setState(() {
...
});
具体而言,明确指定 的返回类型并在 is 时实现某些内容。MaterialPageRoute
return
null
我正在尝试使用onSelected属性
PopupMenuButton<int>(
onSelected: (result) {
if (result == 1) {
nav(context, snap.data![index]);
}
},
icon: Icon(Icons.more_vert_outlined),
itemBuilder: (context) => [
PopupMenuItem(
onTap: () async {
},
value: 1,
child: Text("Edit")),
PopupMenuItem(
onTap: () async {
Map<String, dynamic>? res = await api
.deletepost(snap.data![index].id!);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.amber,
content:
Text(
" ${snap.data![index].id} isdeleted ")));
},
value: 2,
child: Text("Delete")),
],
),
nav(BuildContext context, TODO td) async {
API api = API();
List<dynamic>? data = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UpdateTodo(
td: td,
)));
print(data);
if (data != null) {
var res = await api.updatePost(data);
print(res);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(backgroundColor: Colors.amber, content: Text("Edit
succes")));
}
}
注意: 弹出路线 路线不必遮挡整个屏幕。[PopupRoute] 使用 [ModalRoute.barrierColor] 覆盖屏幕,该屏幕只能部分不透明以允许当前屏幕显示。弹出路由是“模态”的,因为它们会阻止对以下小部件的输入。
有一些函数可以创建和显示弹出路由。例如:[showDialog]、[showMenu] 和 [showModalBottomSheet]。如上所述,这些函数返回其推送路由的 Future。调用方可以等待返回的值,以便在弹出路由时执行操作,或发现路由的值。enter code here
还有一些小部件可以创建弹出路由,例如 [PopupMenuButton] 和 [DropdownButton]。这些小部件创建 PopupRoute 的内部子类,并使用 Navigator 的 push 和 pop 方法来显示和关闭它们。
上一个:发现意外的 null 值
下一个:如何正确显示 JSON 记录
评论