I'm building a web app with flutter and I want an option to change the profile picture. To pick image from gallery I use the image_picker_web 2.1.1
package.
class ImagePickerService {
late Image? img = Image.asset('whatever'); //has to be initialised
Future<void> pickImage() async {
img = await ImagePickerWeb.getImageAsWidget();
}
}
I didn't set the type of pickImage()
to Future<Image?> because then I'd have to convert from Future. This asset('whatever'), although not very elegant, doesn't cause any problems because before _fileLoaded
is set to true while picking an image, I display username's initial letter as avatar. Without it I was getting an error of no initialisation.
Relevant snippets from settings page class:
late Image? avatar;
bool _fileLoaded = false;
final ImagePickerService _ips = ImagePickerService();
Center(
child: displayAvatar(),
),
TextButton.icon(
onPressed: () {
setState(() {
_ips.pickImage();
avatar = _ips.img;
_fileLoaded = true;
});
},
icon: const Icon(Icons.edit),
label: const Text('Change avatar'),
),
Widget displayAvatar() {
if (_fileLoaded) {
return CircleAvatar(
backgroundImage: avatar as ImageProvider, radius: 50.0);
} else...
I searched for similar problems, but didn't find any answer except for adding as ImageProvider
, which in my case removes the error from IDE and lets me run the project, but the error appears later on the red screen when I press the button to change avatar, even though the type should be correct. Please, do you know any solution?
CodePudding user response:
ImageProvider is an abstract class. Classes that implement ImageProvider are AssetImage(""), NetworkImage("URL"), FileImage() etc. I believe FileImage should be well suited for your case.
CodePudding user response:
I'm posting the solution, in case someone has the same problem. I switched back to the image_picker package, it supports web too, you just have to use it a bit differently:
class ImagePickerService {
final ImagePicker _picker = ImagePicker();
Uint8List picked = Uint8List(8);
Future<void> pickImage() async {
XFile? image = await _picker.pickImage(source: ImageSource.gallery);
if (image != null) picked = await image.readAsBytes();
}
}
ClipOval(
child: Image.memory(
avatar,
fit: BoxFit.cover,
width: 100.0,
height: 100.0,
),
)
avatar
is assigned to _ips.picked
, so it's of Uint8List type.