Flutter. Check if a file exists before loading it

Isaac picture Isaac · Oct 2, 2018 · Viewed 21.3k times · Source

What I want to do is load an image in a Material Widget to use it in a ListTile, but this asset might not exist.

class MyImage extends StatelessWidget {
  final imagePath;

  MyIcon(String iconName) {
    try { // check if imagePath exists. Here is the problem
      imagePath = check('assets/$iconName.png/');
    } catch (e, s) { // if not
      imagePath = 'assets/$iconName.png/';
    }
  }

 @override
  Widget build(BuildContext context) {
    return Material(...here I will load the imagePath...);
 }
}

So, since I'm using a Stateless widget, I have to know beforehand if the image exists, otherwise I'll load a null right?

I'm pretty new to Futter so I don't know if this is an obvious question

Thanks!

Answer

Nae picture Nae · Mar 6, 2019

In order to see whether or not a file exists in internal local storage of the app use:

import 'dart:io' as io;
// for a file
io.File(path).exists();
// for a directory
io.Directory(path).exists();