1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flutterでimage_pickerライブラリを画像ファイルをアップロード

Posted at

Flutterでアプリを作っていて、端末の画像ファイルをアプリ上でアップロードして
使うような実装する機会がありました。
初めてで、うまくいかないこともあり、備忘録として手順などを残します。

iOSシュミレータで動かすことを前提としています。

image_pikerの導入

Flutterで画像をアップする手法としてはimage_pikerライブラリを使うのが一般的みたいです。
https://pub.dev/packages/image_picker
ドキュメントを参考に、インストールします。

flutter pub add image_picker

続いて、pubspec.yaml に追記します

dependencies:
  image_picker: ^1.1.2

下準備

アプリから端末の画像にアクセスするためには、権限を付与?
するような設定をflutterでやってあげないといけないようです。
(公式ドキュメントにも書いてますが、私は見落としエラーにハマりました、、、。)

ぴckwr.png

iosシュミレータの場合、下記の手順で設定を行います。
flutterプロジェクトの中にInfo.plisというファイルがあるので、
ここに設定を追加します。
場所: ios/Runner/Info.plis
image-pi.png

設定は、下記を追加してください。

Info.plis
	<key>NSPhotoLibraryUsageDescription</key>
    <key>NSCameraUsageDescription</key>

これで、下準備が整いました。

画像をアップする処理にトライ

それでは、画像をアップする処理を書いてみます
画像をアップする関数を作ってみましょう。

画像アップロードを使いたいファイルに、下記のような関数を書きます。


XFile? image;//画像ファイルを格納する変数
final imagePicker = ImagePicker();

//端末から画像を選択
Future pickImage() async {
    final image = await ImagePicker().pickImage(source: ImageSource.gallery);
    // 画像がnullの場合戻る
    if (image == null) return;
    final imageTemp = XFile(image.path);

    //画像ファイルをimage変数に格納
    setState(() => this.image = imageTemp);
    
}

この関数を、ボタンのonPressに設定し、ボタンを押すと
画像を選択するドロワーが出現するような処理が実現できます。
ボタンのWigetを下記のように追加してください。

    ElevatedButton(
      onPressed: () {
        pickImage();
      },
      child: Text("画像を開く"),
    ),

ボタンを押すと、下記のように画像を選択するドロワーが出現します。
pikker.png

アップした画像を表示

せっかくなので、アップした画像を表示したいですね。
Image.fileを使って表示できます。
実装例としては下記のようになります。
'dart:io'をインポートするのを忘れずに。


import 'dart:io'; 

Center(
  child: image == null
      ? const Text('画像が選択されていません')
      : Image.file(File(image!.path)),
),

以上、簡単ですがimage_pickerを用いたflutterでの画像のアップロード備忘録でした。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?