Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter. Check if a file exists before loading it

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?

like image 786
Isaac Avatar asked Oct 02 '18 18:10

Isaac


People also ask

How do I create a folder in flutter?

Create a new Directory to give access the directory with the specified path: var myDir = Directory('myDir'); Most instance methods of Directory exist in both synchronous and asynchronous variants, for example, create and createSync.


2 Answers

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

import 'dart:io' as io; var syncPath = await path;  // for a file await io.File(syncPath).exists(); io.File(syncPath).existsSync();  // for a directory await io.Directory(syncPath).exists(); io.Directory(syncPath).existsSync(); 
like image 156
Nae Avatar answered Sep 20 '22 14:09

Nae


For me simply worked this:

import 'dart:io'; File("path/to/file").exists()  

or, for checking it synchronously

import 'dart:io'; File("path/to/file").existsSync() 
like image 38
Giuse Petroso Avatar answered Sep 20 '22 14:09

Giuse Petroso