Using hive with flutter to store to do list

120 views Asked by At

Im a complete noob to flutter so this one might be easy for you. I am trying to integrate Hive into my app so I can store the information locally. However, I am not sure how I would do this. This is what I have so far and I am so stuck. If you could show me where in the code to add/remove/change things, that would be great.

MAIN FUNCTION

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;
      });
    });
  }

EDIT / DELETE FUNCTIONS

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]);
                                      }),
                                    },
                                  ),

ADDING NEW DATA TO LIST

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));
1

There are 1 answers

0
Emanuel Balaban On

Please check the official documentation here.

You can create a new box in your State such as:

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

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

Then to get the todos in your widget, you can use ValueListenableBuilder as in this example: 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);
          }
        );
      },
    );
  }
}

But keep in mind that .listenable() method from Box<E> is only available if you add the following pub: https://pub.dev/packages/hive_flutter