Notice
Recent Posts
Recent Comments
Link
«   2025/09   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Archives
Today
Total
관리 메뉴

자라나라

[Flutter] 데이터 저장 (2) 파일 이용하기 본문

Flutter

[Flutter] 데이터 저장 (2) 파일 이용하기

자랄수있다 2022. 9. 12. 23:14

오늘은 파일을 이용해볼 것이다.

먼저 의존성에 path_provider 패키지를 추가해주자.

이 패키지는 앱이 설치되어 있는 경로와 임시 폴더의 경로를 찾아준다.

main.dart 파일에서도 path_provider와 추가적으로 dart:io 라이브러리도 import 해준다.

 

import 'package:flutter/material.dart';
import 'FileApp클래스가 작성된 다트파일';

void main() => runApp(MyApp());

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: FileApp(),
    );
  }
}

  

데모파일에서 MyApp은 전부 날리고 FileApp()이라는 클래스를 홈으로 받자.

새 다트파일을 만들어 그곳에 FileApp 클래스를 만들 것이다.

 

 

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

class FileApp extends StatefulWidget {
  const FileApp({Key? key}) : super(key: key);

  @override
  State<FileApp> createState() => _FileAppState();
}

class _FileAppState extends State<FileApp> {

  int _count = 0;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('File Example'),
      ),
      body: Container(
        child: Center(
          child: Text(
            '$_count',
            style: TextStyle(fontSize: 40),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          setState(() {
            _count++;
          });
          writeCountFile(_count);
        },
        child: Icon(Icons.add),
      ),
    );
  }
  
  void writeCountFile(int count) async{
    var direc = await getApplicationDocumentsDirectory(); // path_provider 제공, 저장경로 가져옴
    File(direc.path + '/count.txt').writeAsStringSync(count.toString());  // dart:io 제공
  }
  
  void readCountFile()async{
    try{
      var direc = await getApplicationDocumentsDirectory();
      var file = await File(direc.path + '/count.txt').readAsString();
      print(file);
      setState(() {
        _count = int.parse(file);
      });
    }catch(e){
      print(e);
    }
  }
}

 

 

initState에 readCountFile()함수를 호출하여 파일에서 가져온 데이터를 실행하도록한다.

버튼이 눌리면 writeCountFile()함수를 이용해 _count값을 전달받아 count.txt라는 이름의 파일로 만들어 String 형태로 저장한다.

readCountFile()은 이 파일을 읽어 다시 정수형으로 반환해 _count변수에 저장한다.