颤振数组循环列表



我正在制作自己的扑动应用程序,但我遇到了一个问题。我正在创建一个Breakfast类

class Breakfast {
String foodTitle;
String foodCalories;
Breakfast({this.foodTitle, this.foodCalories});
}

从这个类中创建一个包含该类对象的数组

class BreakfastFood {
List<Breakfast> _breakfastFoodData = [
Breakfast(
foodTitle: "Bread",
foodCalories: "100",
),
Breakfast(
foodTitle: "Soup",
foodCalories: "50",
),
];
int _foodTitle = 0;
int _foodCalories = 0;
String getFoodTitle() {
return _breakfastFoodData[_foodTitle].foodTitle;
}
String getFoodCalories() {
return _breakfastFoodData[_foodCalories].foodCalories;
}

}

我已经创建了一个组件来获取foodtitle和foodcalorie,并将它们放在一个小部件中。

现在我想创建一个函数,循环遍历_breakfastfoodData的对象并显示它们。但是我不知道如何循环遍历列表,并显示所有的对象彼此分开。

_breakfastFoodData在你的代码中是私有属性(因为它以_开头),你应该改为breakfastFoodData。

  • 使用ListView。构建列表的生成器:

    List<Breakfast> datas= new BreakfastFood().breakfastFoodData;
    return ListView.builder(
    itemCount: datas.length,
    itemBuilder: (context, index) {
    return ListTile(
    title: Text('${datas[index].foodTitle}'),
    );
    },
    );
    

你只需要像这样定义你的类:

class BreakfastFood {
List<Breakfast> _items = [
Breakfast(
foodTitle: "Bread",
foodCalories: "100",
),
Breakfast(
foodTitle: "Soup",
foodCalories: "50",
),
];
List<Breakfast> get items => [..._items];
}

然后调用它来显示所有项目:

BreakfastFood foodData = BreakfastFood();
ListView.builder(
itemCount: foodData.items.length,
itemBuilder: (ctx, index) {
return ListTile(
title: Text('${foodData.items[index].foodTitle}'),
subTitle: Text('${foodData.items[index].foodCalories}'),
);
}
)

相关内容

  • 没有找到相关文章

最新更新