【问题标题】:Store Image in List<Xfile> from image urls从图像 url 将图像存储在 List<Xfile> 中
【发布时间】:2022-09-27 13:04:46
【问题描述】:

我创建了一个变量

List<Xfile> imageList;

使用这个变量,我在 GridView.Builder 中显示了选定的图像并上传了它们。

但我想将这些上传的图像存储在这个列表中,以便在 GridView.Builder 中再次显示它们。

表示如何将 imageUrls 中的图像存储在 List 中

我怎样才能做到这一点?

    标签: flutter api rest


    【解决方案1】:

    如下:

    变量

        final picker = ImagePicker();
     File? file;
      XFile? pickedImage;
      bool isLoading = false;
      List<File?> fileList = [];
    

    从图库中选择图像的方法

    Future pickImageFromGallery() async {
        pickedImage = await picker.pickImage(source: ImageSource.gallery);
        setState(() {
          file = File(pickedImage!.path);
          fileList.add(file);
        });
      }
    

    并按如下方式放置在gridview中:

    GridView.builder(
        itemCount: fileList.length,
      
        gridDelegate:
            const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
        itemBuilder: (BuildContext context, int i) {
          return Container(
            padding: const EdgeInsets.all(10),
            child: Stack(
              children: <Widget>[
                SizedBox(
                  height: 100,
                  width: 100,
                  child: Image.file(File(fileList[i]!.path),fit: BoxFit.cover,),
                ),
                Positioned(
                    right: 1,
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          dltImages(fileList[i]);
                        });
                      },
                      child: const Icon(Icons.cancel, color: Colors.red),
                    ))
              ],
            ),
          );
        },
      ),
    

    在以下位置找到完整代码: https://github.com/nbnD/image_picker_flutter/blob/master/lib/homepage.dart

    【讨论】:

    • 这个答案的坦克,但这不是我如何选择图像并在网格视图中显示的问题。我想知道如何从网格视图中的 rest api 再次检索这些图像并更新它们。我想我必须从 rest api 中检索这些图像并将它们分配给 List<File?> fileList 变量,然后它们将直接显示在网格视图构建器中。请帮助我。非常感谢。
    【解决方案2】:

    如果有多张图片上传,我会喜欢这个

    class PickImagesPage extends StatefulWidget {
      const PickImagesPage({super.key, required this.initialUrls});
      final List<String> initialUrls;
      @override
      State<PickImagesPage> createState() => _PickImagesPageState();
    }
    
    class _PickImagesPageState extends State<PickImagesPage> {
      @override
      void initState() {
        urls = widget.initialUrls;
        super.initState();
      }
    
      List<String> urls = [];
      List<File> files = [];
      List<String> removedUrls = [];
    
      final Repo repo = Repo();
      @override
      Widget build(BuildContext context) {
        final theme = Theme.of(context);
        final style = theme.textTheme;
        final scheme = theme.colorScheme;
        return LoadingLayer(
          child: Scaffold(
            bottomNavigationBar: Padding(
              padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
              child: ElevatedButton(
                onPressed:
                    files.isNotEmpty || widget.initialUrls.length != urls.length
                        ? () async {
                            try {
                              await repo.uploadImages(
                                files: files,
                                urls: urls,
                                removedUrls: removedUrls,
                              );
                              Navigator.pop(context);
                            } catch (e) {
                              AppSnackbar(context).error(e);
                              if (kDebugMode) {
                                print(e);
                              }
                            }
                          }
                        : null,
                child: const Text(Labels.save),
              ),
            ),
            appBar: AppBar(
              title: const Text(
                Labels.ambienceImages,
              ),
            ),
            floatingActionButton: FloatingActionButton(
              onPressed: () async {
                final List<XFile> pickedFiles = await pickImages();
                if (pickedFiles.isNotEmpty) {
                  setState(() {
                    files.addAll(pickedFiles.map((e) => File(e.path)));
                  });
                }
              },
              child: const Icon(Icons.add),
            ),
            body: GridView.count(
              padding: const EdgeInsets.all(12),
              crossAxisCount: 2,
              mainAxisSpacing: 12,
              crossAxisSpacing: 12,
              children: [
                ...urls
                    .map(
                      (e) => GestureDetector(
                        onTap: () {
                          setState(() {
                            urls.remove(e);
                            removedUrls.add(e);
                          });
                        },
                        child: Container(
                          clipBehavior: Clip.antiAlias,
                          decoration: BoxDecoration(
                            color: scheme.surfaceVariant.withOpacity(0.5),
                            borderRadius: BorderRadius.circular(20),
                            image: DecorationImage(
                              image: NetworkImage(e),
                            ),
                          ),
                        ),
                      ),
                    )
                    .toList(),
                ...files
                    .map(
                      (e) => Container(
                        clipBehavior: Clip.antiAlias,
                        alignment: Alignment.topRight,
                        decoration: BoxDecoration(
                          color: scheme.surfaceVariant.withOpacity(0.5),
                          borderRadius: BorderRadius.circular(20),
                          image: DecorationImage(
                            image: FileImage(e),
                          ),
                        ),
                        child: SizedBox(
                          height: 40,
                          width: 40,
                          child: RawMaterialButton(
                            elevation: 0,
                            focusElevation: 0,
                            hoverElevation: 0,
                            shape: const CircleBorder(),
                            fillColor: theme.cardColor.withOpacity(0.5),
                            onPressed: () {
                              setState(() {
                                files.remove(e);
                              });
                            },
                            child: const Icon(Icons.remove),
                          ),
                        ),
                      ),
                    )
                    .toList(),
                GestureDetector(
                  onTap: () async {
                    final List<XFile> pickedFiles = await pickImages();
                    if (pickedFiles.isNotEmpty) {
                      setState(() {
                        files.addAll(pickedFiles.map((e) => File(e.path)));
                      });
                    }
                  },
                  child: Container(
                    clipBehavior: Clip.antiAlias,
                    decoration: BoxDecoration(
                      color: scheme.surfaceVariant.withOpacity(0.5),
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Stack(
                      children: const [
                        Center(
                          child: Icon(Icons.add),
                        ),
                        PickImageLabel(),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    }
    
    class Repo {
      Future<void> uploadImages(
          {required List<String> urls,
          required List<File> files,
          required List<String> removedUrls}) async {
        List<String> newUrls = [];
        for (var file in files) {
          final url = await upload(file);
          newUrls.add(url);
        }
        for (var url in removedUrls) {
          await deleteImage(url);
        }
        await saveImages(urls + newUrls);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-25
      • 2022-12-12
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      • 2014-06-20
      • 2015-02-28
      • 2019-07-24
      • 2019-03-10
      相关资源
      最近更新 更多