I am getting some list of images names only I need to get it from my asset folder. But there are some images which are not available so I need to add some error placeholder If it's not exists. I tried with Future But When I show it on screen its showing error that Future Widget can't be added in Widget
ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(100)),
child: Image.asset(
'assets/images/${image}.png',
height: 50,
width: 50,
fit: BoxFit.fill,
)),
This is what I get
Future<Widget> Imagee(image) async {
try {
await rootBundle.load(image);
return ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(100)),
child: Image.asset(
'assets/team/${image}.png',
height: 60,
width: 60,
fit: BoxFit.fill,
));
} catch (_) {
return SizedBox(); // Return this widget
}
}
Its showing that Future can't be added in Widget
CodePudding user response:
Maybe you can try using a validation:
await rootBundle.load(image);
if (image != null) {
return ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(100)),
child: Image.asset(
'assets/team/${image}.png',
height: 60,
width: 60,
fit: BoxFit.fill,
));
} else {
//...
}
CodePudding user response:
You can use FutureBuilder
if you have async call to load the Image.
Future<Widget> ImageOrNot() async {
try {
await rootBundle.load(image);
return ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(100)),
child: Image.asset(
'assets/team/${image}.png',
height: 60,
width: 60,
fit: BoxFit.fill,
));
} catch (_) {
return SizedBox(); // Return this widget
}
}
and inside build use FutureBuilder
class ImageOrBox extends StatelessWidget {
const ImageOrBox({super.key});
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: imageOrNot(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
return snapshot.data??Text('Error');
},
);
}
}