Flutter. Check if a file exists before loading it

谁说我不能喝 提交于 2020-05-14 18:44:48

问题


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!


回答1:


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();



回答2:


Looks like you want to try to load an ImageProvider from a folder where the image may or may not exist and then, if it does not, load a fallback asset image (which you can be sure will exist as you'll put it in your root bundle).

Try this:

ImageProvider getImageProvider(File f) {
  return f.existsSync()
      ? FileImage(f)
      : const AssetImage('images/fallback.png');
}


来源:https://stackoverflow.com/questions/52614610/flutter-check-if-a-file-exists-before-loading-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!