我在StatefulWidget中有一个底部导航栏,并带有一个对话框,其中有3个选项可打开相机,图库或取消。
这是我的代码:导航栏
Widget build(BuildContext context) {
return new Scaffold(
body: PageView(
children: [
Container(
color: Colors.white,child: HomePage(),),
Container(
color: Colors.white,child: AddPost(),),
],
controller: pageController,
physics: NeverScrollableScrollPhysics(),
onPageChanged: onPageChanged,
),
bottomNavigationBar: CupertinoTabBar(
backgroundColor: Colors.white,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home,
title: Container(height: 0.0),
backgroundColor: Colors.white),
BottomNavigationBarItem(
icon: Icon(Icons.add_circle,
title: Container(height: 0.0),
)
],
onTap: navigationTapped,
currentIndex: _page,
),
);
}
对话
File file;
_selectImage( ) async {
return showDialog<Null>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return SimpleDialog(
title: const Text('Create a Post'),
children: <Widget>[
SimpleDialogOption(
child: const Text('Take a photo'),
onPressed: () async {
Navigator.pop(context);
File imageFile =
await ImagePicker.pickImage(source: ImageSource.camera, maxWidth: 1920, maxHeight: 1200, imageQuality: 80);
setState(() {
file = imageFile;
});
}),
SimpleDialogOption(
child: const Text('Choose from Gallery'),
onPressed: () async {
Navigator.of(context).pop();
File imageFile =
await ImagePicker.pickImage(source: ImageSource.gallery, maxWidth: 1920, maxHeight: 1200, imageQuality: 80);
setState(() {
file = imageFile;
});
}),
SimpleDialogOption(
child: const Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
)
],
);
},
);
}
我想做这样的事情,我可以打开对话框,但是没有等到选择了该选项,然后才开始
void navigationTapped(int page) async{
if(page != 1){
pageController.jumpToPage(page);
}else{
await _selectImage(); //opens dialog
}
//Handle button tap
}
我该如何等待用户点击导航栏上的选项?
提前感谢!
在_selectImage
函数中,您可以等待对话框关闭以执行如下代码:
await showDialog(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return SimpleDialog(
title: const Text('Create a Post'),
children: <Widget>[
SimpleDialogOption(
child: const Text('Take a photo'),
onPressed: () async {
Navigator.pop(context);
File imageFile = await ImagePicker.pickImage(source: ImageSource.camera, maxWidth: 1920, maxHeight: 1200, imageQuality: 80);
setState(() {
file = imageFile;
});
}),
SimpleDialogOption(
child: const Text('Choose from Gallery'),
onPressed: () async {
Navigator.of(context).pop();
File imageFile = await ImagePicker.pickImage(source: ImageSource.gallery, maxWidth: 1920, maxHeight: 1200, imageQuality: 80);
setState(() {
file = imageFile;
});
}),
SimpleDialogOption(
child: const Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
)
],
);
},
).then((onValue) {
if (onValue != null) {
/// Code you want to do
}
});
onValue
可以使用此功能设置:
Navigator.pop(context, valueYouWantToReturn);
如果即使onValue
为空(Navigator.pop(context)
)也要执行一些代码,则删除条件