我试图在另一个类的另一个小部件内的类MealItem的返回承包商,我正确地导入了,我得到了
错误:未为“可迭代”类型定义运算符“[]”。尝试定义运算符'[]'。dartundefined_operator
这里是MealItem类
import 'package:flutter/material.dart';
import '../models/meal.dart';
class MealItem extends StatelessWidget {
final String title;
final String imageUrl;
final int duration;
final Complexity complexity;
final Affordability affordability;
MealItem(
this.title,
this.imageUrl,
this.duration,
this.complexity,
this.affordability
);
}
}
这是CategoryMealsScreen类中的错误import 'package:flutter/material.dart';
import '../widgets/meal_item.dart';
import '../models/dummy_data.dart';
class CategoryMealsScreen extends StatelessWidget {
static const routeName = '/CategoriesScreen';
//final String categoryId;
//final String categoryTitle;
//CategoryMealsScreen(this.categoryId,this.categoryTitle);
@override
Widget build(BuildContext context) {
final routeArgs =
ModalRoute.of(context).settings.arguments as Map<String, String>;
final categoryTitle = routeArgs['title'];
final categoryId = routeArgs['id'];
final categoryMeals = DUMMY_MEALS.where((meal) {
return meal.categories.contains(categoryId);
});
return Scaffold(
appBar: AppBar(title: Text(categoryTitle)),
body: ListView.builder(
itemBuilder: (ctx, index) {
return MealItem(
title : categoryMeals[index].title,
imageUrl: categoryMeals[index].imageUrl,
duration: categoryMeals[index].duration,
complexity: categoryMeals[index].complexity,
affordability: categoryMeals[index].affordability
);
},
itemCount: categoryMeals.length,
),
);
}
}
这是使用vsCode的IDE错误:The operator '[]' isn't defined for the type 'Iterable<Meal>'.
Try defining the operator '[]'.
任何帮助将不胜感激 最佳答案
您正在将名为参数的传递给采用位置参数的构造函数。
更改:
或在创建import 'package:flutter/material.dart';
import '../models/meal.dart';
class MealItem extends StatelessWidget {
final String title;
final String imageUrl;
final int duration;
final Complexity complexity;
final Affordability affordability;
// use parenthesis '{}' to wrap the constructor arguments to make them named arguments
MealItem({
this.title,
this.imageUrl,
this.duration,
this.complexity,
this.affordability
});
}
}
MealItem
时简单地删除名称并传递位置参数
另外:默认情况下,位置参数是required
,但命名参数不是。将它们更改为命名参数后,如果需要,不要忘记将它们标记为@required
也可以在此处使用toList()
:final categoryMeals = DUMMY_MEALS.where((meal) {
return meal.categories.contains(categoryId);
}).toList();