我有一个String
,它应该在单击Future
showModalBottomSheet
中的按钮后返回。下面是我如何实现它以及它是如何工作的:
onPressed: () async {
String? returnString = await showModalBottomSheet<String>(
context: context,
isDismissible: false,
builder: (ctx) {
return StatefulBuilder(builder: (ctx, setState) {
return Container(
margin: EdgeInsets.all(10),
padding: EdgeInsets.all(10),
child: ElevatedButton(
onPressed: (){
Navigator.pop(ctx, "This is return string bla bla bla");
},
child: Text("Click Me To Return"),
),
);
});
},
);
Logger().i("PrintReturnString: $returnString");
Logger().i("PrintReturnStringRunTimeType: ${returnString.runtimeType}");
}
但是,因为我想在几个地方使用它,而且我不想重复自己,每次在其他类中重写代码都是多余的,所以我决定尝试使用全局方法来实现它,但是它不能工作,所以只返回null而不是String
。
这是返回字符串bla bla bla
下面是我如何尝试使用类中任何地方都可以调用的方法来实现它:
showReturnStringBottomSheet(ctx) async {
await showModalBottomSheet<String>(
context: ctx,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(25))),
elevation: 5,
isDismissible: true,
isScrollControlled: true,
builder: (ctx) {
return StatefulBuilder(builder: (ctx, setState) {
return Container(
margin: EdgeInsets.all(10),
padding: EdgeInsets.all(10),
child: ElevatedButton(
onPressed: (){
Navigator.pop(ctx, "This is return string bla bla bla");
},
child: Text("Click Me To Return"),
),
);
});
}
);
}
下面是我如何调用该方法:
onPressed: () async {
String? returnString = await showReturnStringBottomSheet(context);
}
我做错什么了吗?因为它只是在我将方法直接放在onPressed
中时起作用,但是当我使用全局方法时,它就停止工作了。
发布于 2022-10-05 09:08:50
showModalBottomSheet
是一个async
方法,所以您应该等待它,然后它使showReturnStringBottomSheet
成为一个future
函数,尝试如下:
Future<String?> showReturnStringBottomSheet(ctx) async {
var result = await showModalBottomSheet<String>(
context: ctx,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(25))),
elevation: 5,
isDismissible: true,
isScrollControlled: true,
builder: (ctx) {
return StatefulBuilder(builder: (ctx, setState) {
return Container(
margin: EdgeInsets.all(10),
padding: EdgeInsets.all(10),
child: ElevatedButton(
onPressed: () {
Navigator.pop(ctx, "This is return string bla bla bla");
},
child: Text("Click Me To Return"),
),
);
});
});
return result;
}
像这样使用它:
onPressed: () async {
String? returnString = await showReturnStringBottomSheet(context);
if(returnString != null){
print("returnString = $returnString");
}
}
https://stackoverflow.com/questions/73957962
复制相似问题