I have this code to show posts on my feed:
class Post {
final String username;
final String description;
final ImageProvider profileImageUrl;
Post({required this.username, required this.description, required this.profileImageUrl});
}
List<Post> posts = [
Post(username: 'John Doe', description: 'Hello world!', profileImageUrl: Image.network('https://t3.ftcdn.net/jpg/05/16/27/58/360_F_516275801_f3Fsp17x6HQK0xQgDQEELoTuERO4SsWV.jpg').image),
];
Then later on I try to show this image:
SizedBox(
height: 50,
width: 50,
child: CircleAvatar(
foregroundImage: posts[index].profileImageUrl,
backgroundColor: Colors.transparent,
),
),
Which results in the following error: type 'Null' is not a subtype of type 'ImageProvider' of 'function result'
If I change it to this:
foregroundImage: posts[index].profileImageUrl ?? Image.network('https://t3.ftcdn.net/jpg/05/16/27/58/360_F_516275801_f3Fsp17x6HQK0xQgDQEELoTuERO4SsWV.jpg').image,
my SDK says:
The left operand can't be null, so the right operand is never executed. Try removing the operator and the right operand.
What am I missing here?
The left operand can't be null, so the right operand is never executed. This error occurs because the profileImageUrl variable in your Post class is non-nullable, meaning it always has a value. If you make profileImageUrl nullable, you can add a condition where, if profileImageUrl is null, the right operand is used and displayed in the UI.
class Post {
final String username;
final String description;
final ImageProvider? profileImageUrl;
Post({required this.username, required this.description, required this.profileImageUrl});
}
List<Post> posts = [
Post(username: 'John Doe', description: 'Hello world!', profileImageUrl: Image.network('https://t3.ftcdn.net/jpg/05/16/27/58/360_F_516275801_f3Fsp17x6HQK0xQgDQEELoTuERO4SsWV.jpg').image),
];
After that you can add your condition it won't gave you warning. If you assign null to profileImageUrl in your list then also works.
SizedBox(
height: 50,
width: 50,
child: CircleAvatar(
foregroundImage: posts[index].profileImageUrl ?? Image.network('https://t3.ftcdn.net/jpg/05/16/27/58/360_F_516275801_f3Fsp17x6HQK0xQgDQEELoTuERO4SsWV.jpg').image,
backgroundColor: Colors.transparent,
),
),