参数类型'X'不能分配给参数类型"X"dartargument_type_not_assignable



我不能运行我的系统,因为在用户上有一个错误。并且在ListTile Text(plant.name)中也是错误的。参数类型是'String?'不能分配给参数类型'String'。有人能帮帮我吗?

The argument type 'List<Plants>?' can't be assigned to the parameter type 'List<Plants>'.dartargument_type_not_assignable List<Plants>? users
body: FutureBuilder<List<Plants>>(
future: PlantsApi.getPlantsLocally(context),
builder:(context, snapshot) {
final users = snapshot.data;
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
if (snapshot.hasError) {
return Center(child: Text('Some error'),);
}
else {
return buildPlants(users);
}
}
}, 

Widget buildPlants(List<Plants> plants) => 
ListView.builder(

itemCount: plants.length,
itemBuilder: (context, index) {
final plant = plants[index];
return 

ListTile (
title: Text(plant.name),
);
}
);

my fetch api


class PlantsApi {
static Future<List<Plants>> getPlantsLocally(BuildContext context) async {
final assetBundle = DefaultAssetBundle.of(context);
final data = await assetBundle.loadString('assets/plants.json');
final body = json.decode(data);
return body.map<Plants>((e) => Plants.fromJson(e)).toList();
}
}
这是使用数据类 的json示例
[
{
"id": 1,
"name": "ALOCASIA-ELEPHANT EARS",
"image": "assets/images/ALOCASIA.jpeg",
"descript": "Alocasia plant (Alocasia mortfontanensis) is a hybrid species between Alocasia longiloba and Alocasia sanderiana. The Alocasia is known for its large leaves and wide variety of cultivars within the species. Alocasia plant is native to tropical Asia and Australia.",
"charac": [{
"planttype": "Herb",
"lifespan": "Perennial",
"bloomtime": "Spring, summer",
"plantheight": "1-2 feet",
"spread": "7 feet",
"leafColor": "PurpleGreenGreySilver"
}
],
"scienclass": [
{
"genus": "Alocasia - Elephant's-ears, Taro, Kris plant",
"family": " Araceae - Arum, Aroids ",
"order": "Alismatales - Water plantains and allies",
"classes": "Liliopsida - Monocotyledons, Monocots ",
"phylum":"Tracheophyta - Vascular plants, Seed plants, Ferns, Tracheophytes"
}
],
"pestdesease": " Stem rot, crown rot, root rot, leaf spot, mealy bugs, aphids",
"requirements":[{
"difficultyrating": "Alocasia plant is super easy to take care of, with resistance to almost all pests and diseases. It is a perfect option for gardeners with brown thumbs.",
"sunlight": "Full shade to partial sun",
"hardenesszone": " 9-11 ",
"soil": "Loose, fertile and well-drained humus soil"
}
],
"careguide":[
{
"water": "Moisture-loving, keep the soil moist but do not let water accumulate.",
"fertilizaton": "Fertilization once in spring. ", 
"pruning": "Fertilization once in spring. ", 
"plantingtime": "Spring, summer, autumn ",
"propagation": "Division ",
"pottingsuggestion": " Needs excellent drainage in pots."
}
],
"toxictohuman": "Is the alocasia plant poisonous for humans? The sap of alocasia plant is toxic to humans topically and when ingested. When the leaves are chewed or swallowed, symptoms may include swelling, stinging, and irritation of the mouth and gastrointestinal tract. In rare cases, it can cause swelling of the upper airway and difficulty breathing. Contact with the sap can also lead to skin irritation where the contact occurred. Poisoning is most likely to occur from accidental ingestion of the leaves or rough handling of the plant, particularly by children. Alocasia plant is often encountered as an ornamental plant in gardens or as a houseplant."
},
{
"id": 2,
"name": "Sample Sample",
"image": "assets/images/ALOCASIA.jpeg",
"descript": "Alocasia plant (Alocasia mortfontanensis) is a hybrid species between Alocasia longiloba and Alocasia sanderiana. The Alocasia is known for its large leaves and wide variety of cultivars within the species. Alocasia plant is native to tropical Asia and Australia.",
"charac": [{
"planttype": "Herb",
"lifespan": "Perennial",
"bloomtime": "Spring, summer",
"plantheight": "1-2 feet",
"spread": "7 feet",
"leafColor": "PurpleGreenGreySilver"
}
],
"scienclass": [
{
"genus": "Alocasia - Elephant's-ears, Taro, Kris plant",
"family": " Araceae - Arum, Aroids ",
"order": "Alismatales - Water plantains and allies",
"classes": "Liliopsida - Monocotyledons, Monocots ",
"phylum":"Tracheophyta - Vascular plants, Seed plants, Ferns, Tracheophytes"
}
],
"pestdesease": " Stem rot, crown rot, root rot, leaf spot, mealy bugs, aphids",
"requirements":[{
"difficultyrating": "Alocasia plant is super easy to take care of, with resistance to almost all pests and diseases. It is a perfect option for gardeners with brown thumbs.",
"sunlight": "Full shade to partial sun",
"hardenesszone": " 9-11 ",
"soil": "Loose, fertile and well-drained humus soil"
}
],
"careguide":[
{
"water": "Moisture-loving, keep the soil moist but do not let water accumulate.",
"fertilizaton": "Fertilization once in spring. ", 
"pruning": "Fertilization once in spring. ", 
"plantingtime": "Spring, summer, autumn ",
"propagation": "Division ",
"pottingsuggestion": " Needs excellent drainage in pots."
}
],
"toxictohuman": "Is the alocasia plant poisonous for humans? The sap of alocasia plant is toxic to humans topically and when ingested. When the leaves are chewed or swallowed, symptoms may include swelling, stinging, and irritation of the mouth and gastrointestinal tract. In rare cases, it can cause swelling of the upper airway and difficulty breathing. Contact with the sap can also lead to skin irritation where the contact occurred. Poisoning is most likely to occur from accidental ingestion of the leaves or rough handling of the plant, particularly by children. Alocasia plant is often encountered as an ornamental plant in gardens or as a houseplant."
}
]

我使用data类将json转换为dart

将来的生成器将始终具有可空的数据类型,即snapshot.data的类型为[your_type]?。因此,代码必须编写如下:

FutureBuilder<List<Plants>>(
future: PlantsApi.getPlantsLocally(context),
builder:(context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
if (snapshot.hasData) {
return buildPlants(snapshot.data!)
} else {
return Center(child: Text('Some error'),);
}

}
}

关于Text(plant.name)的问题,这是因为Text小部件需要一个非空字符串,但您的Plant类的name是一个可空字符串。

所以要解决这个问题,你可以给它一个默认值,如果它是空的,即plant.name ?? 'default',或者你改变类型为非空在你的类。

The argument type 'List<Plants>?' can't be assigned to the parameter type 'List<Plants>'

注意?。这表明您试图传递的值可能为空值,但是接收器只接受植物列表(List<Plants>没有最终的?)。

你可以重构你的代码,这样你传递给你的函数的变量永远不会是空的,并将它实例化为List<Plants> yourVariable = aListOfPlants。一种想法是将默认值设置为空列表= List<Plant>[]

如果上面的解决方案不可行,你可以断言你的参数不为空,使用bang!,如:

yourFunctionWhichDoesNotAcceptNullValues(variableWhichIsInstantiatedAsNullable!).

这将允许您编译并继续,但您应该手动防止null被传递到yourFunctionWhichDoesNotAcceptNullValues

相关内容