【问题标题】:Saving State After App Is Closed with Provider Package FLUTTER使用提供程序包 FLUTTER 关闭应用程序后保存状态
【发布时间】:2020-05-08 04:19:01
【问题描述】:

使用 Flutter 提供程序包保存活动页面状态的最佳方法是什么?目前,使用提供程序包并重新启动或关闭应用程序会重建页面并删除所有新小部件。状态保存在热重载而不是热重启时。例如,当我关闭或重新启动应用时,用户在新闻提要页面上创建的帖子会被删除。

【问题讨论】:

标签: flutter dart state


【解决方案1】:

所以按照评论并阅读flutter persistence cookbook,我看到了三种常见的可能性:

  • 使用 SQLite 持久化数据
  • 读写文件
  • 在磁盘上存储键值数据

每个都有不同的用例,但我认为常见的情况是将一些对象存储为 JSON。在我看来,SQLite 在简单的情况下有点矫枉过正,而且键值不能提供足够的灵活性。所以我会关注reading and writing files

这里有一个例子。我使用 JSON 代码生成库作为described here

我读写到磁盘的数据对象如下所示:

import 'package:json_annotation/json_annotation.dart';

// json methods generated using code geneartion
// see https://flutter.dev/docs/development/data-and-backend/json#serializing-json-using-code-generation-libraries
part 'easy_data.g.dart';

@JsonSerializable()
class EasyData {
    int counter;
    String data;

    EasyData(this.counter, this.data);

  // run the following command to generate json:
  // flutter pub run build_runner build
  factory EasyData.fromJson(Map<String, dynamic> json) => _$EasyDataFromJson(json);

  Map<String, dynamic> toJson() => _$EasyDataToJson(this);
}

从磁盘加载 json 并保存的服务如下所示:

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

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

import '../model/easy_data.dart';

class FileStorage with ChangeNotifier {
  EasyData loadedData;

  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

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

  loadData() async {
    try {
      final file = await _localFile;
      // Read the file
      String contents = await file.readAsString();
      if (contents != null) {
        // parse json if file was saved before
        loadedData = EasyData.fromJson(json.decode(contents));
        notifyListeners();
      }
    } on FileSystemException catch (_) {
      // the file did not exist before
    } catch (e) {
      // error handling
      log(e);
    }
  }

  Future<File> writeData(EasyData data) async {
    final file = await _localFile;
    // Write the file
    return file.writeAsString(jsonEncode(data.toJson()));
  }
}

我为服务使用了provider,因为我希望在从磁盘加载数据时通知其他服务。其他 Provider 需要在 main dart 中用 ChangeNotifierProxyProvider 声明,才能使用来自 FileStorage Provider 的信息。

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 2022-01-05
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多