꿈꾸는 시스템 디자이너

Flutter Example - File Read & Write | path_provider plugin 본문

Tutorial/Flutter with App

Flutter Example - File Read & Write | path_provider plugin

독행소년 2019. 10. 8. 15:31

* About PlugIn

https://pub.dev/packages/path_provider

 

path_provider | Flutter Package

Flutter plugin for getting commonly used locations on the Android & iOS file systems, such as the temp and app data directories.

pub.dev

 

1. Add this to pubspec.yaml file

dependencies:
  path_provider: ^1.3.0

 

2. Source Code

import 'dart:io';

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

FileReadWriteDemoState pageState;

class FileReadWriteDemo extends StatefulWidget {
  @override
  FileReadWriteDemoState createState() {
    pageState = FileReadWriteDemoState();
    return pageState;
  }
}

class FileReadWriteDemoState extends State<FileReadWriteDemo> {
  String appDocPath;
  String filePath;
  TextEditingController wCon = TextEditingController();
  TextEditingController rCon = TextEditingController();

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

  void prepareDirPath() async {
    Directory appDocDir = await getApplicationDocumentsDirectory();
    Stream<FileSystemEntity> files = appDocDir.list();

    files.listen((data) {
      print("Data: " + data.toString());
    });
    setState(() {
      appDocPath = appDocDir.path;
      filePath = "$appDocPath/text.txt";
    });
  }

  Future<File> getFileRef() async {
    return File(filePath);
  }

  writeFile() async {
    File file = await getFileRef();
    file.writeAsString(wCon.text);
    wCon.clear();
  }

  readFile() async {
    File file = await getFileRef();
    String text = await file.readAsString();
    rCon.text = text;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("File I/O"),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.refresh),
            onPressed: () {
              prepareDirPath();
            },
          )
        ],
      ),
      body: ListView(
        children: <Widget>[showPathInfo(), writeFileArea(), readFileArea()],
      ),
    );
  }

  Widget showPathInfo() {
    return Container(
      padding: const EdgeInsets.only(bottom: 20),
      child: Column(
        children: <Widget>[
          ListTile(
            title: Text("Documents directory's path"),
            subtitle: (appDocPath != null) ? Text(appDocPath) : null,
          ),
          ListTile(
            title: Text("File name & path"),
            subtitle: (filePath != null) ? Text(filePath) : null,
          )
        ],
      ),
    );
  }

  writeFileArea() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 10),
      child: Column(
        children: <Widget>[
          Container(
            child: Text(
              "* Write File (text.txt)",
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            alignment: Alignment(-1, 0),
          ),
          Divider(color: Colors.grey),
          TextField(
            controller: wCon,
            maxLines: 5,
            decoration: InputDecoration(
              hintText: "Insert text want to write to file",
              filled: true,
              fillColor: Color(0xFFDBEDFF),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(10.0)),
                borderSide: BorderSide(color: Colors.grey),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(10.0)),
                borderSide: BorderSide(color: Colors.grey),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: SizedBox(
              height: 30,
              child: RaisedButton(
                color: Colors.orangeAccent,
                textColor: Colors.white,
                child: Text("Write"),
                onPressed: () {
                  writeFile();
                },
              ),
            ),
          )
        ],
      ),
    );
  }

  readFileArea() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 10),
      padding: const EdgeInsets.only(top: 50),
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Container(
                child: Text(
                  "* Read File (text.txt)",
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                alignment: Alignment(-1, 0),
              ),
              SizedBox(
                height: 30,
                child: RaisedButton(
                  color: Colors.orangeAccent,
                  textColor: Colors.white,
                  child: Text("Read"),
                  onPressed: () {
                    readFile();
                  },
                ),
              )
            ],
          ),
          Divider(color: Colors.grey),
          TextField(
            controller: rCon,
            maxLines: 5,
            readOnly: true,
            decoration: InputDecoration(
              filled: true,
              fillColor: Color(0xFFDBEDFF),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(10.0)),
                borderSide: BorderSide(color: Colors.grey),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(10.0)),
                borderSide: BorderSide(color: Colors.grey),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

 

 

▶ Go to Table of Contents | 강의 목차로 이동


※ This example is also available in the Flutter Code Examples app. | 본 예제는 Flutter Code Examples 앱에서도 제공됩니다.

 

Flutter Code Examples - Google Play 앱

Are you a beginner at Flutter? Check out the various features of Flutter through the demo. Source code for all demos is also provided.

play.google.com

Comments