Search code examples
flutterfirebasedartfirebase-storage

How do I share photos on flutter?


In my app, I call images from firebase and create a share image button, but when I click on it, it shares the image link, not the image.

this is my code

class PhotoShow extends StatefulWidget {
  const PhotoShow({Key? key}) : super(key: key);

  @override
  State<PhotoShow> createState() => _PhotoShowState();
}

class _PhotoShowState extends State<PhotoShow> {
  List<String> _imageURLs = [];
  int _currentIndex = 0;

  @override
  void initState() {
    getPhoto();
    super.initState();
  }

  getPhoto() async {
    final FirebaseStorage storage = FirebaseStorage.instance;
    ListResult result = await storage.ref().child('photos').listAll();

    for (Reference ref in result.items) {
      final String downloadUrl = await ref.getDownloadURL();
      setState(() {
        _imageURLs.add(downloadUrl);
      });
    }
  }


This is the share image button:

IconButton(
  icon: Icon(
    Icons.share,
    color: Colors.white,
    size: 32,
  ),
  onPressed: () async {
    Share.shareFiles(_imageURLs);
  },
),

Solution

  • Please try using the following method

    1. Request the imageUrl returned by firebase to obtain image resources
    2. Convert image resources into XFile
    3. Use the Share. shareXFiles function to upload images Example code:
    static Future share(List<String> imageURLs) async {
      List<XFile> xFiles = [];
      for (final url in imageURLs) {
        final response = DioHelper().get(url, options: Options(responseType: ResponseType.bytes));
        if (response.statusCode == HttpStatus.ok) {
          final contentType = response.headers[Headers.contentTypeHeader]?.findByIndex<String>(0);
          final uint8list = Uint8List.fromList(response.data);
          final xFile = XFile.fromData(uint8list, mimeType: contentType);
          xFiles.add(xFile);
        }
      }
      await Share.shareXFiles(xFiles);
    }