我正在制定一份雜貨購物清單。用戶應能夠通過單擊將配方成分添加到串列中。假設我們有兩個包含以下成分的食譜:
食譜一:3個蘋果、2個香蕉、50克酸奶
食譜 2:2 個蘋果、1 個面包、50 克奶油芝士
目前我的代碼是我獲取串列項的地方:
@override
Widget build(BuildContext context){
return Scaffold(
backgroundColor: Colors.grey[900],
body: ValueListenableBuilder(
valueListenable: Hive.box('shopping').listenable(),
builder: (context, __box, _) {
var __box = Hive.box('shopping');
final shoppingTransactions = __box.values.toList();
print('shopping Transactions list is ${shoppingTransactions}');
for (var i=0; i<shoppingTransactions.length; i ) {
List flatList = shoppingTransactions.expand((i) => i).toList();
flatList 的輸出是:
flutter: final individual list is [3 apples, 2 bananas, 50 g yogurt, 2 apples, 1 bread, 50 g cream cheese]
在串列視圖中,我想顯示以下內容:
5 apples
2 bananas
50g yogurt
1 bread
50g cream cheese
如何拆分串列項以便能夠對成分進行分組并將它們匯總以在串列視圖中顯示它們?
uj5u.com熱心網友回復:
你可以ListView.builder
這樣使用:
ListView.builder(
itemCount: flatList.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(flatList[index]),
);
},
),
這將簡單地制作串列中所有元素的串列視圖
希望這可以幫助
uj5u.com熱心網友回復:
首先像這樣創建模型類:
class Ingredient {
final int count;
final String name;
const Ingredient({
required this.count,
required this.name,
});
factory Ingredient.fromString(String str) {
var strList = str.split(' ');
int _count = int.parse(strList[0]);
strList.removeAt(0);
String _name = '';
for (var element in strList) {
_name = _name element ' ';
}
return Ingredient(
count: _count,
name: _name,
);
}
}
然后像這樣使用它:
List<Ingredient> ingredients = flatList.map((e) => Ingredient.fromString(e)).toList();
List<Ingredient> finalIngredients = [];
for (var item in ingredients) {
var index = 0;
bool addedBefore = false;
for (var element in finalIngredients) {
if (element.name == item.name) {
addedBefore = true;
break;
} else {
index ;
}
}
if (addedBefore) {
finalIngredients[index] = Ingredient(
count: finalIngredients[index].count item.count,
name: finalIngredients[index].name);
} else {
finalIngredients.add(item);
}
}
print("apples=${finalIngredients[0].count}"); //apples=5
然后用于finalIngredients
在 中顯示您的串列listview
。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505429.html