White Rabbit
White Rabbit

Reputation: 25

Flutter/Dart: Image widget and check if file exist

I have a layout that place a image widget only when it is exist. But show error as "Unable to load asset: assets/none"

Is the code correct?

  //  list of filename ['index.jpg','','index.jpg','none']
  Widget displayTextImage(String question, String filename) {
  String assetFolder = 'assets/';
  print(filename);
  return (Column(
    mainAxisAlignment: MainAxisAlignment.center,
    crossAxisAlignment: CrossAxisAlignment.center,
    children: [
      Text(
        question,
      ),
      io.File(assetFolder + filename).exists() != null
          ? Image.asset(assetFolder + filename)
          : SizedBox(height: 1),
    ],
  ));
}

Upvotes: 1

Views: 1963

Answers (1)

mohsen meyahi
mohsen meyahi

Reputation: 36

you can use this code:

import 'package:flutter/services.dart' show rootBundle;

ByteData bytes;

try{
   bytes = await rootBundle.load('assets/placeholder.png');
   asset file exist and create your ui code...
}catch(e){
   asset file not exist...
}

read more about this topic in this post: How to read bytes of a local image file in Dart/Flutter?

Upvotes: 2

Related Questions