見出し画像

Flutterでアルバムから画像を読み込む

初めましてblueです。

現在、ITベンチャー企業でWEBキャンペーンシステムの開発を行なっています。

以前、Flutterを使用したスマホアプリ開発を行なっていました。

今回はFlutterでカメラやアルバムから画像を読み込む方法について記事にしてみました!

使用するパッケージ

導入方法

pubspec.yamlに下記を追加

image_picker: ^0.8.4+4

使用する場所でインポートする

import 'package:image_picker/image_picker.dart';

ios/Runner/info.plistを編集、下記を追加

	<key>NSPhotoLibraryUsageDescription</key>
	<string>This app requires to access your photo library</string>
	<key>NSCameraUsageDescription</key>
	<string>This app requires to add file to your camera</string>
	<key>NSMicrophoneUsageDescription</key>
	<string>This app requires to add file to your photo library your microphone</string>

※Androidは、バージョン0.8.1以降、Android 4.3以降は設定の必要なし

実装コード

File? image;
// インスタンスを生成
final picker = ImagePicker();

Future getImage() async {
   //アルバムから読み込み
   final XFile? _image = await picker.pickImage(source: ImageSource.gallery);
   
   setState(() {
     if (_image != null) {
       //_imageをファイルに変換
       image = File(_image.path);
     }
   });
 }

getImageを呼び出すことで、アルバムから画像の選択することが出来ます。

カメラを起動したい場合は、下記を使用。

picker.getImage(source: ImageSource.camera);

全体コード

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

void main() {
 runApp(const MyApp());
}

class MyApp extends StatelessWidget {
 const MyApp({Key? key}) : super(key: key);

 @override
 Widget build(BuildContext context) {
   return const MaterialApp(
     home: MyHomePage(),
   );
 }
}

class MyHomePage extends StatefulWidget {
 const MyHomePage({Key? key}) : super(key: key);
 @override
 _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
 File? image;
 final picker = ImagePicker();

 Future getImage() async {
   final XFile? _image = await picker.pickImage(source: ImageSource.gallery);

   setState(() {
     if (_image != null) {
       image = File(_image.path);
     }
   });
 }

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       title: const Text('アルバムから画像を読み込む'),
     ),
     body: Center(
       child: image == null ?
         const Text('画像がありません') 
         : Image.file(image!, fit: BoxFit.cover),
     ),
     floatingActionButton: FloatingActionButton(
       onPressed: () async{
         getImage();
       },
       child: const Icon(Icons.photo),
     ),
   );
 }
}

実装画面

画像1

良かったらサポートしていただけると嬉しいです!