在实际项目开发中,个人中心模块经常会遇到上传头像,并显示用户头像的需求.在此分享一个整个的流程.
第一步:图片上传
图片上传使用的image_picker: ^0.8.5+3
这个插件
具体代码如下
final ImagePicker _imagePicker = ImagePicker();
openPicker(bool state) async {
final XFile? pickedFile = await _imagePicker.pickImage(
source: state == true ? ImageSource.camera : ImageSource.gallery,
maxWidth: 200,
maxHeight: 200,
imageQuality: 100);
/// 上传服务器
updateImage(pickedFile!);
}
Future<void> uploadImage(XFile pickedFile) async {
var file = File(pickedFile.path);
Uint8List imageBytes = await file.readAsBytes();
String base64 = base64Encode(imageBytes);
}
第二步:显示图片
上一步上传给服务器是是一个base64
的字符串,所以服务端返回的也是一个图片的base64
字符串.格式如下"iVBORw0KGgoAAAANSUhEUgAAAEYAAAAjCAIAAACmdes6AAACP0lEQVR4Xu2W0U3EQAxETxSA+OMnFdAL30AV1EUproB2SGJwhpldZ7MJEBDSfCT22Ot3vj3dxV5f/pguGvrt+kf6Mg2P9xrs01mQbKY6BOxESK79YKdDcu0BOwype4JEfT1PjWRd6zo7kmsTWCvSzfXzKAo+PdyFxiPxVW2X26ui0KlZ9DSC7UJyIZJmyaaDqnLPKlgTkvPUkGweN7akWTd4Kpk1lHgCJqFaR3KSHMnmM3Ikf0jGDSUeJKmt63gkpcJgMm4o8SiDgq0gBcYmJKSi12TcRo9SeTDiGVIweEGO5DZC0qWNg+rnSgokdPqzCgv9tYpEaxmfa41CHsddEY9VxtU+dBZFsFBTGRK9YqTW3T4jUU+TLxV1QE/xiCjRqqVcQyY8HtGgS89uQUJ5bTGoo+txfISGiqMnSCE8bKj8psfEtfLw1Ob+biSDFRXPTpCiyTBvTGvJU0yZIsXcVNaIhJvBS4V4OZLBr2Jt7iQ1leOLz03C7hHURvaBhBG9VKvjuie31eLv5fiiPAme9kqQIk5fvGIrvUtkS2aYyjVUlC4H8RymeAZRrd6l8OjcRFg8bip3hyZIioSi26LZQ5BctfhSHj7NoRKkGDeaIN7w+b/ffiTsr6mpPEyaQ21CIiFeICVUhERtMYjZeFjuUm0glyLhZ+/SDrofxUM/AqMNq9zpDxhf/NgxCvq0tZxGqWW10LMa9PhPIpEIrw/J9Ec8sbZoZ3mI8FS1uJ0Wyda25AYNmiIl1hbtqSV1I70B+dAU/4dAw64AAAAASUVORK5C"
展示base64
图片代码如下:
Image.memory(
base64Decode(base64字符串),
//防止重绘
gaplessPlayback: true,
width: 100,
height: 100,
fit: BoxFit.cover,
),
注意点:
一定要加上gaplessPlayback : true
这行代码,不然的话,在界面刷新操作时会有图片闪动的bug.