0

hey I get Null Error when I try to edit after deleting an Item in HiveDB on swipe in listview

import 'package:notes_app/HiveDB/hive_crud.dart';
import 'package:notes_app/Model/notes_model.dart';
import 'package:notes_app/components/toast.dart';

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

  @override
  State<NotesList> createState() => _NotesListState();
}

class _NotesListState extends State<NotesList> {
  // late NotesModel? notesModel;
  late HiveCRUD hiveCRUD;
  List noteListFromDB = [];
  bool isAnimating = false;
  @override
  initState() {
    super.initState();
    hiveCRUD = HiveCRUD();
    _loadNotes();
    // TODO: implement initState
  }

  Future<void> _loadNotes() async {
    // await hiveCRUD.init();
    setState(() {
      noteListFromDB = hiveCRUD.getAllData();
    });
  }

@override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: noteListFromDB.length,
      itemBuilder: (context, index) {
        if (isAnimating) return Container();
        final NotesModel note = noteListFromDB[index];

        return Dismissible(
          key: Key(noteListFromDB[index].toString()),
          direction: DismissDirection.endToStart,
          onDismissed: (direction) async {
            await hiveCRUD.deleteData(index: index);
            setState(() {
              isAnimating = true;
              noteListFromDB.removeAt(index);
            });
            // _loadNotes();
            toast(context: context, message: "Note Deleted Successfully");
          },
          child: ListTile(
            onTap: () {
              if (index >= noteListFromDB.length) return;
              Navigator.pushNamed(
                context,
                '/notes',
                arguments: index.toString(),
              );
            },

title: Container(
              margin: EdgeInsets.only(bottom: 8.0),
              decoration: BoxDecoration(
                color: note.color,
                borderRadius: BorderRadius.circular(16),
                border: Border.all(
                  style: BorderStyle.solid,
                  color: Colors.white,
                ),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            note.title ?? '',
                            style: TextStyle(
                              fontFamily: note.fontFamily ?? '',
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                              color: Colors.white,
                            ),
                          ),
                          Divider(height: 2, color: Colors.white),
                          Padding(
                            padding: const EdgeInsets.only(top: 8.0),
                            child: Text(
                              '${note.description?.characters.take(150).toString()}...' ??
                                  '',
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),      ],
              ),
            ),
          ),
        );
      },
    );
  }
}
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:notes_app/Model/notes_model.dart';

class HiveCRUD {
  Box<NotesModel>? noteBox;

  HiveCRUD() {
    init();
  }

  Future<void> init() async {
    if (Hive.isBoxOpen('NotesBox')) {
      noteBox = Hive.box<NotesModel>('NotesBox');
      return;
    }
    noteBox = await Hive.openBox<NotesModel>('NotesBox');
  }

  void addData({myNotes, colorString}) async {
    try {
      await noteBox?.add(myNotes);
      // print(colorString);
      // Color newColor = colorCreation(colorString);
      // print("New Color: $newColor");
      // print(notesBox.values.toString());
    } catch (e) {
      print(e);
    }
  }

  void updateData({index, myNotes, colorString}) async {
    try {
      await noteBox?.put(index, myNotes);
      getAllData();
    } catch (e) {
      print(e);
    }
  }

  Color colorCreation(String colorString) {
    print("Color Creation");
    Color color = Color(
      int.parse(colorString.replaceFirst('#', '0x'), radix: 16),
    );
    return color;
  }

  NotesModel? getData(int index) {
    return noteBox!.get(index);
  }

  List<NotesModel> getAllData() {
    List<NotesModel> test = noteBox!.values.cast<NotesModel>().toList();
    print('Retrieved ${test.length} notes');
    return test;
  }

  Future<void> deleteData({index}) async {
    await noteBox?.deleteAt(index);
    getAllData();
    return;
  }
}

so once I remove an Index my notesBox and List variable it does not sync index, means

-note 1 -note 2 -note 3 -note 4 -note 5

so if I remove note 3, it removes -note1 -note2 -note4 -note5

but when I try to click on note4, it gives me "Unexpected Null" and when I try to edit note5, it picks ID of Note4 and opens it up for me to edit where its suppose to open note 5 for editing if i click on notes 5

so from NoteList.dart above code something is wrong while deleting data

2
  • noteListFromDB is probably out of sync. You call hiveCRUD.deleteData(index: index) and also noteListFromDB.removeAt? Hows that supposed to not go terribly wrong? Maybe also try to copy the lists when you assign them, as in Dart Lists assignments do not actually copy the elements, just pass a "pointer" to the elements. Thats always a source of these kind of problems with Lists. Commented Mar 19 at 7:29
  • 1
    well what I tried is instead of accessing index I am deleting using note.key from HiveDB and now its working fine, I guess ealier it was accessing list index which because null because hiveDB index was 3 and list index after update was 2 so it would give me null since index are mismatching, but its working and that's all matters no errors thank god Commented Mar 20 at 18:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.