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

Omo*_*o4i 2 dart flutter flutter-dependencies imagepicker

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

下面是我的代码。

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,
            ),
          ),
        );
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样调用该函数:

IconButton(
              onPressed: () => pickImage(context),
              icon: Icon(
                Icons.camera_alt,
                color: CustomColors.primary,
                size: 100,
              ),
            ),
Run Code Online (Sandbox Code Playgroud)

以下是我收到的错误:

FlutterError(查找已停用的小部件的祖先是不安全的。此时小部件的元素树的状态不再稳定。要在其 dispose() 方法中安全地引用小部件的祖先,请通过调用inheritFromWidgetOfExactType(保存对祖先的引用) )在小部件的 didChangeDependency() 方法中。)

Thi*_*tal 6

问题是,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,
                ),
          ),
        );

    }
  }
Run Code Online (Sandbox Code Playgroud)