Home > other >  How to display an image from local storage
How to display an image from local storage

Time:03-18

I took a picture with the camera and I got its path

/data/user/0/com.example.tarea_8/cache/CAP8057460019038129642.jpg

I tried to display it like this

var imagePath = '/data/user/0/com.example.tarea_8/cache/CAP8057460019038129642.jpg';
Image.file(File(imagePath));

But I got this error

The argument type 'File (where File is defined in C:\flutter\bin\cache\pkg\sky_engine\lib\html\html_dart2js.dart)' can't be assigned to the parameter type 'File (where File is defined in C:\flutter\bin\cache\pkg\sky_engine\lib\io\file.dart)'. (Documentation) 

File is defined in C:\flutter\bin\cache\pkg\sky_engine\lib\html\html_dart2js.dart (html_dart2js.dart:144).

File is defined in C:\flutter\bin\cache\pkg\sky_engine\lib\io\file.dart (file.dart:144).

2 positional argument(s) expected, but 1 found. (Documentation) 

dart:html (new) File File(   List  fileBits,   String fileName, [   Map ? options, ]

I saw that someone had the same problem 3 year ago here. I followed the solution steps to the letter but it didn't work for me.

I am using Android Studio and the version of the installed plugins are Dart 211.7808 & Flutter 65.2.2

CodePudding user response:

Check your imports this Error say's that File id defined in both dart:html and dart:io.

solution 1: if you are not using functionality of dart:html remove it from imports and your code will be running. (i am saying this first solution because dart:html only runs on flutter web and dart:io does not work on web).

solution 2: you have to import any of one library as named import and then use. (import alies/named imports)

import 'dart:async';
import 'my_library.dart' as myLib;

void main() {
  Stream stream = new Stream.fromIterable([1, 2]); // from async
  myLib.Stream myCustomStream = new myLib.Stream(); // from your library
}

CodePudding user response:

The first thing you need to get is the Application Documents Directory. Using path_provider package. https://pub.dev/packages/path_provider

path_provider: ^2.0.9

now you have two options if you using state management like (riverpod or bloc) you can make logic in it but if you don't use any state management you can use FutureBuilder to get the path and show image

  @override
Widget build(BuildContext context) {
return new MaterialApp(
    title: 'Flutter Demo',
    home: new FutureBuilder(
        future: _getLocalFile("flutter_assets/image.png"),
        builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
          return snapshot.data != null ? Image.file(snapshot.data) : new Container();
        })
);
}

Future<File> _getLocalFile(String filename) async {
String dir = (await getApplicationDocumentsDirectory()).path;
File file = new File('$dir/$filename');
return file;

}

  • Related