flutter入门实战——文件读取和写入

问题背景

本文将介绍flutter中如何读取文件内容以及保存内容到文件。

问题分析

先直接上效果:
flutter入门实战——文件读取和写入_第1张图片

问题解决

话不多说,直接上代码。
main.dart文件,代码如下:

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

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Write to File',
      home: HomePage(storage: IntStorage()),
    ),
  );
}

class IntStorage {
  Future get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    print(directory.path);
    return directory.path;
  }

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

  /**
   * 读取文件内容
   */
  Future readCounter() async {
    try {
      final file = await _localFile;
// Read the file
      final contents = await file.readAsString();
      return int.parse(contents);
    } catch (e) {
// If encountering an error, return 0
      return 0;
    }
  }

  /**
   * 写入文件
   */
  Future writeCounter(int counter) async {
    final file = await _localFile;
// Write the file
    return file.writeAsString('$counter');
  }
}

class HomePage extends StatefulWidget {
  const HomePage({required this.storage});

  final IntStorage storage;

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

class _HomePageState extends State {
  int count = 0;
  int savedValue = 0;

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

  Future _incrementCounter() {
    setState(() {
      count++;
      savedValue++;
    });
// Write the variable as a string to the file.
    return widget.storage.writeCounter(savedValue);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Write to file'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Count of button presses in disk $savedValue time${savedValue == 1 ? '' : 's'}.',
              style: TextStyle(fontSize: 22),
            ),
            Text('Button pressed $count time${count == 1 ? '' : 's'}.',
                style: TextStyle(fontSize: 22)),
            TextButton(
                onPressed: () {
                  setState(() {
                    count = 0;
                  });
                },
                child: Text("Refresh"))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

问题总结

本文介绍了flutter中如何读取文件内容以及保存内容到文件中,有兴趣的同学可以进一步深入研究。

你可能感兴趣的:(移动开发,flutter,android,ios)