使用URL下载图像,但在Galery中没有显示

发布于 2025-01-18 12:43:17 字数 6278 浏览 0 评论 0 原文

我正在使用此依赖项 image_downloader: ^0.31.0 示例中的代码,问题是它没有显示任何错误,但图像不会进入图库。 此屏幕用于显示来自 firestore 的图像并创建列表样式,当用户单击图像时应该下载它。

import 'dart:io';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:image_downloader/image_downloader.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:pap_test/upload/upload_resumos_screen.dart';

class DownloadScreen extends StatefulWidget {
  const DownloadScreen({Key? key}) : super(key: key);
  static const routeName = '/downlaod-resumos';

  @override
  State<DownloadScreen> createState() => _DownloadScreenState();
}

class _DownloadScreenState extends State<DownloadScreen> {
  String _message = "";
  String _path = "";
  String _size = "";
  String _mimeType = "";
  File? _imageFile;
  int _progress = 0;
  String query = '1';

  CollectionReference _firebaseFirestore =
      FirebaseFirestore.instance.collection('images');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Resumos'),
      ),
      body: StreamBuilder<QuerySnapshot>(
        stream: _firebaseFirestore.snapshots().asBroadcastStream(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: CircularProgressIndicator(),
            );
          } else {
            if (snapshot.data!.docs
                .where((QueryDocumentSnapshot<Object?>
                        element) =>
                    element['disciplina']
                        
                        .toString()
                        .toLowerCase()
                        
                        .contains(query.toLowerCase()))
                .isEmpty) {
              return Center(
                child: Text(
                  'Por aqui está muito lento, carrega no botão e publica um resumo.',
                  style: Theme.of(context).textTheme.headline5,
                  textAlign: TextAlign.center,
                ),
              );
            } else {
              return ListView(
                children: [
                  
                  ...snapshot.data!.docs
                      .where((QueryDocumentSnapshot<Object?>
                              element) => 
                          element['disciplina']
                              
                              .toString()
                              .toLowerCase()
                              
                              .contains(query.toLowerCase()))
                      .map(
                    (QueryDocumentSnapshot<Object?> data) {
                      
                      final String descricao = data.get('descricao');
                      
                      final _image = data['url'];
                      
                      return ListTile(
                        onTap: () {
                          _downloadImage(_image);
                          
                        },
                        
                        leading: CircleAvatar(
                          backgroundImage: NetworkImage(_image),
                        ),

                       
                        title: Text(
                          descricao.toString(),
                          style: Theme.of(context).textTheme.headline5,
                        ),
                      );
                    },
                  )
                ],
              );
            }
          }
        },
      ),
    );
  }

  Future<void> _downloadImage(
    String url, {
    AndroidDestinationType? destination,
    bool whenError = false,
    String? outputMimeType,
  }) async {
    String? fileName;
    String? path;
    int? size;
    String? mimeType;
    try {
      String? imageId;

      if (whenError) {
        imageId = await ImageDownloader.downloadImage(url,
                outputMimeType: outputMimeType)
            .catchError((error) {
          if (error is PlatformException) {
            String? path = "";
            if (error.code == "404") {
              print("Not Found Error.");
            } else if (error.code == "unsupported_file") {
              print("UnSupported FIle Error.");
              path = error.details["unsupported_file_path"];
            }
            setState(() {
              _message = error.toString();
              _path = path ?? '';
            });
          }

          print(error);
        }).timeout(Duration(seconds: 10), onTimeout: () {
          print("timeout");
          return;
        });
      } else {
        if (destination == null) {
          imageId = await ImageDownloader.downloadImage(
            url,
            outputMimeType: outputMimeType,
          );
        } else {
          imageId = await ImageDownloader.downloadImage(
            url,
            destination: destination,
            outputMimeType: outputMimeType,
          );
        }
      }

      if (imageId == null) {
        return;
      }
      fileName = await ImageDownloader.findName(imageId);
      path = await ImageDownloader.findPath(imageId);
      size = await ImageDownloader.findByteSize(imageId);
      mimeType = await ImageDownloader.findMimeType(imageId);
    } on PlatformException catch (error) {
      setState(() {
        _message = error.message ?? '';
      });
      return;
    }

    if (!mounted) return;

    setState(
      () {
        var location = Platform.isAndroid ? "Directory" : "Photo Library";
        _message = 'Saved as "$fileName" in $location.\n';
        _size = 'size:     $size';
        _mimeType = 'mimeType: $mimeType';
        _path = path ?? '';

        if (!_mimeType.contains("video")) {
          _imageFile = File(path!);
        }
        return;
      },
    );
  }
}

这是我单击图像

debug console

后的图库

这是我点击galery

I'm using the code from the example of this dependencie image_downloader: ^0.31.0, the problem is that it doesn't show any error but the image doesn't go to the galery.
This screen is to show the images from firestore and create listtyle that when the user clicks the image is suposed to download it.

import 'dart:io';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:image_downloader/image_downloader.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:pap_test/upload/upload_resumos_screen.dart';

class DownloadScreen extends StatefulWidget {
  const DownloadScreen({Key? key}) : super(key: key);
  static const routeName = '/downlaod-resumos';

  @override
  State<DownloadScreen> createState() => _DownloadScreenState();
}

class _DownloadScreenState extends State<DownloadScreen> {
  String _message = "";
  String _path = "";
  String _size = "";
  String _mimeType = "";
  File? _imageFile;
  int _progress = 0;
  String query = '1';

  CollectionReference _firebaseFirestore =
      FirebaseFirestore.instance.collection('images');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Resumos'),
      ),
      body: StreamBuilder<QuerySnapshot>(
        stream: _firebaseFirestore.snapshots().asBroadcastStream(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: CircularProgressIndicator(),
            );
          } else {
            if (snapshot.data!.docs
                .where((QueryDocumentSnapshot<Object?>
                        element) =>
                    element['disciplina']
                        
                        .toString()
                        .toLowerCase()
                        
                        .contains(query.toLowerCase()))
                .isEmpty) {
              return Center(
                child: Text(
                  'Por aqui está muito lento, carrega no botão e publica um resumo.',
                  style: Theme.of(context).textTheme.headline5,
                  textAlign: TextAlign.center,
                ),
              );
            } else {
              return ListView(
                children: [
                  
                  ...snapshot.data!.docs
                      .where((QueryDocumentSnapshot<Object?>
                              element) => 
                          element['disciplina']
                              
                              .toString()
                              .toLowerCase()
                              
                              .contains(query.toLowerCase()))
                      .map(
                    (QueryDocumentSnapshot<Object?> data) {
                      
                      final String descricao = data.get('descricao');
                      
                      final _image = data['url'];
                      
                      return ListTile(
                        onTap: () {
                          _downloadImage(_image);
                          
                        },
                        
                        leading: CircleAvatar(
                          backgroundImage: NetworkImage(_image),
                        ),

                       
                        title: Text(
                          descricao.toString(),
                          style: Theme.of(context).textTheme.headline5,
                        ),
                      );
                    },
                  )
                ],
              );
            }
          }
        },
      ),
    );
  }

  Future<void> _downloadImage(
    String url, {
    AndroidDestinationType? destination,
    bool whenError = false,
    String? outputMimeType,
  }) async {
    String? fileName;
    String? path;
    int? size;
    String? mimeType;
    try {
      String? imageId;

      if (whenError) {
        imageId = await ImageDownloader.downloadImage(url,
                outputMimeType: outputMimeType)
            .catchError((error) {
          if (error is PlatformException) {
            String? path = "";
            if (error.code == "404") {
              print("Not Found Error.");
            } else if (error.code == "unsupported_file") {
              print("UnSupported FIle Error.");
              path = error.details["unsupported_file_path"];
            }
            setState(() {
              _message = error.toString();
              _path = path ?? '';
            });
          }

          print(error);
        }).timeout(Duration(seconds: 10), onTimeout: () {
          print("timeout");
          return;
        });
      } else {
        if (destination == null) {
          imageId = await ImageDownloader.downloadImage(
            url,
            outputMimeType: outputMimeType,
          );
        } else {
          imageId = await ImageDownloader.downloadImage(
            url,
            destination: destination,
            outputMimeType: outputMimeType,
          );
        }
      }

      if (imageId == null) {
        return;
      }
      fileName = await ImageDownloader.findName(imageId);
      path = await ImageDownloader.findPath(imageId);
      size = await ImageDownloader.findByteSize(imageId);
      mimeType = await ImageDownloader.findMimeType(imageId);
    } on PlatformException catch (error) {
      setState(() {
        _message = error.message ?? '';
      });
      return;
    }

    if (!mounted) return;

    setState(
      () {
        var location = Platform.isAndroid ? "Directory" : "Photo Library";
        _message = 'Saved as "$fileName" in $location.\n';
        _size = 'size:     $size';
        _mimeType = 'mimeType: $mimeType';
        _path = path ?? '';

        if (!_mimeType.contains("video")) {
          _imageFile = File(path!);
        }
        return;
      },
    );
  }
}

This is what shows in the console after i click on the image

debug console

And this is the galery after i clicked

galery

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文