Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: How to convert URI to File?

Tags:

flutter

I want to convert path "content://media/external/images/media/138501" to File and set in the Image.

Code:

File imageFile = File("content://media/external/images/media/138501");

is not working on:

DecorationImage(image: ExactAssetImage(imageFile.path),fit: BoxFit.fill)
like image 651
Munish Thakur Avatar asked Jun 23 '19 12:06

Munish Thakur


People also ask

How do I convert a string to a file in flutter?

How do I convert a string to a file in flutter? To write a string to a file, use the writeAsString method: import 'dart:io'; void main() async { final filename = 'file. txt'; var file = await File(filename).

How do you use URI Parse in flutter?

parse method Null safetyCreates a new Uri object by parsing a URI string. If start and end are provided, they must specify a valid substring of uri , and only the substring from start to end is parsed as a URI. If the uri string is not valid as a URI or URI reference, a FormatException is thrown.

How do you get the absolute path of a file in flutter?

You can try to use path_provider plugin to access some directories or you can access to a file by create path from it's parts (like app directory + internal directory + filename).


1 Answers

You can use uri_to_file package. It supports content:// URI.

Simple to use (Updated)

import 'package:uri_to_file/uri_to_file.dart';

try {
  String uriString = 'content://sample.txt';

  // Don't pass uri parameter using [Uri] object via uri.toString().
  // Because uri.toString() changes the string to lowercase which causes this package to misbehave

  // If you are using uni_links package for deep linking purpose.
  // Pass the uri string using getInitialLink() or linkStream

  File file = await toFile(uriString);
} on UnsupportedError catch (e) {
  print(e.message);
} on IOException catch (e) {
  print(e);
} catch (e) {
  print(e);
}

then you can use this file as you want

Important note

Don't pass uri value like this

File file = await toFile(uri.toString());

Use like this if you are using uni_links package for deep linking purpose. Use getInitialLink() or linkStream

String? uriString = await getInitialLink();
if (uriString != null) {
  File file = await toFile(uriString);
}

linkStream.listen((uriString) async {
  if (uriString != null) {
    File file = await toFile(uriString!);
  }
});

This will not modify the uri string as we are not using uri.toString()

So this package will work fine

Working example: Working example

For more details: uri_to_file

like image 95
Nikhil Avatar answered Nov 24 '22 10:11

Nikhil