Flutter/기본2

파일에 데이터 저장하기 (path_provider,

꽃피는봄날 2021. 7. 1. 18:10
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
  _FileAppState createState() => _FileAppState();
}

class _FileAppState extends State<FileApp> {

  int _count = 0;

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

    // 앱이 실행 될 때 파일에서 가지고온 데이터 표시하기위에 initState에서 실행함
    readCountFile();
  }

  // 문자열 형태로 파일을 만들어 저장하기
  void writeCountFile(int count) async{
    //               ↱ 내부 저장소 경로 가져오기
    var dir = await getApplicationDocumentsDirectory();
    File(dir.path + '/count.txt').writeAsStringSync(count.toString());
  }


  // 파일 읽기
  void readCountFile() async{
    try{
      var dir = await getApplicationDocumentsDirectory();
      var file = await File(dir.path + '/count.txt').readAsString();
      print('파일-> $file');

      setState(() {
        _count = int.parse(file);
      });
    }catch(e){
      print(e.toString());
    }

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('파일 예제2'),
      ),

      body: Container(
        child: Center(
          child: Text(
            '$_count',
            style: TextStyle(fontSize: 40),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          setState(() {
            _count++;
          });
          writeCountFile(_count);
        },
        child: Icon(Icons.add),
      ),
    );
  }
}