简体   繁体   中英

Store data in dart/flutter

I am coding a to-do list app in flutter but every time I close the app, all my to-do's are gone, and none of them are stored. How do I stop them from disappearing every time I close the app?

Apps generally store data in temporary storage which destroyed every time yo close the app. in order to save data permanently, you could use sqflite database or shared_preferences database

if you want use shared_preferences, you can do this: first make class that call StorageManager:

import 'package:shared_preferences/shared_preferences.dart';

class StorageManager {
  static Future<bool> saveData(String key, dynamic value) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.reload();
    if (value is int) {
      prefs.setInt(key, value);
      return true;
    } else if (value is String) {
      prefs.setString(key, value);
      return true;
    } else if (value is bool) {
      prefs.setBool(key, value);
      return true;
    } else {
      return false;
    }
  }

  static Future<dynamic> readData(String key) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.reload();
    dynamic obj = prefs.get(key);
    return obj;
  }

  static Future<bool> deleteData(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.remove(key);
  }

  static Future<void> reloadSharedPreferences() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.reload();
  }
}

then use it like this: when you want save some thing in storage call this:

await StorageManager.saveData('some unique key', your int or string or bool value);

when you want read from storage:

var result = await StorageManager.readData('some unique key');
    if (result != null) {
      // use your value
    } else {
      // this means there is no result
    }

Use sqlite or files. Please refer documentation on cookbooks for either approach.

https://docs.flutter.dev/cookbook/persistence

Your other option is to use an external database over the internet

To persist your data (todo list) you can either

  1. store data on the users device

You can do this by using a local databases like sqflite , sqfentity , shared_preferences etc

  1. or store the data on the server

Using this option you can either spin up your own server or use some quick serverless solutions like supabase or cloud firestore from firebase.

I recommend hive it's very easy to use and it's lightweigh.

In addition with all the other propositions, you can try Isar, which is a NoSQL local database that can be used for all platforms:

https://isar.dev/tutorials/quickstart.html

https://pub.dev/packages/isar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM