Flutter:使用 ImagePicker 插件选取图像后如何导航到新页面?

Flutter: How do i navigate to a new page after an image is picked with the ImagePicker plugin?

我正在使用图像选择器插件来选择图像。我想在选择图像后立即导航到新屏幕,但它不起作用。我收到一条错误消息,指出上下文在当前小部件树中不存在。

下面是我的代码。

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

像这样调用函数:

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 完全从堆栈中移除,您的代码就可以工作,但事实并非如此,因此您的代码的其余部分在小部件准备好之前就结束了 运行。

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

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

    }
  }