🎉

【Flutter】画像を端末に保存するコードimage_gallery_saver(2021年10月)

2021/10/01に公開

こいつらをインストール

import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';

呼び出しのコード

SaveImageWidget().displayingImage(context, message.imageUrl);

画像を拡大させて表示(処理に直接的には関係ないがこの中にモデルを呼び出すコードがある)

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:syamoji/presentation/save_image/save_image_model.dart';
import 'package:syamoji/util/color.dart';

class SaveImageWidget {
 Future<void> displayingImage(BuildContext context, imageUrl) async {
   showDialog(
       context: context,
       builder: (context) => ChangeNotifierProvider<SaveImageModel>(
             create: (_) => SaveImageModel(),
             child: Consumer<SaveImageModel>(builder: (context, model, child) {
               return Column(
                 mainAxisAlignment: MainAxisAlignment.center,
                 children: [
                   Container(
                     margin: EdgeInsets.fromLTRB(20, 0, 20, 5),
                     child: CachedNetworkImage(
                       imageUrl: imageUrl,
                       progressIndicatorBuilder:
                           (context, url, downloadProgress) =>
                               CircularProgressIndicator(
                                   value: downloadProgress.progress),
                       errorWidget: (context, url, error) => Icon(Icons.error),
                     ),
                   ),
                   if (model.infoMessage == '写真の保存に成功しました')
                     Container(
                       margin: EdgeInsets.fromLTRB(50, 10, 50, 0),
                       padding: EdgeInsets.all(10),
                       decoration: BoxDecoration(
                           color: ThemeColor.white,
                           borderRadius: BorderRadius.circular(5)),
                       child: Text(
                         model.infoMessage,
                         style: TextStyle(
                             color: ThemeColor.deepGreen,
                             fontSize: 20,
                             fontWeight: FontWeight.bold),
                       ),
                     ),
                   if (model.infoMessage == '保存に失敗しました')
                     Container(
                       margin: EdgeInsets.fromLTRB(20, 10, 20, 0),
                       padding: EdgeInsets.all(10),
                       decoration: BoxDecoration(
                           color: ThemeColor.warningRed,
                           borderRadius: BorderRadius.circular(5)),
                       child: Text(
                         model.infoMessage,
                         style: TextStyle(
                             color: Colors.black,
                             fontSize: 20,
                             fontWeight: FontWeight.bold),
                       ),
                     ),
                   SizedBox(),
                   Container(
                     margin: EdgeInsets.fromLTRB(50, 10, 50, 10),
                     padding: EdgeInsets.all(10),
                     child: ElevatedButton(
                       onPressed: () async {
                         ///ここに画像を保存する関数がある
   		  await model.saveImage(imageUrl);
                       },
                       child: Text(
                         
   		  '保存する',
                         style: TextStyle(
                             color: Colors.black,
                             fontSize: 30,
                             fontWeight: FontWeight.bold),
                       ),
                       style: ElevatedButton.styleFrom(
                           side: BorderSide(
                             color: Colors.black,
                             width: 0.3,
                           ),
                           primary: ThemeColor.lightGreen,
                           shape: RoundedRectangleBorder(
                               borderRadius: BorderRadius.circular(10))
                           //ボタンの背景色
                           ),
                     ),
                   ),
                 ],
               );
             }),
           ));
 }
}

保存するコード

import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';

class SaveImageModel extends ChangeNotifier {
  String infoMessage = '';
  Future<void> saveImage(imageUrl) async {
    try {
      var response = await Dio()
          .get(imageUrl, options: Options(responseType: ResponseType.bytes));
      final result = await ImageGallerySaver.saveImage(
          Uint8List.fromList(response.data),
          quality: 100,
          name: "messageImage");
      print(result);

      if (result.containsKey('isSuccess')) {
        this.infoMessage = '写真の保存に成功しました';
      }
    } catch (e) {
      this.infoMessage = '保存に失敗しました';
    }
    notifyListeners();
  }
}

Discussion