Flutter之文件操作

为了将文件保存到磁盘,需要结合使用 dart:io 库中的 path_provider 这个 package。 

添加依赖

dependencies:
  path_provider: ^2.0.10

步骤

  • 找到正确的本地路径

    //1、找到正确的本地路径
      Future<String> get _localPath async {
        final directory = await getApplicationDocumentsDirectory();
        print("应用文档路径:${directory.path}");
        return directory.path;
      }
getApplicationDocumentsDirectory getApplicationSupportDirectory 的区别 
  1. getApplicationDocumentsDirectory:此方法返回的是应用程序的文档目录,用于存储用户生成的文件,如用户的文档、设置文件等。这个目录在应用程序被卸载时不会被清除,因此适合存储需要持久保存的数据。

  2. getApplicationSupportDirectory:此方法返回的是应用程序的支持目录,用于存储应用程序的支持文件,如日志、缓存文件等。这个目录在应用程序被卸载时可能会被清除,因此不适合存储需要持久保存的数据。

  • 创建一个指向文件位置的引用

    //2、创建一个指向文件位置的引用
      Future<File> get _file async{
        final path = await _localPath;
        print("文件路径:$path/flutter_demo.txt");
        return new File('$path/flutter_demo.txt');
      }
  • 将数据写入文件

    //3、将数据写入文件
      Future<File> writeFile(String text) async {
        final file = await _file;
        return file.writeAsString('$text' + '\n',mode: FileMode.append);
      }
  • 从文件读取数据

    //4、从文件读取数据
      Future<String> readCounter() async {
        try {
          final file = await _file;
    
          // Read the file
          final contents = await file.readAsString();
    
          return contents;
        } catch (e) {
          // If encountering an error, return 0
          return "这是一个错误";
        }
      }
  • 判断文件是否存在

    //5、判断文件是否存在
      Future<bool> fileExit() async{
        File file= await _file;
        print("file.exists():${file.existsSync()}");
        return file.existsSync();
      }
  • 删除文件

     //6、如果文件存在,则删除文件
      deletefile() async{
        File file= await _file;
        if(file.existsSync()){
          file.deleteSync();
        }
      }

用例:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'file_help.dart';

main()  {

  FileHelp().deletefile();

  FileHelp().writeFile("这是一次测试");

  FileHelp().writeFile("这是另一次测试");
  runApp(MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "文件操作",
      home: HYHomePage(),
    );
  }
}

class HYHomePage extends StatefulWidget {

  @override
  State<HYHomePage> createState() => _HYHomePageState();
}

class _HYHomePageState extends State<HYHomePage> {

  bool exit = false;
  String date = "";

  @override
  void initState() {

    FileHelp().fileExit().then((value) {
      setState(() => exit = value);
    });
    FileHelp().readCounter().then((value) {
      setState(() {
        date = value;
      });
    });
        super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("文件操作"),
      ),
      body: Center(
        child: Text("文件是否存在:${exit}\n\n文件内容:${date}"),
      ),
    );
  }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值