본문 바로가기
Dart (Flutter)

[Flutter] File Handling

by llHoYall 2022. 4. 2.

In this posting, we will learn about file handling.

path_provider Package

This package supports getting commonly used locations on the filesystem.

It supports Android, iOS, Linux, macOS, and Windows, but not all methods are supported on all platforms.

Refer to the below page for the detailed supported list.

https://pub.dev/packages/path_provider

Usage

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

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

It is easy to use.

For more detail, refer to the official page.

File class

You can handle the file system through this class.

if you use File class, you need to import 'dart:io' first.

import 'dart:io';

Write to a File

var file = await File('test_file.txt').writeAsString('some content');

You can write to a file as a string or list of bytes form.

Read from a FIle

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

Read methods exist in pairs with write-related methods.

Other Methods

You can easily use copy, create, delete, open, and rename as well.

Please refer to this official site.

https://api.flutter.dev/flutter/dart-io/File-class.html

Example

Now, let's make an example using the learned things.

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'File Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FileExample(),
    );
  }
}

class FileExample extends StatefulWidget {
  @override
  State<FileExample> createState() => _FileExampleState();
}

class _FileExampleState extends State<FileExample> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    readCountFromFile();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('File Example'),
      ),
      body: Center(
        child: Text(
          '$_counter',
          style: const TextStyle(fontSize: 40),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _counter++;
          });
          writeCountToFile(_counter);
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  void writeCountToFile(int counter) async {
    Directory dir = await getApplicationDocumentsDirectory();
    File(dir.path + '/counter.txt').writeAsStringSync(counter.toString());
  }

  void readCountFromFile() async {
    try {
      Directory dir = await getApplicationDocumentsDirectory();
      var counter = await File(dir.path + '/counter.txt').readAsString();

      setState(() {
        _counter = int.parse(counter);
      });
    } catch (e) {
      print(e.toString());
    }
  }
}

The most important part is writeCountToFile() and readCountFromFile() functions.

We already learned about it, so please enjoy it.

'Dart (Flutter)' 카테고리의 다른 글

[Flutter] Desktop Application using Flutter  (0) 2023.01.25
[Flutter] Animation  (0) 2022.04.03
[Flutter] Save Data using Shared Preferences  (0) 2022.04.01
[Flutter] Navigation  (0) 2022.03.30
[Flutter] How to Use Tab Bar Widget  (0) 2022.03.27

댓글