본문으로 바로가기

플러터(Flutter) 파일 읽고 쓰기

category Application/Flutter 2020. 8. 25. 10:14

패키지 추가

 

pubspec.yaml 파일에 path_provider 패키지를 추가합니다.

 

 

path_provider

  • 파일 시스템에서 일반적으로 사용하는 경로 찾기를 지원
  • IOS, Android, Mac OS

 

pubspec.yaml

name: layout
description: A new Flutter project.

version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2

  path_provider: ^1.6.14

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

 

 

예제1

 

import 'dart:async';
import 'dart:io';

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

void main() {
  runApp(
    MaterialApp(
      title: 'Reading and Writing Files',
      home: FlutterDemo(storage: CounterStorage()),
    ),
  );
}

class CounterStorage {
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();

    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/counter.txt');
  }

  Future<int> readCounter() async {
    try {
      final file = await _localFile;

      // Read the file
      String contents = await file.readAsString();

      return int.parse(contents);
    } catch (e) {
      // If encountering an error, return 0
      return 0;
    }
  }

  Future<File> writeCounter(int counter) async {
    final file = await _localFile;
    print(file);
    // Write the file
    return file.writeAsString('$counter');
  }
}

class FlutterDemo extends StatefulWidget {
  final CounterStorage storage;

  FlutterDemo({Key key, @required this.storage}) : super(key: key);

  @override
  _FlutterDemoState createState() => _FlutterDemoState();
}

class _FlutterDemoState extends State<FlutterDemo> {
  int _counter;

  @override
  void initState() {
    super.initState();
    widget.storage.readCounter().then((int value) {
      setState(() {
        _counter = value;
      });
    });
  }

  Future<File> _incrementCounter() {
    setState(() {
      _counter++;
    });

    // Write the variable as a string to the file.
    return widget.storage.writeCounter(_counter);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Reading and Writing Files')),
      body: Center(
        child: Text(
          'Button tapped $_counter time${_counter == 1 ? '' : 's'}.',
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

 

File, socket, HTTP 등 I/O 를 지원하는 라이브러리입니다.

import 'dart:io';

 

비동기 작업을 지원하는 라이브러리입니다.

import 'dart:async';

 

주요 코드를 살펴봅니다.

 

다음 함수는 getApplicationDocumentsDirectory() 함수를 통해 데이터를 읽고 쓰는 어플리케이션 디렉터리 경로를 반환합니다.

Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();

    return directory.path;
}

 

위의 함수에서 경로를 가져와 파일명까지 더하여 파일타입으로 반환합니다.

Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/counter.txt');
}

 

위에서 반환 받은 파일을 readAsString() 또는 writeAsString() 함수로 읽고 쓰는 것을 볼 수 있습니다.

Future<int> readCounter() async {
    try {
      final file = await _localFile;

      // Read the file
      String contents = await file.readAsString();

      return int.parse(contents);
    } catch (e) {
      // If encountering an error, return 0
      return 0;
    }
}

Future<File> writeCounter(int counter) async {
    final file = await _localFile;
    print(file);
    // Write the file
    return file.writeAsString('$counter');
}

 

클래스가 호출되면 initState() 함수를 통해 파일에서 값을 읽어옵니다.

widget 객체는 FlutterDemo StatefulWidget 입니다.

class FlutterDemo extends StatefulWidget {
  final CounterStorage storage;

  FlutterDemo({Key key, @required this.storage}) : super(key: key);

  @override
  _FlutterDemoState createState() => _FlutterDemoState();
}

class _FlutterDemoState extends State<FlutterDemo> {
  int _counter;

  @override
  void initState() {
    super.initState();
    widget.storage.readCounter().then((int value) {
      setState(() {
        _counter = value;
      });
    });
  }
  
  ...

 

 

floatActionButton 을 누르면 onPressed 의 _incrementCounter 함수가 호출되어 _FlutterDemoState 클래스의 속성인 _counter 변수의 값이 1 증가되어 writeCounter() 함수를 통해 파일에 쓰게됩니다.

Future<File> _incrementCounter() {
    setState(() {
      _counter++;
    });

    // Write the variable as a string to the file.
    return widget.storage.writeCounter(_counter);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Reading and Writing Files')),
      body: Center(
        child: Text(
          'Button tapped $_counter time${_counter == 1 ? '' : 's'}.',
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }

 

 

 

참고

 

File 읽고 쓰기

가끔은 디스크에 파일을 읽고 쓰는 일을 해야할 때가 있습니다. 앱 런처간에 데이터를관리하거나 나중에 오프라인 모드에서 사용하기 위한 목적으로 인터넷에서 파일을다운로드 받을 수도 있��

flutter-ko.dev