Flutter | reorderableelistview与Hive的最佳实践是什么?



我想在Flutter应用程序中保留Hive的收藏夹列表。用户可以使用reorderableelistview更改列表的顺序。但是Hive似乎是按键排序的,我们不能存储列表的顺序。

基本上我们用下面的代码实现了ReorderableListView。

onReorder: (int oldIndex, int newIndex) {
setState(() {
if (oldIndex < newIndex) {
newIndex -= 1;
}
final int item = _items.removeAt(oldIndex);
_items.insert(newIndex, item);
});
},

Hive不支持插入。

当我们想要用hive存储列表数据时,最好的做法是什么?

有一个类似的问题,但它的答案将与键冲突,颤振将输出错误。颤振,Hive -如何在Hive中保存重排序列表

class SortStudentsPage extends StatefulWidget {
final String title;
final List<int> students;
const SortStudentsPage({
Key? key,
required this.title,
required this.students,
}) : super(key: key);
@override
State<SortStudentsPage> createState() => _SortStudentsPageState();
}
class _SortStudentsPageState extends State<SortStudentsPage> {
List<int> students=[];
@override
void initState() {
super.initState();
students=widget.students;
}
@override
Widget build(BuildContext context) {
int groupId = (ModalRoute.of(context)!.settings.arguments
as Map<String, dynamic>)['id'];
return WillPopScope(
onWillPop: () async {
StorageService myStorage = StorageService();
await myStorage.setGroup(
groupId,
students.map((e) => e).toList(),
);
return Future.value(true);
},
child: Scaffold(
appBar: AppBarWidget(
title: widget.title,
isNavigate: true,
),
body: ReorderableListView.builder(
itemBuilder: (context, index) {
return Card(
key: Key(students[index].toString()),
child: ListTile(
title: Text(students[index].toString()),
),
);
},
itemCount: students.length,
onReorder: (oldIndex, newIndex) {
if (oldIndex < newIndex) {
newIndex -= 1;
}
int student = students[oldIndex];
students.removeAt(oldIndex);
students.insert(newIndex, student);
setState(() {});
},
),
),
);
}
}

存储服务

class StorageService {
Future<void> setGroup(int groupId, List<int> contacts) async {
await Hive.box("groups").put("$groupId", contacts);
}
List<int>? getGroup(int groupId) {
return Hive.box("groups").get('$groupId');
}
static Future<void> init() async {
final appDocumentDir = await getApplicationDocumentsDirectory();
Hive.init(appDocumentDir.path);
await Hive.openBox("groups");
}

main.dart

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await StorageService.init();
runApp(const MyApp());
}

相关内容

最新更新