flutter 文件读写

import 'dart:async';
import 'dart:io';

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

void main() {
  runApp(
    MaterialApp(
      title: 'Reading and Writing Files',
      home: FlutterDemo(storage: CounterStorage()),
    ),
  );
}

class CounterStorage {
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();

    return directory.path;
  }

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

  Future<int> readCounter() async {
    try {
      final file = await _localFile;

      // Read the file
      String contents = await file.readAsString();

      return int.parse(contents);
    } catch (e) {
      // If encountering an error, return 0
      return 0;
    }
  }

  Future<File> writeCounter(int counter) async {
    final file = await _localFile;

    // Write the file
    return file.writeAsString('$counter');
  }
}

class FlutterDemo extends StatefulWidget {
  final CounterStorage storage;

  FlutterDemo({Key key, @required this.storage}) : super(key: key);

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

class _FlutterDemoState extends State<FlutterDemo> {
  int _counter;

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

  Future<File> _incrementCounter() {
    setState(() {
      _counter++;
    });

    // Write the variable as a string to the file.
    return widget.storage.writeCounter(_counter);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Reading and Writing Files')),
      body: Center(
        child: Text(
          'Button tapped $_counter time${_counter == 1 ? '' : 's'}.',
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

 

### 如何在 Flutter 中实现文件的上传和下载 #### 文件上传 在 Flutter 中,可以通过 HTTP 请求来完成文件上传的功能。通常会使用 `http` 或者 `dio` 这样的第三方库来进行网络请求操作。 以下是基于 `dio` 库的一个简单示例: ```dart import 'package:dio/dio.dart'; Future<void> uploadFile(String filePath, String url) async { try { Dio dio = Dio(); // 创建 FormData 对象并附加文件 FormData formData = FormData.fromMap({ "file": await MultipartFile.fromFile(filePath, filename: "example.txt"), }); // 发送 POST 请求 Response response = await dio.post( url, data: formData, onSendProgress: (int sent, int total) { print(((sent / total * 100).toStringAsFixed(0)) + "%"); }, ); if (response.statusCode == 200 || response.statusCode == 201) { print("文件上传成功!"); } else { print("文件上传失败:${response.statusMessage}"); } } catch (e) { print("错误:$e"); } } ``` 上述代码展示了如何通过 `FormData` 将本地文件作为多部分表单数据发送给服务器[^1]。 对于特定场景如华为 OBS 的文件上传,则可以参考专门针对该服务的 SDK 和 API 文档进行适配开发[^2]。 #### 文件下载 同样地,在 Flutter 中也可以利用类似的工具包执行文件下载任务。下面是一个简单的例子展示怎样从远程地址获取资源保存至设备内部存储位置。 ```dart import 'dart:io'; import 'package:path_provider/path_provider.dart'; import 'package:http/http.dart' as http; Future<File> downloadFile(String fileUrl, String fileName) async { Directory? appDocDir; final response = await http.get(Uri.parse(fileUrl)); if(response.statusCode >=200 && response.statusCode<300){ appDocDir=await getApplicationDocumentsDirectory(); File newFile=File('${appDocDir.path}/$fileName'); await newFile.writeAsBytes(response.bodyBytes); return newFile; }else{ throw Exception('Failed to load file'); } } ``` 此函数接受两个参数——目标 URL 及期望命名的新档案名,并返回代表已储存档案实例之 Future 物件。 #### 注意事项 - **权限管理**:确保应用拥有必要的读写外部存储器许可权。 - **用户体验优化**:考虑加入进度条显示功能让用户知晓当前状态。 - **异常处理机制完善化**:增加更多类型的错误捕捉逻辑提高程序稳定性。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

computerclass

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值