0

我的应用程序中有以下小部件:

 @override
  Widget build(BuildContext context) {

        return Scaffold(

          bottomNavigationBar: BottomAppBar(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
               
                IconButton(
                  icon: Icon(
                    Icons.photo_library,
                    size: 30,
                  ),
                  onPressed: () => _pickImage(ImageSource.gallery),
                  color: Colors.pink,
                ),
              ],
            ),
          ),
          body: ListView(
            children: <Widget>[
              if (_imageFile != null) ...[
                Container(
                    padding: EdgeInsets.all(32),
                    child: Image.file(_imageFile)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                   
                    FlatButton(
                      color: Colors.blue,
                      child: Icon(Icons.arrow_forward_ios),
                      onPressed: () =>
                          Get.toNamed(
                            AppRoutes.OCR_DETAILS,
                            arguments: {'image': _imageFile},
                          ),
                    ),
                  ],
                ),
              ]
            ],
          )
        );
      }

和以下功能来选择图像:

Future _pickImage(ImageSource source) async {
    File selected = await ImagePicker.pickImage(source: source);
      _imageFile = selected;
      _imageLoaded=true;
  }

我想导入文件(_imageFile)并在导入后将其显示在当前小部件上。我想使用 GetX 库。非常感谢您的帮助。

4

1 回答 1

0

编辑:切换到从画廊而不是相机中选择。仅供参考pickImage,该软件包已被弃用,因此我们getImage改为使用该软件包。

设置一个 ImageController GetX 类。

class ImageController extends GetxController {
  File image;
  final picker = ImagePicker();

  Future<void> getImage() async {
    final pickedFile = await picker.getImage(source: ImageSource.gallery);

    if (pickedFile != null) {
      image = File(pickedFile.path);
    } else {
      print('No image selected.');
    }
    update();
  }
}

初始化控制器,您可以在 main 或 build 方法中进行。在运行应用程序之前,让我们在 main 中执行此操作。

Get.lazyPut<ImageController>(() => ImageController(), fenix: true);

然后在您的页面上,您可以找到控制器。

final controller = Get.find<ImageController>();

onPressed您的按钮中触发getImageImageController 类中的方法

controller.getImage();

然后在你的 UI 中任何需要它的地方,只要把它扔在那里,你就可以开始了。

      GetBuilder<ImageController>(
                  builder: (_) {
                    return controller.image != null
                        ? Image.file(controller.image)
                        : Container();
                  },
                ),
于 2021-02-18T18:00:51.403 回答