如何在此 Todo 应用程序代码中使用共享首选项?

问题描述 投票:0回答:3
import 'package:flutter/material.dart';
import '../main.dart';
import 'colors.dart';
import 'todo_item.dart';
import 'todo.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

  @override
  State<Toodoo> createState() => _ToodooState();
}

class _ToodooState extends State<Toodoo> {
  final todosList = ToDo.todoList();
  List<ToDo> _foundToDo = [];
  final _todoController = TextEditingController();
  final GlobalKey<ScaffoldState> _key = GlobalKey();
String ""
  @override
  void initState() {
    _foundToDo = todosList;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _key,
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.menu, color: Colors.black),
          onPressed: () => _key.currentState!.openDrawer(),
        ),
          backgroundColor: const Color(0xff346594),
        title: const Text("ToDos", style: TextStyle(color: Colors.black)),
      ),
      backgroundColor: tdBGColor,
      body: Stack(
        children: [
          Container(
            padding: const EdgeInsets.symmetric(
              horizontal: 20,
              vertical: 15,
            ),
            child: Column(
              children: [
                searchBox(),
                Expanded(
                  child: ListView(
                    children: [
                      Container(
                        margin: const EdgeInsets.only(
                          top: 50,
                          bottom: 20,
                        ),
                        child: const Text(
                          'All ToDos',
                          style: TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                      for (ToDo todo in _foundToDo.reversed)
                        ToDoItem(
                          todo: todo,
                          onToDoChanged: _handleToDoChange,
                          onDeleteItem: _deleteToDoItem,
                        ),
                    ],
                  ),
                )
              ],
            ),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Row(children: [
              Expanded(
                child: Container(
                  margin: const EdgeInsets.only(
                    bottom: 20,
                    right: 20,
                    left: 20,
                  ),
                  padding: const EdgeInsets.symmetric(
                    horizontal: 20,
                    vertical: 5,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    boxShadow: const [
                      BoxShadow(
                        color: Colors.grey,
                        offset: Offset(0.0, 0.0),
                        blurRadius: 10.0,
                        spreadRadius: 0.0,
                      ),
                    ],
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: TextField(
                    controller: _todoController,
                    decoration: const InputDecoration(
                        hintText: 'Add a new todo item',
                        border: InputBorder.none),
                  ),
                ),
              ),
              Container(
                margin: const EdgeInsets.only(
                  bottom: 20,
                  right: 20,
                ),
                child: ElevatedButton(
                  onPressed: () {
                    _addToDoItem(_todoController.text);
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: tdBlue,
                    minimumSize: const Size(60, 60),
                    elevation: 10,
                  ),
                  child: const Text('+', style: TextStyle(fontSize: 40),),
                ),
              ),
            ]),
          ),
        ],
      ),
      drawer: const Navigation(),
    );
  }

  void _handleToDoChange(ToDo todo) {
    setState(() {
      todo.isDone = !todo.isDone;
    });
  }

  void _deleteToDoItem(String id) {
    setState(() {
      todosList.removeWhere((item) => item.id == id);
    });
  }

  void _addToDoItem(String toDo) async{
    final sp = await SharedPreferences.getInstance();
    setState(() {
      todosList.add(ToDo(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        todoText: toDo,
      ));
    });
    sp.setString(id, todo)
    _todoController.clear();
  }

  void _runFilter(String enteredKeyword) {
    List<ToDo> results = [];
    if (enteredKeyword.isEmpty) {
      results = todosList;
    } else {
      results = todosList
          .where((item) => item.todoText!
          .toLowerCase()
          .contains(enteredKeyword.toLowerCase()))
          .toList();
    }

    setState(() {
      _foundToDo = results;
    });
  }

  Widget searchBox() {
    return Container(
      
    );
  }
  }

我正在尝试使用共享首选项在本地保存待办事项数据,但不知道如何实现这一点,对此的任何帮助将不胜感激。共享首选项是在此类应用程序中使用的最佳选择,因此这就是我使用共享首选项的原因偏好而不是 firebase。

我将来已经初始化了共享首选项,但问题是如何使用代码上面给出的控制器读取和显示数据。

flutter sharedpreferences
3个回答
1
投票

使用Hive数据库sqflite来保存此类数据(很好的做法)。您应该使用

shared preference
来存储一小堆数据。


0
投票

是的,共享首选项是将数据永久存储在本地设备上的好方法。我可以建议你一种方法来做到这一点。

您只需要创建一个键(和值),并且该值将是一个字符串化数组。每次用户创建新的待办事项时,您首先需要拉取之前的数组,将其解析为 JSON,将最新的待办事项推送到该数组中,然后再次设置键值。

如果您想通过仅从一个键提取数据来向用户显示所有待办事项,此数组也会帮助您,因为所有待办事项将存储在一个数组中。

var todos = [
  {
    "id": "", 
    "todoText": "''"
  },
    {
    "id": "", 
    "todoText": "''"
  },
  ...
]

但是您需要存储字符串化数组,因此从共享首选项获取数据后需要解析回 JSON


0
投票

处理小数据时,共享偏好是一个好主意。示例:

        // NB: you need to have shared_preferences in your packages (pubspec.yaml)
            class SharedPreferencesFunction{
            // save String, example: 'John', 'I love coding, it is fun' and so on
                 void saveString({required String key, required String value}) async {
                final SharedPreferences sharedPreferences =
                    await SharedPreferences.getInstance();
                await sharedPreferences.setString(key, value);
              }
            // save bool example: true, or false
              void saveBool({required String key, required bool value}) async {
                final SharedPreferences sharedPreferences =
                    await SharedPreferences.getInstance();
                await sharedPreferences.setBool(key, value);
              }
            // save int, numbers without points. like 1,50, 100 not 0.9, or
              //zero point other something(number)
              void saveInt({required String key, required int value}) async {
                final SharedPreferences sharedPreferences =
                    await SharedPreferences.getInstance();
                await sharedPreferences.setInt(key, value);
              }
            
              // save double, number with decimal point. like 9.0, 10.5, e.t.c
              void saveDouble({required String key, required double value}) async {
                final SharedPreferences sharedPreferences =
                    await SharedPreferences.getInstance();
                await sharedPreferences.setDouble(key, value);
              }
            
              // save List<String> a list of Strings. more like ['paul', 'john', 'jack'];
              void saveListOfString({
                required String key,
                required List<String> value,
              }) async {
                final SharedPreferences sharedPreferences =
                    await SharedPreferences.getInstance();
                await sharedPreferences.setStringList(key, value);
              }
            }
    
    Now to retrieve save this data you need to simply call that above method 
    like this: 
    
    
    class MyClass {
    // your other codes, 
    void saveString(String someValue){
       SharedPreferencesFunction().saveString(key:'learning', value: someValue);
    }
    // and others like that, according your data. // bool, int, double, 
     // List<String>, .... and so on 
    // remember to use this code according to your data type needs, but your data  // has to be (bool, String, int, double,List<String>) if you happen to have a // map and you want to save it, don't try to use the following code
    final Map<String, Object> info = {
    'name':'john',
    'age':'20',
    };
    // error 
    final String data = info.toString();
    // and save it like 
    saveString(data); // it is possible to save this data but you won't be able // to retrieve it for use later. 
    
    // instead use import 'dart:convert' show json;
    like  
    final String data = json.encode(info);
    // retrieve using json.decode
    }
    
    
    // finally retrieving data is simple
    
    class RetrieveData{
    void data()async{
    final sharedPref= await SharedPreferences.getInstance();
    sharedPref.getString('learning'); 
// this returns a String ? might be null if the value is absent 
    }
    }
© www.soinside.com 2019 - 2024. All rights reserved.