关于 dart:Flutter:如何在使用 ImagePicker 插件选择图像后导航到新页面?

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.)


问题是,如果小部件未构建在屏幕上(已安装),则无法使用 context。因此,您应该在小部件处于活动状态时存储对导航器的引用,然后您就不需要引用 context
如果 ImagePicker.pickImage() 等到它的 Route 完全从堆栈中删除,您的代码将工作,但它没有,因此您的其余代码最终在小部件准备好之前运行。

我对您的代码进行了一些修改。这应该可以解决您的问题:

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,
                ),
          ),
        );

    }
  }