6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flutterで画像をImagePickerで取得、FirebaseStorageに保存して画像のURLを取得、Firestoreに保存して画像を表示する方法

Last updated at Posted at 2021-09-02

Flutterで画像をImagePickerで取得、FirebaseStorageに保存して画像のURLを取得、Firestoreに保存して画像を表示する方法

参考リンク:
https://firebase.flutter.dev/docs/storage/usage

4つのステップに分けてまとめ:

1、準備:image_picker、firebase_storageをインストール、ios/Runner/Info.plistファイル内に下記を追記
https://pub.dev/packages/image_picker
https://pub.dev/packages/firebase_storage

<key>NSPhotoLibraryUsageDescription</key>
<string>フォトライブラリへのアクセスを求めています</string>
<key>NSCameraUsageDescription</key>
<string>カメラへのアクセスを求めています</string>

2、File型の変数imageを宣言、ImagePickerでimageを取得、そのまま画像を表示する方法

ImagePicker imagePicker = ImagePicker();
final file = imagePicker.pickImage(source: ImageSource.gallery);
image = File(file!.path);

late File? image = null;
image == null ? Container() : Container(
  child: Image.file(image!, fit: BoxFit.cover),
  height: 100.0,
  ),

3、画像をFirebaseStorageに保存、imageのURLを取得、URLから画像を表示する方法

final ref = FirebaseStorage.instance.ref(imageId);
final storedImage = await ref.putFile(image!);

imageURL = await storedImage.ref.getDownloadURL();

String? imageURL = null;
imageURL == null ? Container() : Container(
  child: Image.network(imageURL!, fit: BoxFit.cover),
  height: 100.0,
  ),

4、imageのURLをFireStoreに保存、FirestoreからimageのURLを取得、URLから画像を表示(3と同じ)する方法

await FirebaseFirestore.instance.collection('users').doc(Id).set({
  'imageURL': imageURL,
  });

final documentSnapshot = await FirebaseFirestore.instance.collection('users').doc(Id).get();
imageURL = documentSnapshot.get('imageURL');

String? imageURL = null;
imageURL == null ? Container() : Container(
  child: Image.network(imageURL!, fit: BoxFit.cover),
  height: 100.0,
  ),
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?