【问题标题】:Saving list of objects locally on device with shared_preferences in Flutter使用 Flutter 中的 shared_preferences 在设备上本地保存对象列表
【发布时间】:2022-12-10 13:25:42
【问题描述】:

我创建了一个可以发送红外信号的应用程序,您可以在其中自己添加红外信号。信号保存在一个名为 Item 的对象列表中,其中项目作为对象。我希望在应用程序运行时将名称和信号本地保存在设备上,但永远不会保存这些项目:这是代码:

import 'package:flutter/material.dart';
import 'package:ir_sensor_plugin/ir_sensor_plugin.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
import 'dart:convert';

class Item {
  String buttonName = "", hexCode = "";
  bool isSelected = false;

  Item({
    required this.buttonName,
    required this.hexCode,
  });

  // Method to convert the Item object to a JSON object
  Map<String, dynamic> toJson() {
    return {
      'buttonName': buttonName,
      'hexCode': hexCode,
      'isSelected': isSelected,
    };
  }

  // Method to convert a JSON object to an Item object
  static Item fromJson(Map<String, dynamic> json) {
    return Item(
      buttonName: json['buttonName'],
      hexCode: json['hexCode'],
    );
  }
}

class IrRemoteEmulator extends StatefulWidget {
  const IrRemoteEmulator({Key? key}) : super(key: key);

  @override
  State<IrRemoteEmulator> createState() => _IrRemoteEmulatorState();
}

class _IrRemoteEmulatorState extends State<IrRemoteEmulator> {
  String buttonName = "";
  TextEditingController _buttonName = TextEditingController();
  String hexCode = "";
  TextEditingController _hexCode = TextEditingController();

  List<Item> items = [
    Item(
        buttonName: "Samsung Power",
        hexCode:
            "0000 006d 0022 0003 00a9 00a8 0015 003f 0015 003f 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 003f 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0040 0015 0015 0015 003f 0015 003f 0015 003f 0015 003f 0015 003f 0015 003f 0015 0702 00a9 00a8 0015 0015 0015 0e6e"),
    Item(
        buttonName: "Prowise Power",
        hexCode:
            "0000 006d 0022 0003 00a9 00a8 0015 003f 0015 003f 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 003f 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0040 0015 0015 0015 003f 0015 003f 0015 003f 0015 003f 0015 003f 0015 003f 0015 0702 00a9 00a8 0015 0015 0015 0e6e")
  ];

  // Method to save the items list to the local storage
  Future<void> saveList(List<Item> items) async {
    // Get the instance of the shared preferences
    final prefs = await SharedPreferences.getInstance();

    // Convert the items list to a JSON string
    var itemsJson = json.encode(items);

    // Save the JSON string to the local storage
    prefs.setString('items', itemsJson);
    debugPrint("Items saved");
  }

  Future<List<Item>> loadList() async {
    // Get the instance of the shared preferences
    final prefs = await SharedPreferences.getInstance();

    // Retrieve the JSON string from the local storage
    var itemsJson = prefs.getString('items') ?? '';

    // Convert the JSON string to a List<Item> object
    var items = json.decode(itemsJson);
    debugPrint("Items loaded");
    return items;
  }

  String selectedHexcode =
      "0000 006d 0022 0003 00a9 00a8 0015 003f 0015 003f 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 003f 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0040 0015 0015 0015 003f 0015 003f 0015 003f 0015 003f 0015 003f 0015 003f 0015 0702 00a9 00a8 0015 0015 0015 0e6e";

  String _platformVersion = 'Unkown';
  bool _hasIrEmitter = false;
  String _getCarrierFrequencies = 'Unknown';

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

    // Load the saved items list from the local storage
    loadList().then((savedItems) {
      // Set the items list to the loaded list
      setState(() {
        items = savedItems;
      });
    });

    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    bool hasIrEmitter;
    String getCarrierFrequencies;

    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      platformVersion = await IrSensorPlugin.platformVersion;
      hasIrEmitter = await IrSensorPlugin.hasIrEmitter;
      getCarrierFrequencies = await IrSensorPlugin.getCarrierFrequencies;
    } on PlatformException {
      platformVersion = 'Failed to get data in a platform.';
      hasIrEmitter = false;
      getCarrierFrequencies = 'None';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
      _hasIrEmitter = hasIrEmitter;
      _getCarrierFrequencies = getCarrierFrequencies;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: Column(
            children: [
              const SizedBox(
                height: 25,
              ),
              const SizedBox(
                height: 15.0,
              ),
              Container(
                decoration:
                    BoxDecoration(border: Border.all(color: Colors.white)),
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    children: [
                      FloatingActionButton.large(
                        onPressed: () async {
                          final String result =
                              await IrSensorPlugin.transmitString(
                                  pattern: selectedHexcode);
                          debugPrint('Emitting  List Int Signal: $result');
                        },
                        child: const Icon(Icons.power_settings_new_outlined),
                      ),
                    ],
                  ),
                ),
              ),
              Expanded(
                child: SizedBox(
                  height: 200,
                  child: ListView.builder(
                    itemCount: items.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                        onTap: () {
                          items[index].isSelected = true;
                          selectedHexcode = items[index].hexCode;
                          debugPrint(items[index].hexCode);
                          setState(() {});
                        },
                        onLongPress: () {
                          items.remove(items[index]);
                          saveList(items);
                          setState(() {});
                        },
                        title: Text(items[index].buttonName),
                        leading: Icon((items[index].hexCode == selectedHexcode)
                            ? Icons.circle
                            : Icons.circle_outlined),
                      );
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton.extended(
          onPressed: () => showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: const Text("Add IR Hexcode"),
              content: Column(
                children: <Widget>[
                  TextFormField(
                    controller: _buttonName,
                    decoration: InputDecoration(
                        labelText: "Remotebutton name",
                        hintText: "Ac Powerbutton",
                        hintStyle: TextStyle(color: Colors.grey[300])),
                  ),
                  TextFormField(
                    controller: _hexCode,
                    decoration: InputDecoration(
                        labelText: "Hexcode",
                        hintText:
                            "0000 006d 0022 0003 00a9 00a8 0015 003f 0015 003f 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 003f 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0040 0015 0015 0015 003f 0015 003f 0015 003f 0015 003f 0015 003f 0015 003f 0015 0702 00a9 00a8 0015 0015 0015 0e6e",
                        hintStyle: TextStyle(color: Colors.grey[300])),
                  ),
                ],
              ),
              actions: [
                TextButton(
                  child: const Text("Cancel"),
                  onPressed: () => Navigator.pop(context),
                ),
                TextButton(
                  child: const Text("Ok"),
                  onPressed: () {
                    if (_hexCode.text.isEmpty || _buttonName.text.isEmpty) {
                      debugPrint("${(items.length)}");
                    } else {
                      items.add(Item(
                        buttonName: _buttonName.text,
                        hexCode: _hexCode.text,
                      ));
                      saveList(items);
                      debugPrint("${(items)}");
                    }
                    Navigator.pop(context);

                    setState(() {});
                    return;
                  },
                ),
              ],
            ),
          ),
          label: const Text("Add IR Hexcode"),
          icon: const Icon(Icons.add),
        ),
      ),
    );
  }
}

我尝试添加 Shared_preferences 但是当我添加了一个新信号并重新打开应用程序时,整个应用程序被重置并且我没有看到新添加的信号。谁能帮我?

【问题讨论】:

    标签: json flutter flutter-sharedpreference


    【解决方案1】:

    在

    Future<void> saveList(List<Item> items) async {
      // Get the instance of the shared preferences
      final prefs = await SharedPreferences.getInstance();
    
      // Convert the items list to a JSON string
      var itemsJson = json.encode(items);
    
      // Save the JSON string to the local storage
      prefs.setString('items', itemsJson);
      debugPrint("Items saved");
    }
    

    您不是在保存项目,而是在更新它们(因为setString 替换了在SharedPreferences 中按键存储的所有数据)。而SharedPreferences 不是存储用户数据的好解决方案(因为它们是为存储偏好而设计的,它不是数据库)。为了您的目的,您需要使用数据库。如果数据量不大,使用hive。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-10
      • 2021-03-29
      • 1970-01-01
      • 2021-05-19
      • 2021-12-02
      • 1970-01-01
      • 2014-02-23
      • 2022-11-27
      相关资源
      最近更新 更多