How to save my current state by using json or something else in Flutter

陌路散爱 提交于 2021-02-08 08:52:08

问题


I want to know how to save my current state by modifying the existing JSON file. but I can't find a way to saving..... So I want to ask you about that.

The size of the JSON file is not so big. So I considered total - loading and total - saving when the loading and saving state is called. but I think it is not efficient and unstable... So can I get some help?


回答1:


please use this package https://pub.dev/packages/shared_preferences
Wraps NSUserDefaults (on iOS) and SharedPreferences (on Android), providing a persistent store for simple data. Data is persisted to disk asynchronously

example code

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

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Center(
      child: RaisedButton(
        onPressed: _incrementCounter,
        child: Text('Increment Counter'),
        ),
      ),
    ),
  ));
}

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


来源:https://stackoverflow.com/questions/57540694/how-to-save-my-current-state-by-using-json-or-something-else-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!