新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Flutter教程:Flutter文件讀寫(xiě)
介紹
PathProvider 插件提供了一種平臺(tái)透明的方式來(lái)訪問(wèn)設(shè)備文件系統(tǒng)上的常用位置。該類當(dāng)前支持訪問(wèn)兩個(gè)文件系統(tǒng)位置:

- 臨時(shí)目錄: 系統(tǒng)可隨時(shí)清除的臨時(shí)目錄(緩存)。在iOS上,這對(duì)應(yīng)于NSTemporaryDirectory() 返回的值。在Android上,這是getCacheDir()返回的值。
- 文檔目錄: 應(yīng)用程序的目錄,用于存儲(chǔ)只有自己可以訪問(wèn)的文件。只有當(dāng)應(yīng)用程序被卸載時(shí),系統(tǒng)才會(huì)清除該目錄。在iOS上,這對(duì)應(yīng)于NSDocumentDirectory。在Android上,這是AppData目錄。
一旦你的Flutter應(yīng)用程序有一個(gè)文件位置的引用,你可以使用dart:ioAPI來(lái)執(zhí)行對(duì)文件系統(tǒng)的讀/寫(xiě)操作。有關(guān)使用Dart處理文件和目錄的更多信息,請(qǐng)參閱此概述 和這些示例。
讀寫(xiě)文件的示例
以下示例展示了如何統(tǒng)計(jì)應(yīng)用程序中按鈕被點(diǎn)擊的次數(shù)(關(guān)閉重啟數(shù)據(jù)不丟失):
- 通過(guò) flutter create 或在IntelliJ中 File > New Project 創(chuàng)建一個(gè)新Flutter App.
- 在pubspec.yaml文件中聲明依賴 PathProvider 插件
- 用一下代碼替換 lib/main.dart中的:
import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(
new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(primarySwatch: Colors.blue),
home: new FlutterDemo(),
),
);
}
class FlutterDemo extends StatefulWidget {
FlutterDemo({Key key}) : super(key: key);
@override
_FlutterDemoState createState() => new _FlutterDemoState();
}
class _FlutterDemoState extends State {
int _counter;
@override
void initState() {
super.initState();
_readCounter().then((int value) {
setState(() {
_counter = value;
});
});
}
Future _getLocalFile() async {
// get the path to the document directory.
String dir = (await getApplicationDocumentsDirectory()).path;
return new File('$dir/counter.txt');
}
Future _readCounter() async {
try {
File file = await _getLocalFile();
// read the variable as a string from the file.
String contents = await file.readAsString();
return int.parse(contents);
} on FileSystemException {
return 0;
}
}
Future _incrementCounter() async {
setState(() {
_counter++;
});
// write the variable as a string to the file
await (await _getLocalFile()).writeAsString('$_counter');
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text('Flutter Demo')),
body: new Center(
child: new Text('Button tapped $_counter time${
_counter == 1 ? '' : 's'
}.'),
),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
),
);
}
} 網(wǎng)頁(yè)名稱:創(chuàng)新互聯(lián)Flutter教程:Flutter文件讀寫(xiě)
URL分享:http://fisionsoft.com.cn/article/djcgipp.html


咨詢
建站咨詢
