I've used file_picker library so the user can select his favorite image and then use it as the background image in my application. Thing is, I can't cast it correctly. Here's some code:
floatingActionButton: FloatingActionButton(
onPressed: () async {
final result = await FilePicker.platform.pickFiles(type: FileType.any, allowMultiple: false);
if (result != null) {
var fileBytes = result.files.first.bytes;
if (fileBytes != null) {
blogimage = Image.memory(fileBytes);
setState(() {});
}
}
},
tooltip: 'Select Image',
child: Icon(Icons.select_all),
),
In the above code, I'm getting the image.
and I'm trying to use blogimage
as my background image.
I've already tried using containers but failed. This is the code I used:
Widget build(BuildContext context) {
return Container(
decoration: (blogimage != null)? BoxDecoration(image: DecorationImage(image: blogimage)): null,
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
title: Text(widget.title),
),
.....
Got the error: Expected a value of type 'ImageProvider', but got one of type 'Image'.
Any ideas? Thanks for reading.
First of all, If you want to get the bytes from the selected image you are missing one argument
final result = await FilePicker.platform.pickFiles(type: FileType.any, allowMultiple: false, withData: true);
withData: true Will give you the bytes from the selected image.
If you do not set it to true result.files.first.bytes will be null.
Secondly, Why declare blogImage as a Image type?
Use Uint8List type instead and use MemoryImage(blogImage) in your DecorationImage
class FilePickerTest extends StatefulWidget {
@override
_FilePickerTestState createState() => _FilePickerTestState();
}
class _FilePickerTestState extends State<FilePickerTest> {
Uint8List? blogImage;
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () async {
final result = await FilePicker.platform.pickFiles(type: FileType.any, allowMultiple: false, withData: true);
if (result != null) {
blogImage = result.files.first.bytes;
if (blogImage != null) {
setState(() {});
}
}
},
tooltip: 'Select Image',
child: Icon(Icons.select_all),
),
body: Container(
decoration: (blogImage != null) ? BoxDecoration(image: DecorationImage(image: MemoryImage(blogImage!))) : null,
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
title: Text(widget.title),
),
),
),
);
}
}