Flutter - 本地存储

使用库:shared_preferences、path_provider

在pubspec.yaml中导入:

dependencies:
  #本地存储、plist
  shared_preferences: ^0.5.6+1
  #本地存储、file
  path_provider: ^1.6.0

示例代码:

void main() => runApp(Storage());

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:io';

//本地存储、plist
import 'package:shared_preferences/shared_preferences.dart';
//本地存储、file
import 'package:path_provider/path_provider.dart';

class Storage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: StoragePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class StoragePage extends StatefulWidget {
  StoragePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _StoragePageState createState() => _StoragePageState();
}

class _StoragePageState extends State {
  int _counter = 0;
  SharedPreferences prefs;

  @override
  void initState() {
    super.initState();
    _pathPro();
  }

  _incrementCounter() async {
    setState(() {
      _counter++;
    });

    prefs = await SharedPreferences.getInstance();
    int counter = (prefs.getInt('counter') ?? 0) + 1;
    print('Pressed $counter times.');
    await prefs.setInt('counter', counter);
    writeCounter(_counter);
  }

  _getPrefs() async {
    print(await readCounter());
    if (prefs != null) {
      Fluttertoast.showToast(
          msg: 'get prefs' + prefs.getInt('counter').toString(),
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIos: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0);
    }
  }

  _pathPro() async {
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = tempDir.path;
    print('tempPath = $tempPath');

    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path;
    print('appDocPath = $appDocPath');
  }

//找到正确的本地路径
  Future get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

// 创建对文件位置的引用
  Future get _localFile async {
    final path = await _localPath;
    return new File('$path/counter.txt');
  }

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

// 从文件中读取数据
  Future readCounter() async {
    try {
      final file = await _localFile;
      // Read the file
      String contents = await file.readAsString();
      return contents;
      // return int.parse(contents);
    } catch (e) {
      // If we encounter an error, return 0
      return '0';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'You have pushed PATHText $_counter the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
            RaisedButton(onPressed: _getPrefs, child: Icon(Icons.add_location))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

你可能感兴趣的:(Flutter - 本地存储)