Home > other >  Loading assets dynamically with Flutter
Loading assets dynamically with Flutter

Time:02-25

I'm running a Flutter application with a list of products need to be displayed.

I've an asset folders (loaded in pubspec.yaml) which contains certain of my product images.

I wan't to show the image or a placeholder if not exists

Attempt one :

Image buildImg() {
   var img = `assets/img/${product.id}.png`;
   if(File(img).existsSync()){
      return Image.asset(img);
   }else{
      return Image.asset('assets/img/placeholder.png');
   }
}

Result: condition is always false

Attempt two :

Image buildImg() async {
   try{
      var img = rootBundle.load(`assets/img/${product.id}.png`);
      return Image.memory(img.buffer.asUint8List());
   }catch (_){
      return Image.asset('assets/img/placeholder.png');
   }
}

Result: Working but a lot of warns in terminal.

Is there a better way to dynamically load assets ? Thank's

CodePudding user response:

the Image widget has an error builder which is called when the provided path is not valid, simply use this code

Image.asset("image path.png" , errorBuilder: (context, error, stackTrace) => Image.asset('placeholder path.png'),),
  • Related