0

I have listviewBuilder , I want sorting my listview based on DateCreate with this code

taskList.sort((a, b) => -a.dateCreate.compareTo(b.dateCreate));

Everything is fine, i can see my list Sort (Descending) based on DateCreate, But the problem is everytime i delete/update the list, the action is wrong index!

It's without Sort (Working)

enter image description here

It's using Sort (Failed !!!)

enter image description here

If you see in Failed gif , I want deleted index 0 , But index 1 is deleted. If without Sort list is fine.

I surely passing right index, because in Working gif, i can successfully delete right index.

How can i fix this ?

ListviewBuilder Source Code :

SingleChildScrollView(
          child: Column(
            children: <Widget>[
              WatchBoxBuilder(
                box: Hive.box("task_box"),
                builder: (ctx, box) {
                  if (box.isEmpty) {
                    return Container(
                      margin: EdgeInsets.symmetric(
                        vertical: mqHeight / 8,
                        horizontal: 8,
                      ),
                      height: mqHeight / 3.5,
                      width: double.infinity,
                      alignment: Alignment.topCenter,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          fit: BoxFit.cover,
                          image: const AssetImage("assets/images/empty.png"),
                        ),
                      ),
                      child: Text(
                        'Task Empty , Add Someone',
                        style: textTheme.title
                            .copyWith(color: Colors.black.withOpacity(.5)),
                        textAlign: TextAlign.center,
                      ),
                    );
                  } else {
                    final taskList = box.values.toList().cast<TaskModel>();
                    taskList
                        .sort((a, b) => -a.dateCreate.compareTo(b.dateCreate));
                    return Container(
                      margin: EdgeInsets.symmetric(
                        vertical: mqHeight / 8,
                        horizontal: 8,
                      ),
                      child: ListView.builder(
                        shrinkWrap: true,
                        itemCount: taskList.length,
                        physics: NeverScrollableScrollPhysics(),
                        itemBuilder: (BuildContext context, int index) {
                          final taskValue = taskList[index];

                          return CardOddCustom(
                            idTask: taskValue.idTask,
                            codeIcon: taskValue.codeIcon,
                            titleTask: taskValue.titleTask,
                            imagePath: taskValue.imageTask,
                            dateCreate: taskValue.dateCreate,
                            indexTask: index,
                          );

                        },
                      ),
                    );
                  }
                },
              )
            ],
          ),
        ),

Deleting Code

  void deleteCategory({@required int indexBox}) async {
    final hiveBox = Hive.box(taskBox);
    await hiveBox.deleteAt(indexBox);
    notifyListeners();
  }

Onpressed Function :

class CardOddCustom extends StatefulWidget {
  final DateTime idTask;
  final String titleTask;
  final String imagePath;
  final DateTime dateCreate;
  final int codeIcon;
  final int indexTask;
  CardOddCustom({
    this.idTask,
    this.titleTask,
    this.imagePath,
    this.dateCreate,
    this.codeIcon,
    this.indexTask,
  });

  @override
  _CardOddCustomState createState() => _CardOddCustomState();
}

class _CardOddCustomState extends State<CardOddCustom> {
 return InkResponse(
      onLongPress: () =>
          taskProvider.deleteCategory(indexBox: widget.indexTask),
      child: Card(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topRight: Radius.circular(80),
            bottomRight: Radius.circular(80),
          ),
        ),
2
  • Share the code snippet of deleting item Commented Jan 5, 2020 at 15:14
  • @Vamsi Please see my updated. Commented Jan 6, 2020 at 0:33

1 Answer 1

1

taskList is a copy of Hive.box

taskList = box.values.toList().cast<TaskModel>();

when you do taskList.sort, Hivebox data still keep in original sequence

taskList.sort((a, b) => -a.dateCreate.compareTo(b.dateCreate));

You do not use box.put or box.putAll to persist the change
When you do hiveBox.deleteAt, it actually with sequence in HiveBox

await hiveBox.deleteAt(indexBox);

You can use key when you do put/get/delete

Edit
In offical example , the key is the same when you do put
"dave" is key for put/get/delete

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';

class PersonAdapter extends TypeAdapter<Person> {
  @override
  final typeId = 1;

  @override
  Person read(BinaryReader reader) {
    var numOfFields = reader.readByte();
    var fields = <int, dynamic>{
      for (var i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
    };
    return Person()
      ..name = fields[0] as String
      ..age = fields[1] as int
      ..friends = (fields[2] as List)?.cast<String>();
  }

  @override
  void write(BinaryWriter writer, Person obj) {
    writer
      ..writeByte(3)
      ..writeByte(0)
      ..write(obj.name)
      ..writeByte(1)
      ..write(obj.age)
      ..writeByte(2)
      ..write(obj.friends);
  }
}

@HiveType(typeId: 1)
class Person {
  @HiveField(0)
  String name;

  @HiveField(1)
  int age;

  @HiveField(2)
  List<String> friends;

  @override
  String toString() {
    return '$name: $age';
  }
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  var dir = await getApplicationDocumentsDirectory();
  Hive
    ..init(dir.path)
    ..registerAdapter(PersonAdapter());

  var box = await Hive.openBox('testBox');

  var person = Person()
    ..name = 'Dave'
    ..age = 22
    ..friends = ['Linda', 'Marc', 'Anne'];

  var current = DateTime.now().toString();
  await box.put(current, person);

  print(box.get(current)); // Dave: 22
}
Sign up to request clarification or add additional context in comments.

10 Comments

await hiveBox.deleteAt() only accept int, but my type idTask is DateTime it's not suits, but i try change to await hiveBox.delete(idTask) it's not working. nothing happens
In offical example , the key is the same when you do put, how do you deal with put? you can use it as key , in example 'dave', you can see my edited answer.
It's make sense, i use await hiveBox.add() to adding data. gist.github.com/zgramming/6ac43f9d697892dfd750f3c13c5d634d
/// Saves the [value] with an auto-increment key. Future<int> add(E value); source code say add use auto-increment key
In your case, I would suggest use put(key, your data) and pass this key to delete function
|

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.