Set backgroundImage of type ImageProvider<Object> with conditional statment in Flutter

I would like to set the backgroundImage property of a CircleAvatar with a conditional statement. I have a variable _imageProvided of type bool. If it is true a FileImage should be assigned to the backgroundImage property, else it should assign an AssetImage.

The Error that occurred: The argument type ‘Object’ can’t be assigned to the parameter type ‘ImageProvider<Object>?

The code Works when I assigned the a AssetImage or the FileImage separately.
Like this:

CircleAvatar(
    .....
    backgroundImage: FileImage(MyFileVariable),
    .....
);

And Like this:

CircleAvatar(
    .....
    backgroundImage: AssetImage("MyAssetPath"),
    .....
);

But the error mentioned above occurred, when I tried this:

CircleAvatar(
    .....
    backgroundImage: _imageProvided ? FileImage(MyFileVariable) : AssetImage("MyAssetPath"),
    .....
);

>Solution :

You could cast it like this; FileImage(MyFileVariable) as ImageProvider? so the whole code block would be like this:

CircleAvatar(
    .....
    backgroundImage: _imageProvided ? FileImage(MyFileVariable) as ImageProvider?: AssetImage("MyAssetPath"),
    .....
);

Leave a Reply