0

I'm trying to read data from TXT file but somthing goes wrong. There is a code

import 'dart:async'
import 'dart:io';
void main(){
File('file.txt').readAsString().then((String contents){
 print(contents);
});
}

This is code From official documentation.also I tried change path to my file in File('') like (assets/file.txt) but stil nothing work. I getting this error after starting program

Error: Unsupported operation: _Namespace

I know that i need to add assets at pbuspec.yaml file, i did it. also when i using rootBundle from services.dart, to read this file.txt, everything is working fine and i can read data from it.

GDTyka
  • 472
  • 3
  • 16
  • Are trying to run this for Flutter Web? If so, that is your problem. The `dart:io` package does not work on web – PatrickMahomes Jul 26 '21 at 12:51
  • I think the problem is you need to provide complete path. You can't use `File` class for files bundled into your app. File class works with actual files on mobile (like you apk file). Try path_provider plugin to find `getTemporaryDirectory` or something. – Rahul Jul 26 '21 at 12:51

1 Answers1

0

The Dart code shown above has a syntax error - the first line does not have a ;. When I run it I get this error:

$ dart run file.dart
file.dart:1:8: Error: Expected ';' after this.
import 'dart:async'
       ^^^^^^^^^^^^

Note that you do not need to import this library. If I remove this line then it successfully reads the file file.txt in the current directory.

You mention using rootBundle to read an asset file - this is all appropriate to Flutter, as opposed to the simple Dart program that you show.

As mentioned in the comments to your question, dart:io cannot be used for Flutter Web apps, because the browser does not permit file access. It can be used for Flutter Mobile and Desktop apps. See Reading and Writing Files.

Patrick O'Hara
  • 1,999
  • 1
  • 14
  • 18