iT邦幫忙

2021 iThome 鐵人賽

DAY 7
0
Mobile Development

Flutter with GetX, loading*175%歷程 系列 第 7

[Day07] Flutter with GetX image picker 手機相簿選照片

Image picker

flutter的照片操作,從相簿選照片或是拍照
之前用的時候版本是0.7.4 , 但寫這篇的時候改版到了0.8.4

Android:
Android 4.3 與 套件版本0.8.1以上的版本 在AndroidManifest.xml內
可以不用新增 android:requestLegacyExternalStorage="true"

iOS:
Info.plist還是老樣子需要新增
NSPhotoLibraryUsageDescription, NSCameraUsageDescription

原先的PickedFile Class 改為 XFile 詳細的請再參考文檔
但用法差異沒有太多

https://cdn-images-1.medium.com/max/800/1*GvoE99CjCwY6Vbolz7wFSA.png

搭配Getx使用的話 controller 如下
最後選到的照片, 回傳的是儲存路徑String
source 則可以選擇照片來源,拍照或是從相簿選擇

class ImagePickPageController extends GetxController {
  final _imageFilePath = "".obs;
  set imageFilePath(value) => this._imageFilePath.value = value;
  get imageFilePath => this._imageFilePath.value;

  @override
  void onInit() {
    super.onInit();
  }

  getImage(ImageSource source) async {
    final _picker = ImagePicker();
    XFile? pickedFile = await _picker.pickImage(source: source);
    if (pickedFile != null) {
      imageFilePath = pickedFile.path;
      print(imageFilePath);
    } 
  }

Widget page
Obx 觀察 imageFilePath 是否有變動
如果照片的路徑是空字串,則顯示一個photo_library的Icon
如果不是空字串, 則用Image.file()顯示該路徑的圖片

class ImagePickerPage extends GetView<ImagePickPageController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('ImagePickPage')),
      body: SafeArea(
        child: Column(
          children: [
            _buildImageWidget(),
            CupertinoButton(
              child: Text("選擇照片"),
              onPressed: () => controller.getImage(ImageSource.gallery),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildImageWidget() {
    return Center(
      child: Obx(
        () {
          return Container(
            color: Colors.grey[200],
            width: Get.width,
            height: Get.width,
            child: (controller.imageFilePath.isEmpty)
                ? Icon(Icons.photo_library, size: 50)
                : Image.file(File(controller.imageFilePath)),
          );
        },
      ),
    );
  }
}

結果如下
https://cdn-images-1.medium.com/max/800/1*sBqm5B856buKQxN4V8EGbw.gif

本篇的GitHub source code

下篇將為大家繼續延伸介紹 image_cropper
照片旋轉與裁切


上一篇
[Day06] Flutter with GetX shared_preference
下一篇
[Day08] Flutter with GetX image_cropper 照片裁切
系列文
Flutter with GetX, loading*175%歷程 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言