Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled Exception: FileSystemException: Cannot open file, path = 'assets/xml/strings.xml' (OS Error: No such file or directory, errno = 2)

Tags:

flutter

dart

I started studying Flutter and everything should work, yet it doesn't read xml file Here's pubspec.yaml part :

flutter:
  uses-material-design: true
  assets:
    - assets/
    - assets/xml/strings.xml

here's the part where xml should be read :

  void main(){
    String file = "";
    switch (type){
      case TYPE_STRING:
        file = 'assets/xml/strings.xml';
        break;
    }
    readFileAsync(file);
  }

  void readFileAsync(String filePath) {
    File file = new File(filePath);
    Future<String> futureContent = file.readAsString();
    futureContent.then((xmlString) => {
      parseXml(xmlString)
    });
  }

And the error I get is

Unhandled Exception: FileSystemException: Cannot open file, path = 'assets/xml/strings.xml' (OS Error: No such file or directory, errno = 2)

Here how my assets are set in the project structure : enter image description here

So, it seems to me I set up everything right, what's the problem?

like image 731
Vlad Alexeev Avatar asked Dec 21 '19 14:12

Vlad Alexeev


1 Answers

Use rootBundle to access resources from application package.

And also call WidgetsFlutterBinding.ensureInitialized() first, if you want to use rootBundle before runApp function.

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  String file = "";
  switch (type) {
    case TYPE_STRING:
      file = 'assets/xml/strings.xml';
      break;
  }
  readFileAsync(file);
}

Future<dynamic> readFileAsync(String filePath) async {
  String xmlString =  await rootBundle.loadString(filePath);
  print(xmlString);
  return parseXml(xmlString);
}
like image 156
Crazy Lazy Cat Avatar answered Sep 28 '22 02:09

Crazy Lazy Cat