如何解决类型 'Future<PickedFile?>' 不是类型 'Future<File>' 的子类型,迁移到空安全后出错
我最近将我的 flutter 应用程序迁移到了 null 安全 2.12.0 ,我不得不对我的代码进行很多更改,而且我只停留在我的图像选择器和上传功能上。我设法更改了 null 接受的变量。应用程序运行没有问题,但在选择图像后,它不会显示在 ui 中,或者关闭其他需要图像文件数据的管道功能。我对颤振还很陌生,颤振的这种突然变化引起了很多混乱。我将非常感谢对此的解决方案以及避免将来出现此类问题的良好解释,谢谢!
整个代码的Git“https://github.com/sudaraka93/stack.git”
late SharedPreferences sharedPreferences;
late Size deviceSize;
Future<File>? file;
late String base64Image;
String status = '';
late File tmpFile;
String errMessage = 'Error Uploading Image';
DateTime selectedDate = DateTime.now();
final TextEditingController CommentController = new TextEditingController();
@override
void initState() {
}
chooseImage() {
setState((){
file = ImagePicker().getImage(source: ImageSource.gallery) as Future<File>;
});
}
startUpload()async {
setStatus('Uploading Image...');
if (null == tmpFile) {
setStatus(errMessage);
return;
}
String fileName = tmpFile.path.split('/').last;
upload(base64Image);
}
Widget showImage() {
return FutureBuilder<File>(
future: file,builder: (BuildContext context,AsyncSnapshot<File> snapshot) {
if (snapshot.connectionState == ConnectionState.done &&
null != snapshot.data) {
tmpFile = snapshot.data!;
base64Image = base64Encode(snapshot.data!.readAsBytesSync());
return Flexible(
child:Container(
child:Image.file(
snapshot.data!,fit: BoxFit.fill,),)
);
} else if (null != snapshot.error) {
return const Text(
'画像の選択エラー',textAlign: TextAlign.center,);
} else {
return const Text(
'画像が選択されていません',);
}
},);
}
解决方法
ImagePicker
不再使用 File
作为数据类型,您必须使用 PickedFile
只要改变
Future<File>? file
到
Future<PickedFile>? file
将 tmpFile
的数据类型更改为 PickedFile
。像这样转换为base64
base64Image = base64Encode(File(snapshot.data.path).readAsBytesSync());
然后为了显示图像使用像这样的楔形
Image.file(File(snapshot.data.path))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。