zoukankan      html  css  js  c++  java
  • Flutter 读写本地文件

    文档

    注意

    • 安装 path_provider 插件后重启f5, 而不是等待热更新

    demo

    import 'dart:io';
    import 'dart:async';
    
    import 'package:flutter/material.dart';
    import 'package:path_provider/path_provider.dart';
    
    void main() => runApp(new MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Ajnauw',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key}) : super(key: key);
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      String value; // 每次input的值
      String allText = ''; // 从本地文件获取的值
    
      /**
       * 此方法返回本地文件地址
       */
      Future<File> _getLocalFile() async {
        // 获取文档目录的路径
        Directory appDocDir = await getApplicationDocumentsDirectory();
        String dir = appDocDir.path;
        final file = new File('$dir/demo.txt');
        // print(file);
        return file;
      }
    
      /**
       * 保存value到本地文件里面
       */
      void _saveValue() async {
        try {
          File f = await _getLocalFile();
          IOSink slink = f.openWrite(mode: FileMode.append);
          slink.write('$value
    ');
          // await fs.writeAsString('$value');
          setState(() {
            value = '';
          });
          slink.close();
        } catch (e) {
          // 写入错误
          print(e);
        }
      }
    
      /**
       * 读取本地文件的内容
       */
      void _readContent() async {
        File file = await _getLocalFile();
        // 从文件中读取变量作为字符串,一次全部读完存在内存里面
        String contents = await file.readAsString();
        setState(() {
          allText = contents;
        });
      }
    
      // 清空本地保存的文件
      void _clearContent() async {
        File f = await _getLocalFile();
        await f.writeAsString('');
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('demo'),
          ),
          body: ListView(
            children: <Widget>[
              Container(
                padding: EdgeInsets.all(8.0),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: Container(
                        margin: EdgeInsets.only(right: 16.0),
                        child: TextField(
                          controller: TextEditingController(
                            text: value,
                          ),
                          onChanged: (String v) {
                            value = v;
                          },
                          onSubmitted: (String r) {
                            value = r;
                          },
                        ),
                      ),
                    ),
                    RaisedButton(
                      color: Theme.of(context).primaryColor,
                      onPressed: _saveValue,
                      child: Text('保存'),
                    ),
                  ],
                ),
              ),
              Container(
                child: Column(
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        RaisedButton(
                          color: Theme.of(context).accentColor,
                          onPressed: _readContent,
                          child: Text('获取本地数据'),
                        ),
                        RaisedButton(
                          color: Colors.red,
                          textColor: Colors.white,
                          onPressed: _clearContent,
                          child: Text('清空本地数据'),
                        ),
                      ],
                    ),
                    Container(
                      padding: const EdgeInsets.all(16.0),
                      child: Text('''$allText'''),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      }
    }
    
  • 相关阅读:
    51nod 1412 AVL树的种类(经典dp)
    HDU 6141 I am your Father!(最小树形图+权值编码)
    POJ 3164 Command Network(最小树形图模板题+详解)
    HDU 6125 Free from square(状态压缩+分组背包)
    HDU 6143 Killer Names(容斥原理)
    CSU 1808 地铁(最短路变形)
    HDU 6128 Inverse of sum(同余)
    HDU 6121 Build a tree(完全K叉树)
    HDU 6129 Just do it(杨辉三角)
    HDU 6127 Hard challenge(扫描线)
  • 原文地址:https://www.cnblogs.com/ajanuw/p/10490836.html
Copyright © 2011-2022 走看看