Issue
In my app, there is a button that will copy the file(in my case txt) to the local download folder. I even ask permission from the phone and it works. But when I read from the txt file, the error said
FileSystemException: Cannot open file, path = 'assets/readme.txt' (OS Error: No such file or directory, errno = 2)
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:io';
import "package:path_provider/path_provider.dart";
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
int a;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("What up"),
),
body: Center(
child: RaisedButton(
onPressed: () async {
await Permission.storage.request();
if (PermissionStatus == PermissionStatus.granted) {
print("permission granted");
}
if (PermissionStatus == PermissionStatus.denied) {
print('permission denied');
}
var path = "assets/readme.txt";
a = await readCounter();
print(a);
},
child: Text("Press me"),
),
),
),
);
}
}
Future<int> readCounter() async {
try {
final file = File("assets/readme.txt");
// Read the file.
String contents = await file.readAsString();
return int.parse(contents);
} catch (e) {
// If encountering an error, return 0.
print(e);
}
}
I add this code in android>app>src>main>AndroidMainfest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I also add the asset folder in pubspec.yaml
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/
Solution
The File
class references a file in the whole file system of the device, not the assets of the application.
To access assets you should follow what is stated in the documentation.
- Import the flutter services
import 'package:flutter/services.dart'
- Use the
rootBundle
to access theAssetBundle
- Use the
loadString
method to access the data inside your asset with the specified pathawait rootBundle.loadString('assets/readme.txt');
Implementation in your code:
Future<int> readCounter() async {
try {
String contents = await rootBundle.loadString('assets/readme.txt');
return int.parse(contents);
} catch (e) {
// If encountering an error, return 0.
print(e);
}
}
Answered By - Christopher Moore
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.