【问题标题】:Flutter array looping listFlutter 数组循环列表
【发布时间】:2021-05-06 13:23:26
【问题描述】:

我正在制作自己的颤振应用程序,但遇到了问题。我正在创建一个早餐课程

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 和 foodCalories 并将它们放入一个小部件中。

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

【问题讨论】:

  • 我认为您可以使用 listview.builder 并利用它的 index 属性来循环遍历数组中的所有 ojc。
  • 您的信息不足。您是否知道 _breakfastfoodData 属性是隐藏/私有的?你需要一个方法来访问它并循环它(for)。

标签: flutter dart


【解决方案1】:

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

  • 您使用 ListView.builder 来构建您的列表:

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

【讨论】:

    【解决方案2】:

    你只需要在这里定义你的类:

    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}'),
        );
      }
    )
    

    【讨论】:

      猜你喜欢
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多