Flutter Getx 在本地存储数据

Flutter Getx Store Data locally

我目前正在开发一款用户可以将 ListTimes 标记为收藏夹的应用程序。 然后,这些收藏夹会显示在第二页上。

我正在为此使用 GetX,并且该功能有效。但是一旦应用程序关闭,应用程序的状态就会重置,收藏夹也会被删除。

有谁知道如何在本地存储收藏夹?

这是我的代码:

GetX 控制器:

import 'package:get/state_manager.dart';

class FavouriteController extends GetxController {
  var favItems = <Entries>[].obs;
  int get count => favItems.length;

  addToCart(Entries product) {
    favItems.add(product);
  }

收藏夹页面:

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


class Favs extends StatelessWidget {
  final favouritesController = Get.put(FavouriteController());
  final entriesController = Get.put(EntriesController());

  Favs({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: backGround,
      appBar: AppBar(
        backgroundColor: appbarColor,
        title: const Text('Favs'),
      ),
      body: SafeArea(
        child: Column(
          children: [
            const SizedBox(height: 10),
            Expanded(
              child: GetX<FavouriteController>(
                builder: (controller) {
                  return ListView.builder(
                    itemCount: controller.favItems.length,
                    itemBuilder: (context, index) {
                      return Card(
                          margin: const EdgeInsets.all(12),
                          color: container,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(15.0)),
                          child: ListTile(
                            title: Text(
                              controller.favItems[index].name,
                              style: const TextStyle(
                                  fontSize: 16, color: Colors.white),
                            ),
                            trailing: IconButton(
                              onPressed: () {
                                favouritesController
                                    .deleteEntries(controller.favItems[index]);
                              },
                              icon: const Icon(
                                Icons.delete_forever,
                                color: titleColor,
                              ),
                            ),
                            onTap: () {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => controller
                                          .favItems[index].navigation));
                            },
                          ));
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

使用 sqflite,您可以在设备上存储数据。

终端机:

flutter pub add sqflite and flutter pub get

import 'package:sqflite/sqflite.dart';
// Get a location using getDatabasesPath
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');

// Delete the database
await deleteDatabase(path);

// open the database
Database database = await openDatabase(path, version: 1,
    onCreate: (Database db, int version) async {
  // When creating the db, create the table
  await db.execute(
      'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});

// Insert some records in a transaction
await database.transaction((txn) async {
  int id1 = await txn.rawInsert(
      'INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)');
  print('inserted1: $id1');
  int id2 = await txn.rawInsert(
      'INSERT INTO Test(name, value, num) VALUES(?, ?, ?)',
      ['another name', 12345678, 3.1416]);
  print('inserted2: $id2');
});

// Update some record
int count = await database.rawUpdate(
    'UPDATE Test SET name = ?, value = ? WHERE name = ?',
    ['updated name', '9876', 'some name']);
print('updated: $count');

// Get the records
List<Map> list = await database.rawQuery('SELECT * FROM Test');
List<Map> expectedList = [
  {'name': 'updated name', 'id': 1, 'value': 9876, 'num': 456.789},
  {'name': 'another name', 'id': 2, 'value': 12345678, 'num': 3.1416}
];
print(list);
print(expectedList);
assert(const DeepCollectionEquality().equals(list, expectedList));

// Count the records
count = Sqflite
    .firstIntValue(await database.rawQuery('SELECT COUNT(*) FROM Test'));
assert(count == 2);

// Delete a record
count = await database
    .rawDelete('DELETE FROM Test WHERE name = ?', ['another name']);
assert(count == 1);

// Close the database
await database.close();

(是引号)

更详细的信息:https://pub.dev/packages/sqflite