zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

Flutter 使用插件打开相册、相机「建议收藏」

flutter插件 使用 建议 收藏 打开 相机 相册
2023-06-13 09:11:14 时间

大家好,又见面了,我是你们的朋友全栈君。

需求: image_picker的使用,点击按钮底部弹出 相册、拍照选择框,实现具体功能

1:引入插件 pubspec.yaml 增加

 image_picker: ^0.7.5+2

2:android 添加androidx兼容

gradle.properties 增加

android.useAndroidX=true
android.enableJetifier=true

build 添加依赖

androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    testImplementation 'androidx.test:core:1.2.0'

3: ios ->Runner->info.plist添加权限说明

<key>NSCameraUsageDescription</key>
    	<string>这是你的自拍照</string>
    	<key>NSMicrophoneUsageDescription</key>
    	<string>用于音频插件</string>
    	<key>NSPhotoLibraryUsageDescription</key>
    	<string>用于相册选择插件</string>
    	<key>UIBackgroundModes</key>
    	<array>
    		<string>remote-notification</string>
    	</array>

4:编写Ui 添加一个浮动按钮,增加点击事件弹出相册/拍照选择框具体如下:

floatingActionButton: FloatingActionButton(
        child: Center(
            child: Text(
          "点我",
          style: TextStyle(color: Colors.white),
        )),
        backgroundColor: Colors.blueAccent,
        elevation: 0.2,
        onPressed: () {
          //点击事件
          showPicker();
        },
      )
//弹出选择相册/拍照对话框
  showPicker() {
    //底部弹出
    showModalBottomSheet(
        context: context,
        builder: (BuildContext con) => Container(
              height: 160,
              padding: EdgeInsets.all(20),
              color: Colors.white,
              child: Expanded(
                child: ListView(
                  children: [createItem(true, "拍照"), createItem(false, "相册")],
                ),
              ),
            ));
  }
//创建item
  Widget createItem(bool state, String name) {
    return GestureDetector(
        onTap: () {
          //点击事件处理
          openPicker(state);
        },
        child: ListTile(
          leading: Icon(state ? Icons.camera : Icons.image),
          title: Text(name),
        ));
  }
//使用imagePicker异步打开拍照 、相册
  openPicker(bool state) async {
    //销毁底部弹出框
    Navigator.pop(context);
    var picker = ImagePicker();
    //根据状态标识决定打开相机还是相册
    var future = await picker.getImage(
        source: state ? ImageSource.camera : ImageSource.gallery);
    setState(() {
      //通过setstate 通知重绘更新
      file = File(future.path);
    });
  }
拿到了图片,那么就差左后一步了,实现body 添加Image 显示图片,代码如下:
 body: Container(
        alignment: Alignment.center,
        margin: EdgeInsets.all(20),
        //没有图片时候显示占位图
        child: file == null ? Icon(Icons.image,) : Image.file(file),
      )

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/193177.html原文链接:https://javaforall.cn