知识FlutterFlutter-ImagePicker-ImageCropper
Kahvia ImagePicker
Flutter用于选择图片的工具包。
依赖引入
使用
1 2 3 4 5
| final ImagePicker _picker=ImagePicker(); onPressed: ()async{ final image=await _picker.pickImage(source: ImageSource.gallery); }
|
ImageCropper
用于图片裁剪的工具包
依赖引入
相关配置(安卓需要配置,ios不需要)
在AndroidManifest.xml加入以下信息。
1 2 3 4
| <activity android:name="com.yalantis.ucrop.UCropActivity" android:screenOrientation="portrait" android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>
|
使用
1
| CroppedFile? croppedImage=await ImageCropper().cropImage(sourcePath: image.path);
|
两者结合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| Widget build(BuildContext context) { final ImagePicker _picker=ImagePicker(); return ElevatedButton( onPressed: ()async{ final image=await _picker.pickImage(source: ImageSource.gallery); if(image!=null){ CroppedFile? croppedImage=await ImageCropper().cropImage(sourcePath: image.path); if(croppedImage!=null){ context.read<ImageData>().setImage(File(croppedImage.path)); } else{ context.read<ImageData>().setImage(File(image.path)); } } }, style: ButtonStyle( shape: MaterialStateProperty.all(const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(30)) )), minimumSize: MaterialStateProperty.all(const Size(300, 40)), backgroundColor: MaterialStateProperty.all(MyColors.rgbRed) ), child: const Text("Select a photo from gallery"), ); }
|
图片上传
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class FinishedButton extends StatelessWidget { const FinishedButton({Key? key}) : super(key: key);
@override Widget build(BuildContext context) { final dio=Dio(); File? image=context.watch<ImageData>().image; return ElevatedButton( onPressed: image==null? (){}: ()async{ final multipartImg=await MultipartFile.fromFile(image.path); final map=<String,dynamic>{}; map['file']=await MultipartFile.fromFile(image.path); var response=await dio.post("$serviceUploadHeader/${context.read<UserMsg>().userId}",data: FormData.fromMap(map)); context.read<UserMsg>().setHeadImg(response.data); Navigator.pop(context); }, style: ButtonStyle( backgroundColor: image==null? MaterialStateProperty.all(Colors.grey): MaterialStateProperty.all(MyColors.rgbRed) ), child: const Text("Finished",), ); } }
|