Flutter: How do i navigate to a new page after an image is picked with the ImagePicker plugin?
我正在使用图像选择器插件来选择图像。我想在选择图像后立即导航到新屏幕,但它不起作用。我收到一个错误,指出当前小部件树中不存在上下文。
下面是我的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | pickImage(BuildContext context) async { File pickedImage = await ImagePicker.pickImage(source: ImageSource.camera); if (pickedImage != null) { print(pickedImage.path); if (this.mounted) { await Navigator.of(context).push( MaterialPageRoute( builder: (context) => ViewStory( localImagePath: pickedImage.path, ), ), ); } } } |
这样调用函数:
1 2 3 4 5 6 7 8 | IconButton( onPressed: () => pickImage(context), icon: Icon( Icons.camera_alt, color: CustomColors.primary, size: 100, ), ), |
以下是我得到的错误:
FlutterError (Looking up a deactivated widget's ancestor is unsafe. At
this point the state of the widget's element tree is no longer stable.
To safely refer to a widget's ancestor in its dispose() method, save a
reference to the ancestor by calling inheritFromWidgetOfExactType() in
the widget's didChangeDependencies() method.)
问题是,如果小部件未构建在屏幕上(已安装),则无法使用
如果
我对您的代码进行了一些修改。这应该可以解决您的问题:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | pickImage(BuildContext context) async { final navigator = Navigator.of(context); File pickedImage = await ImagePicker.pickImage(source: ImageSource.camera); if (pickedImage != null) { print(pickedImage.path); await navigator.push( MaterialPageRoute( builder: (context) => ViewStory( localImagePath: pickedImage.path, ), ), ); } } |