dart 使用hive和flutter存储待办事项列表

new9mtju  于 2023-11-14  发布在  Hive
关注(0)|答案(1)|浏览(132)

我是一个完整的菜鸟扑所以这一个可能对你来说很容易.我正试图将Hive集成到我的应用程序,所以我可以在本地存储信息.然而,我不知道我会怎么做.这是我到目前为止,我是如此卡住.如果你能告诉我在代码中添加/删除/更改的东西,那将是伟大的.
主要功能

import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';

void main() async {
  await Hive.initFlutter();
  Hive.registerAdapter(TodoAdapter());
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Builder(
        builder: (context) {
          return GestureDetector(
            onTap: () {
              FocusScope.of(context).unfocus();
            },
            child: const TodoApp(),

字符串
TODO CLASS ETC

class Todo {
  final String text;
  final bool checked;
  int priority;
  static int _tasknumber = 0;
  final int key;
//TODO: UNDERSTAND THIS
  Todo({
    required this.text,
    required this.checked,
    required this.priority,
  }) : key = _tasknumber++;
}

class TodoAdapter extends TypeAdapter<Todo> {
  @override
  final int typeId = 0;

  @override
  Todo read(BinaryReader reader) {}

  @override
  void write(BinaryWriter writer, Todo obj) {}
}

class TodoApp extends StatefulWidget {
  const TodoApp({super.key});

  @override
  State<TodoApp> createState() => _TodoAppState();
}

class _TodoAppState extends State<TodoApp> {
  final _textyController = TextEditingController();
  List<Todo> data = [];
  int? _radioValue = 1;
  bool isEditing = false;
  int editingIndex =
      -1; // Initialize as -1 to indicate no active edit initially.
  bool isContainerVisible = false;
  bool settingsVisibility = false;

  var box = await Hive.openBox<Todo>('todoBox');
  box.add(yourTodo);
  var todos = box.values.toList;
  box.putAt(index, updatedTodo);
  box.deleteAt(index);
  await box.close;

  final FocusNode _textFocus = FocusNode();
  void dispose() {
    _textFocus.dispose();
    super.dispose();
  }

  @override
  void initState() {
    _textFocus.addListener(() {
      setState(() {
        isContainerVisible = _textFocus.hasFocus;
      });
    });
  }


编辑/编辑功能

SlidableAction(
                                    backgroundColor: Colors.green,
                                    icon: Icons.edit,
                                    //label: 'Edit',
                                    onPressed: (context) => {
                                      setState(() {
                                        isEditing = true;
                                        editingIndex = index;
                                        _textyController.text =
                                            data[index].text;
                                        _radioValue = data[index].priority;
                                        _textFocus.requestFocus();
                                      }),
                                    },
                                  ),
                                  SlidableAction(
                                    backgroundColor:
                                        Colors.red[400] ?? Colors.red,
                                    icon: Icons.delete_forever,
                                    //label: 'Delete',
                                    onPressed: (context) => {
                                      setState(() {
                                        if (isEditing &&
                                            editingIndex >= 0 &&
                                            editingIndex < data.length) {
                                          isEditing = false;
                                          _textyController.text = '';
                                          _radioValue = 1;
                                          Slidable.of(context)?.close();
                                        }
                                        deleteTasks(index, data[index]);
                                      }),
                                    },
                                  ),


向列表中添加新数据

Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              Radio(
                                value: 1,
                                groupValue: isEditing
                                    ? data[editingIndex].priority
                                    : _radioValue,
                                onChanged: (changedRadio) {
                                  setState(() {
                                    if (isEditing) {
                                      data[editingIndex].priority =
                                          changedRadio ?? 1;
                                    } else {
                                      _radioValue = changedRadio;
                                    }
                                    _textFocus.requestFocus();
                                  });
                                },
                                fillColor:
                                    MaterialStateProperty.all(Colors.red),
                              ),
                              //Text('High'),
                            ],
                          ),
child: TextField(
                    focusNode: _textFocus,
                    controller: isEditing
                        ? TextEditingController(text: data[editingIndex].text)
                        : _textyController,
                    onSubmitted: (value) {
                      setState(() {
                        if (isEditing) {
                          data[editingIndex] = Todo(
                            text: value,
                            checked: data[editingIndex].checked,
                            priority: data[editingIndex].priority,
                          );
                          isEditing = false;
                        } else {
                          data.insert(
                              0,
                              Todo(
                                text: value,
                                checked: false,
                                priority: _radioValue ?? 0,
                              ));
                        }
                        _textyController.clear();
                        _textFocus.requestFocus();
                        _textyController.selection = TextSelection.fromPosition(
                            TextPosition(offset: _textyController.text.length));
wr98u20j

wr98u20j1#

请在这里查看官方文档。
您可以在您的州创建一个新框,例如:

class _TodoAppState extends State<TodoApp> {
  ...
  late final Box<Todo> todoBox;
  ...

  @override
  void initState() async {
    todoBox = await Hive.openBox<Todo>('todos');
  }

字符串
然后,要在小部件中获取todos,可以使用ValueListenableBuilder,如以下示例所示:https://pub.dev/packages/hive#hive--flutter

...
  
  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: todoBox.listenable(),
      builder: (context, box, widget) {
        // TODO: handle todoBox here

        return Switch(
          value: todoBox.get('darkMode'),
          onChanged: (val) {
            todoBox.put('darkMode', val);
          }
        );
      },
    );
  }
}


但请记住,只有在添加以下pub时,Box<E>中的.listenable()方法才可用:https://pub.dev/packages/hive_flutter

相关问题