Search code examples
flutterdartfilepicker.io

Receiving type cast error when selecting file from library using the FilePicker package


I am creating an app that uses FilePicker to get images from the user's gallery but I am receiving type cast errors.

lib/widgets/rounded_image.dart:53:34: Error: The argument type 'PlatformFile' can't be assigned to the parameter type 'String'.

Here's the 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,
      ),
    );
  }
}

This is the class that sets the image as a profile image:

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,
          );
        }

Casting as String gives the same error and parsing toString gives me the following: enter image description here

I'm stumped since it would have worked in earlier versions I think. Thanks for the responses. Please let me know if I must include more code.

EDIT*: I have tried using FileImage instead of AssetImage and get a different cast type error:

The argument type 'PlatformFile?' can't be assigned to the parameter type 'File'.

Solution

  • the problem is that you're using AssetImage, which reads images from your code and not the Device's storage. you should be using FileImage:

    image: DecorationImage(
      fit: BoxFit.cover,
      image: FileImage(image),
    ),