Flutter: How do I open "local" files?

470 views Asked by At

I am trying to figure out how to access "local" files in my Flutter Android app. What I mean by "local" is a file that has been bundled in with the app package. I am using Android Studio as my IDE.

I created an "assets" directory in the base of my project, and added a txt file to that directory.

I then added the following to my pubspec.yaml file and did a pub get:

  assets:
    - assets/data.txt

Here is my main.dart code:

import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter File Test'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _buttonPressed() {
    File file = File('assets/data.txt');
    Future<String> futureContent = file.readAsString();
    futureContent.then((c) => print(c));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _buttonPressed,
        tooltip: 'Press me!',
        child: const Icon(Icons.add),
      ),
    );
  }
}

When I run the app and press the button, I get the following error:

E/flutter (15392): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FileSystemException: Cannot open file, path = 'assets/data.txt' (OS Error: No such file or directory, errno = 2)
E/flutter (15392): #0      _File.open.<anonymous closure> (dart:io/file_impl.dart:356:9)
E/flutter (15392): <asynchronous suspension>
E/flutter (15392): 

What am I missing?

0

There are 0 answers