使用 FilePicker 包从库中选择文件时收到类型转换错误
Receiving type cast error when selecting file from library using the FilePicker package
我正在创建一个使用 FilePicker 从用户图库中获取图像的应用程序,但我收到了类型转换错误。
lib/widgets/rounded_image.dart:53:34: Error: The argument type 'PlatformFile' can't be assigned to the parameter type 'String'.
这是class
class RoundedImageFile extends StatelessWidget {
final PlatformFile? image;
final double size;
const RoundedImageFile({
required Key key,
required this.image,
required this.size,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: size,
height: size,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage(image), <--Type cast error here
),
borderRadius: BorderRadius.all(
Radius.circular(size),
),
color: Colors.black,
),
);
}
}
这是将图像设置为个人资料图像的class:
PlatformFile? _profileImage;
Widget _profileImageField() {
return GestureDetector(
onTap: () {
GetIt.instance.get<MediaService>().pickImageFromLibrary().then(
(_file) {
setState(
() {
_profileImage = _file;
}
);
}
);
},
child: () {
if (_profileImage != null) {
return RoundedImageFile(
key: UniqueKey(),
image: _profileImage!,
size: _deviceHeight * 0.15,
);
}
转换 as String
给出了同样的错误,解析 toString
给出了以下内容:
我很困惑,因为它在我认为的早期版本中会起作用。感谢您的回复。如果我必须包含更多代码,请告诉我。
编辑*:我尝试使用 FileImage
而不是 AssetImage
并得到不同的转换类型错误:
The argument type 'PlatformFile?' can't be assigned to the parameter type 'File'.
问题是您使用的是 AssetImage
,它从您的代码而非设备的存储中读取图像。你应该使用 FileImage
:
image: DecorationImage(
fit: BoxFit.cover,
image: FileImage(image),
),
我正在创建一个使用 FilePicker 从用户图库中获取图像的应用程序,但我收到了类型转换错误。
lib/widgets/rounded_image.dart:53:34: Error: The argument type 'PlatformFile' can't be assigned to the parameter type 'String'.
这是class
class RoundedImageFile extends StatelessWidget {
final PlatformFile? image;
final double size;
const RoundedImageFile({
required Key key,
required this.image,
required this.size,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: size,
height: size,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage(image), <--Type cast error here
),
borderRadius: BorderRadius.all(
Radius.circular(size),
),
color: Colors.black,
),
);
}
}
这是将图像设置为个人资料图像的class:
PlatformFile? _profileImage;
Widget _profileImageField() {
return GestureDetector(
onTap: () {
GetIt.instance.get<MediaService>().pickImageFromLibrary().then(
(_file) {
setState(
() {
_profileImage = _file;
}
);
}
);
},
child: () {
if (_profileImage != null) {
return RoundedImageFile(
key: UniqueKey(),
image: _profileImage!,
size: _deviceHeight * 0.15,
);
}
转换 as String
给出了同样的错误,解析 toString
给出了以下内容:
我很困惑,因为它在我认为的早期版本中会起作用。感谢您的回复。如果我必须包含更多代码,请告诉我。
编辑*:我尝试使用 FileImage
而不是 AssetImage
并得到不同的转换类型错误:
The argument type 'PlatformFile?' can't be assigned to the parameter type 'File'.
问题是您使用的是 AssetImage
,它从您的代码而非设备的存储中读取图像。你应该使用 FileImage
:
image: DecorationImage(
fit: BoxFit.cover,
image: FileImage(image),
),