由於Flutter屬於UI框架
所以很多跟系統溝通的功能必須透過套件完成
從今天起會介紹一些開發中常常需用到的輪子
很基本的功能
使用image_picker從相簿或相機挑照片
作法跟以前UIImagePickerController差不多
只是以前使用delegate pattern
現在使用async/await⚠️⚠️⚠️
還有以前可以直接拿到UIImage
現在是拿到path⚠️⚠️⚠️
透過path拿到File
再用Image.file顯示
使用前記得老規矩
要在info.plist加入隱私請求
不然一樣閃給你看
PS.if Andorid API < 29, add android:requestLegacyExternalStorage="true" as an attribute to the tag in AndroidManifest.xml.
另外跟以前一樣
只能選一張
如果想要多選
請使用image_pickers(多一個s)
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:icofont_flutter/icofont_flutter.dart';
import 'package:image_picker/image_picker.dart';
class LessonPageImagePicker extends StatefulWidget {
@override
_LessonPageImagePickerState createState() => _LessonPageImagePickerState();
}
class _LessonPageImagePickerState extends State<LessonPageImagePicker> {
File _imageFile;
String wording = "";
Future<Null> _pickerImageFrom(ImageSource imgSrc) async {
final theImage = await ImagePicker().getImage(source: imgSrc);
setState(() {
if (theImage != null) {
_imageFile = File(theImage.path);
wording = '';
} else {
wording = 'No image selected.';
}
});
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_){
print("addPostFrameCallback");
});
}
@override
Widget build(BuildContext context) {
Widget _createButton(bool isCamera) {
final color = isCamera ? Colors.blueAccent : Colors.greenAccent;
final icon = isCamera ? IcoFontIcons.uiCamera : IcoFontIcons.uiImage;
final source = isCamera ? ImageSource.camera : ImageSource.gallery;
return Expanded(
child: GestureDetector(
child: Card(
margin: EdgeInsets.only(top: 8),
color: color,
child: Center(child: Icon(icon, size: 40))
),
onTap: () {
_pickerImageFrom(source);
},
)
);
}
return Scaffold(
appBar: AppBar(
title: Text("ImagePicker"),
),
body: Container(
padding: EdgeInsets.all(8),
child: ListView(
children: [
_imageFile == null
? Image.asset("resource/images/placeholder.png")
: Image.file(_imageFile),
SizedBox(
height: 100,
child: Row(
children: [
_createButton(true),
SizedBox(width: 8),
_createButton(false)
]
)
),
Text(wording,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.redAccent),
)
]
)
)
);
}
}
下集預告:Local Storage + URL Launcher