gpt4 book ai didi

list - 如何从列表内部访问实例方法?

转载 作者:行者123 更新时间:2023-12-03 04:35:06 26 4
gpt4 key购买 nike

所以,我试图按类的特定方法对列表进行分组排序。我的代码目前以此类格式使用 Hive 存储“膳食”:
https://pub.dev/packages/hive

import 'package:hive/hive.dart';

part 'meal.g.dart';

@HiveType(typeId: 1, adapterName: "MealAdapter")
class MealModel{
@HiveField(0)
int id;
@HiveField(1)
String mealName;
@HiveField(2)
int calories;
@HiveField(3)
int carbohydrates;
@HiveField(4)
int protein;
@HiveField(5)
int fats;
@HiveField(6)
String day;

MealModel(this.id, this.mealName, this.calories, this.day, [this.carbohydrates, this.protein, this.fats]);
}
问题是当我不知道我会将值传递给 GroupedListView ( https://pub.dev/packages/grouped_list ) 的每个参数以显示存储的饭菜时:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:jaetrack/colors.dart';
import 'package:jaetrack/dbmodel/meal.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:grouped_list/grouped_list.dart';

class Meals extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return MealsState();
}
}

class MealsState extends State<Meals> {
Box<MealModel> mealBox = Hive.box<MealModel>('meals');
MealModel previousMeal;

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: mainPurp,
body: SingleChildScrollView(
child: Column(
children: [
ValueListenableBuilder(
valueListenable: Hive.box<MealModel>('meals').listenable(),
builder: (context, Box<MealModel> box, _) {
final mealList = box.values.toList().cast<MealModel>();
print(mealList);
return GroupedListView<dynamic, String>(
elements: mealList,
groupBy: (meal) => meal, // no idea how to sort by calories, name etc. of my MealModel class,
groupSeparatorBuilder: (String groupByValue) =>
Text(groupByValue), // date value
itemBuilder: (context, dynamic element) =>
Text(element['name']), // this is where I would put the meal names/calories etc.
itemComparator: (item1, item2) =>
item1['name'].compareTo(item2['name']), // sort by date is what I'm looking for but again I don't know how to access
useStickyGroupSeparators: true,
floatingHeader: true,
order: GroupedListOrder.ASC,
);
})
],
),
),
);
}
}
因此,如果我仍然没有意义,我将我的 hive 盒饭菜的值作为上述 MealModel 的实例。所以列表就像[MealModel 实例,MealModel 实例,...] 我只需要知道如何访问 MealModel 实例内部的值以传递给 GroupedList。

最佳答案

package:grouped_list图书馆正在使用 dynamic在他们的所有示例中,以简化没有泛型的人的使用。但在你的情况下这是一种误导,你正在失去强类型。
投到

return GroupedListView<MealModel, String>(
代替
return GroupedListView<dynamic, String>(
那么你所有的 element , mealitem2变量将是 MealModel你可以做 element.mealName , 和 meal.calories按卡路里分组
对于排序问题,只需排序 mealList在将其传递给 GroupedListView 之前

关于list - 如何从列表内部访问实例方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64300414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com