Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide path in flutter - path combine

Tags:

flutter

dart

I am creating a quiz app in the Flutter for which I have collected some questions in CSV file. I want to store the CSV file in firebase and display questions into the app by reading from the CSV file. But just to check if the reading file is as simple as it should be, I tried to read a dummy file in this way:

new File('file.txt').readAsString().then((String contents) {
  print(contents);
});

from main.dart before returning the Widget. But i get this error:

`FileSystemException: Cannot open file, path = 'file.txt' (OS Error: No such file or directory, errno = 2)`

even though I have made a dummy 'file.txt' file in the same directory as 'main.dart'.

I tried doing './file.txt' and even the absolute path from windows explorer but none seem to work.

How to fix this?

like image 764
Bipin Avatar asked May 07 '18 06:05

Bipin


People also ask

How do you use the path in flutter?

Drawing a line is probably the easiest thing to do with paths. First, move the current point of the path to the starting point using the moveTo function. Then draw the line using the lineTo function to the endpoint. That's it.

How do you get the directory path 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.

How do I change the path of a file in flutter?

If the files are on different file systems you need to create a new destination file, read the source file and write the content into the destination file, then delete the source file.


2 Answers

The path_provider package allows you to access the temp and appDir directory

https://pub.dartlang.org/packages/path_provider

Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;

Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;

You can use the join() method of https://pub.dartlang.org/packages/path to concatenate paths in a platform dependent way, or just use string concatenation like

String filePath = '${appDocDir.path}/file.txt';

new File(filePath).readAsString().then((String contents) {
  print(contents);
});    
like image 57
Günter Zöchbauer Avatar answered Nov 03 '22 01:11

Günter Zöchbauer


You can use join to safely join files or folders:

Example:

import 'package:path/path.dart' as Path;

    String fileName = Path.join('/storage/emulated/0/', '/MyFolder/file.txt');

Result:

fileName = '/storage/emulated/0/MyFolder/file.txt'

like image 30
live-love Avatar answered Nov 03 '22 01:11

live-love