【问题标题】:Flutter: How do I select and display imagesFlutter:如何选择和显示图像
【发布时间】:2021-10-08 08:10:57
【问题描述】:

我无法在网格中显示从图库中选择的图像。在这段代码中,我在列表中显示图像,我想将它变成 1 行中的小网格类型,但我不知道如何。你能帮忙吗?

这是我使用文件选择器选择多个图像的代码。

FileType fileType;
String imgName, _imgPath;
Map<String, String> imgPaths;
List<File> _imgList = List();
bool isLoadingPath = false;


  _openFile() async {
setState(() => isLoadingPath = true);
try {
  _imgPath = null;
  imgPaths = await FilePicker.getMultiFilePath(
      type: fileType != null ? fileType : FileType.custom,
      allowedExtensions: ['jpg', 'png']);

  _imgList.clear();

  imgPaths.forEach((key, val) {
    print('{ key: $key, value: $val}');
    File file = File(val);
    _imgList.add(file);
  });

} on PlatformException catch (e) {
  print("Unsupported operation" + e.toString());
}
if (!mounted) return;
setState(() {
  isLoadingPath = false;
  imgName = _imgPath != null
      ? _imgPath.split('/').last
      : imgPaths != null
      ? imgPaths.keys.toString()
      : '...';
});
}

在列表中显示图像。 (如何按原样显示图像?)

Widget _fileBuilder() {
return Builder(
  builder: (BuildContext context) => isLoadingPath
      ? Padding(
      padding: const EdgeInsets.only(bottom: 4.0))
      : _imgPath != null || imgPaths != null && (imgPaths.length > 1 && imgPaths.length < 5)
      ? new Container(
    height: imgPaths.length > 1
        ? MediaQuery.of(context).size.height * 0.15
        : MediaQuery.of(context).size.height * 0.10,
    width: MediaQuery.of(context).size.width,
    child: new Scrollbar(
        child: new ListView.separated(
          itemCount: imgPaths != null && imgPaths.isNotEmpty
              ? imgPaths.length
              : 1,
          itemBuilder: (BuildContext context, int index) {
            final bool isMultiPath = imgPaths != null && imgPaths.isNotEmpty;
            final int fileNo = index + 1;
            final String name = 'File $fileNo : ' + (isMultiPath
                ? imgPaths.keys.toList()[index]
                : _imgPath ?? '...');
            final filePath = isMultiPath
                ? imgPaths.values.toList()[index].toString()
                : _imgPath;
            return new ListTile(
              title: Transform.translate(
                offset: Offset(-25, 0),
                child: new Text(
                  name,
                ),
              ),
              leading: Icon(Icons.attach_file_outlined, color: Color(0xFFF3A494),),
              dense: true,
            );
          },
          separatorBuilder:
              (BuildContext context, int index) =>
          new Divider(),
        )),
  )
      : new Container(child: Text('4 photos is the maximum'),),
);
}

依赖关系:

file_picker: ^1.4.2
path:
mime:
async:

【问题讨论】:

    标签: image flutter file-upload gridview grid


    【解决方案1】:

    您可以做的是,使用 Image Picker 依赖项。您可以在 pub.dev 上找到它的文档。安装后,尝试使用它并将上传的图像存储在设备中的文件中。并使用该文件名,您可以访问图像。 你可以试试下面的代码,它对我有用。也不要忘记import dart:io; 使用文件。

    var _storedImage;
    
      Future<void> _takePictureByCamera() async {
        final picker = ImagePicker();
        final imageFile =
            await picker.getImage(source: ImageSource.camera, maxWidth: 600, imageQuality: 60);
    
        setState(() {
          _storedImage = File(imageFile!.path);
        });
    
        final appDir = await path_provider.getApplicationDocumentsDirectory();
        final fileName = path.basename(imageFile!.path);
        final savedImage = File(imageFile.path).copy('${appDir.path}/$fileName');
    
        widget.onSelectImage(savedImage);
      }
    
      Future<void> _takePictureByGallery() async {
        final picker = ImagePicker();
        final imageFile =
            await picker.getImage(source: ImageSource.gallery, maxWidth: 600);
    
        if (imageFile == null) {
          return;
        }
    
        setState(() {
          _storedImage = File(imageFile.path);
        });
    
        final appDir = await path_provider.getApplicationDocumentsDirectory();
        final fileName = path.basename(imageFile.path);
        final savedImage = File(imageFile.path).copy('${appDir.path}/$fileName');
    
        widget.onSelectImage(savedImage);
      }
    

    在选择或点击图片后,您可以这样做以显示图片 ->

    void getImage() async {
        final pickedImage = await showModalBottomSheet(
          context: accountTabScaffoldMessengerKey.currentContext!,
          backgroundColor: Colors.transparent,
          enableDrag: true,
          // elevation: 0,
          builder: (context) => AccountImageUpdateBottomSheet(_selectImage),
        );
        _selectImage(pickedImage);
      }
    
      void _selectImage(File pickedImage) {
        setState(() {
          _pickedImage = pickedImage;
        });
      }
    

    您选择的图像存储在_pickedImage中,您可以通过Image.file(_pickedImage)访问它。

    【讨论】:

    • 谢谢!我会试试看:)
    猜你喜欢
    • 2021-11-19
    • 2020-09-18
    • 1970-01-01
    • 2023-01-04
    • 2018-04-07
    • 2020-12-20
    • 2018-07-05
    • 2014-03-11
    • 1970-01-01
    相关资源
    最近更新 更多