做(zuò)自(zì)由與創造的先行(xíng)者

Flutter 文件讀寫

Flutter開(kāi)發手冊

介紹

PathProvider 插件提供了(le)一(yī)種平台透明(míng)的方式來訪問(wèn)設備文件系統上(shàng)的常用位置。該類當前支持訪問(wèn)兩個文件系統位置:

臨時(shí)目錄: 系統可(kě)随時(shí)清除的臨時(shí)目錄(緩存)。在iOS上(shàng),這(zhè)對應于NSTemporaryDirectory() 返回的值。在Android上(shàng),這(zhè)是getCacheDir()返回的值。

文檔目錄: 應用程序的目錄,用于存儲隻有自(zì)己可(kě)以訪問(wèn)的文件。隻有當應用程序被卸載時(shí),系統才會清除該目錄。在iOS上(shàng),這(zhè)對應于NSDocumentDirectory。在Android上(shàng),這(zhè)是AppData目錄。

一(yī)旦你的Flutter應用程序有一(yī)個文件位置的引用,你可(kě)以使用dart:ioAPI來執行(xíng)對文件系統的讀/寫操作(zuò)。有關使用Dart處理文件和(hé)目錄的更多信息,請(qǐng)參閱此概述 和(hé)這(zhè)些示例。

讀寫文件的示例

以下(xià)示例展示了(le)如(rú)何統計應用程序中按鈕被點擊的次數(shù)(關閉重啓數(shù)據不丢失):

通(tōng)過 flutter create 或在IntelliJ中 File > New Project 創建一(yī)個新Flutter App.

在pubspec.yaml文件中聲明(míng)依賴 PathProvider 插件

用一(yī)下(xià)代碼替換 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),

),

);

}

}

網站建設開(kāi)發|APP設計開(kāi)發|小程序建設開(kāi)發
下(xià)一(yī)篇:Flutter 網絡和(hé)Http
上(shàng)一(yī)篇:Flutter 平台特定的代碼