在 Flutter 中将图片上传到 Firebase 的问题 "type 'XFile' is not a subtype of type 'File'"
Image Upload Problem to Firebase in Flutter "type 'XFile' is not a subtype of type 'File'"
我正在使用 Firebase-Flutter 开发一个项目。我有图像上传到 Firebase 的问题。当我 select 图片来自图库时,它不起作用。我发现了这个问题:“type 'XFile' 不是‘File’类型的子类型”。我的错误在哪里,我该如何解决这个问题?
这是我的代码。
class AddStatus extends StatefulWidget {
final String currentUserId;
const AddStatus({ Key? key,required this.currentUserId }) : super(key: key);
@override
State<AddStatus> createState() => _AddStatusState();
}
class _AddStatusState extends State<AddStatus> {
late String _tweetText;
i.File? _pickedImage;
bool _loading = false;
final ImagePicker _picker = ImagePicker();
handleImageFromGallery() async {
try {
i.File imageFile =
(await _picker.pickImage(source: ImageSource.gallery)) as dynamic;
if (imageFile != null) {
setState(() {
_pickedImage = i.File(_pickedImage!.path);
_pickedImage = i.File( imageFile.path );
});
}
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
centerTitle: true,
title: Text(
'Durum',
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
children: [
SizedBox(height: 20),
TextField(
maxLength: 280,
maxLines: 7,
decoration: InputDecoration(
hintText: 'Ne düşünüyorsun...',
),
onChanged: (value) {
_tweetText = value;
},
),
SizedBox(height: 10),
_pickedImage == null
? SizedBox.shrink()
: Column(
children: [
Container(
height: 200,
decoration: BoxDecoration(
color: Colors.black,
image: DecorationImage(
fit: BoxFit.cover,
image: FileImage(_pickedImage!),
)),
),
SizedBox(height: 20),
],
),
GestureDetector(
onTap: handleImageFromGallery,
child: Container(
height: 70,
width: 70,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.white,
border: Border.all(
color: Colors.amber,
width: 2,
),
),
child: Icon(
Icons.camera_alt,
size: 50,
color: Colors.amber,
),
),
),
SizedBox(height: 20),
RoundedButton(
btnText: 'Paylaş',
onBtnPressed: () async {
setState(() {
_loading = true;
});
if (_tweetText != null && _tweetText.isNotEmpty) {
String image;
if (_pickedImage == null) {
image = '';
} else {
image =
await StorageService.uploadTweetPicture(_pickedImage!);
}
Status tweet = Status(
text: _tweetText,
image: image,
authorId: widget.currentUserId,
likes: 0,
timestamp: Timestamp.fromDate(
DateTime.now(),
), id: '',
);
DatabaseServices.createTweet(tweet);
Navigator.pop(context);
}
setState(() {
_loading = false;
});
},
),
SizedBox(height: 20),
_loading ? CircularProgressIndicator() : SizedBox.shrink()
],
),
),
);
}
}
这是我的存储服务代码`
static Future<String> uploadTweetPicture(File imageFile)
async {
String uniquePhotoId = Uuid().v4();
File? image = await compressImage(uniquePhotoId, imageFile);
UploadTask uploadTask = storageRef
.child('images/tweets/tweet_$uniquePhotoId.jpg')
.putFile(image!);
TaskSnapshot taskSnapshot = await uploadTask.whenComplete(() => null);
String downloadUrl = await taskSnapshot.ref.getDownloadURL();
return downloadUrl;
}
static Future<File?> compressImage(String photoId, File image) async {
final tempDirection = await getTemporaryDirectory();
final path = tempDirection.path;
File? compressedImage = await FlutterImageCompress.compressAndGetFile(
image.absolute.path,
'$path/img_$photoId.jpg',
quality: 70,
);
return compressedImage;
}`
我猜你需要从 XFile 创建文件
myFile = File(myXFile.path)
我正在使用 Firebase-Flutter 开发一个项目。我有图像上传到 Firebase 的问题。当我 select 图片来自图库时,它不起作用。我发现了这个问题:“type 'XFile' 不是‘File’类型的子类型”。我的错误在哪里,我该如何解决这个问题?
这是我的代码。
class AddStatus extends StatefulWidget {
final String currentUserId;
const AddStatus({ Key? key,required this.currentUserId }) : super(key: key);
@override
State<AddStatus> createState() => _AddStatusState();
}
class _AddStatusState extends State<AddStatus> {
late String _tweetText;
i.File? _pickedImage;
bool _loading = false;
final ImagePicker _picker = ImagePicker();
handleImageFromGallery() async {
try {
i.File imageFile =
(await _picker.pickImage(source: ImageSource.gallery)) as dynamic;
if (imageFile != null) {
setState(() {
_pickedImage = i.File(_pickedImage!.path);
_pickedImage = i.File( imageFile.path );
});
}
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
centerTitle: true,
title: Text(
'Durum',
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
children: [
SizedBox(height: 20),
TextField(
maxLength: 280,
maxLines: 7,
decoration: InputDecoration(
hintText: 'Ne düşünüyorsun...',
),
onChanged: (value) {
_tweetText = value;
},
),
SizedBox(height: 10),
_pickedImage == null
? SizedBox.shrink()
: Column(
children: [
Container(
height: 200,
decoration: BoxDecoration(
color: Colors.black,
image: DecorationImage(
fit: BoxFit.cover,
image: FileImage(_pickedImage!),
)),
),
SizedBox(height: 20),
],
),
GestureDetector(
onTap: handleImageFromGallery,
child: Container(
height: 70,
width: 70,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.white,
border: Border.all(
color: Colors.amber,
width: 2,
),
),
child: Icon(
Icons.camera_alt,
size: 50,
color: Colors.amber,
),
),
),
SizedBox(height: 20),
RoundedButton(
btnText: 'Paylaş',
onBtnPressed: () async {
setState(() {
_loading = true;
});
if (_tweetText != null && _tweetText.isNotEmpty) {
String image;
if (_pickedImage == null) {
image = '';
} else {
image =
await StorageService.uploadTweetPicture(_pickedImage!);
}
Status tweet = Status(
text: _tweetText,
image: image,
authorId: widget.currentUserId,
likes: 0,
timestamp: Timestamp.fromDate(
DateTime.now(),
), id: '',
);
DatabaseServices.createTweet(tweet);
Navigator.pop(context);
}
setState(() {
_loading = false;
});
},
),
SizedBox(height: 20),
_loading ? CircularProgressIndicator() : SizedBox.shrink()
],
),
),
);
}
}
这是我的存储服务代码`
static Future<String> uploadTweetPicture(File imageFile)
async {
String uniquePhotoId = Uuid().v4();
File? image = await compressImage(uniquePhotoId, imageFile);
UploadTask uploadTask = storageRef
.child('images/tweets/tweet_$uniquePhotoId.jpg')
.putFile(image!);
TaskSnapshot taskSnapshot = await uploadTask.whenComplete(() => null);
String downloadUrl = await taskSnapshot.ref.getDownloadURL();
return downloadUrl;
}
static Future<File?> compressImage(String photoId, File image) async {
final tempDirection = await getTemporaryDirectory();
final path = tempDirection.path;
File? compressedImage = await FlutterImageCompress.compressAndGetFile(
image.absolute.path,
'$path/img_$photoId.jpg',
quality: 70,
);
return compressedImage;
}`
我猜你需要从 XFile 创建文件
myFile = File(myXFile.path)