【问题标题】:The argument type 'X' can't be assigned to the parameter type 'X' dartargument_type_not_assignable参数类型“X”不能分配给参数类型“X”dartargument_type_not_assignable
【发布时间】:2021-10-25 11:47:30
【问题描述】:

由于用户出错,我无法运行我的系统。并且在 ListTile Text(plant.name) 中也是错误的。参数类型“字符串?”不能分配给参数类型“字符串”。有人可以帮我吗?

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

我的 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."
        }
    ]
  

我使用 json 的数据类将其转换为 dart

【问题讨论】:

  • 尝试将植物名称更改为植物名称?? " ";
  • 先生怎么样作为回报 buildPlants(users);我这里有一个错误,要求我添加“!”
  • 只使用“!”当你 100% 确定它永远不会返回 null 时,我不知道你的 api,但我建议使用“??”代替,这意味着如果它为 null,它会返回其他东西,在你的情况下你可以放一个空类或带有占位符数据的东西
  • 对于一些必填字段,例如 id,您可以为空字段。我认为最好重新设计您的数据类。快速修复---标题:文本(植物名称!),
  • rosh-dev 我的数据类。仅由 Visual Studio Code 的扩展自动生成。数据类生成器

标签: json flutter dart


【解决方案1】:

Future builder 将始终具有可为空的数据类型,即 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 是一个可以为空的字符串。

因此,要解决此问题,您可以给它一个默认值(如果它为 null,即 plant.name ?? 'default'),或者在您的类中将类型更改为不可为空。

【讨论】:

  • 您好,先生。它仍然显示“一些错误”
  • 如果它显示'Some error',那么这是因为快照没有数据,即PlantsApi.getPlantsLocally(context)方法没有正常工作。能否调试并检查该方法是否返回正确的输出?
  • 我尝试将两者都更改为 buildPlants(snapshot.data!) 然后错误是 null 检查运算符用于空值 futurebuilder
  • 是的,else 流将意味着快照没有数据,即 data = null。我的意思是检查方法本身,检查数据是否正确解析
  • 数据类的解析。使用数据类生成器。
猜你喜欢
  • 2019-01-27
  • 2016-04-16
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-25
  • 1970-01-01
  • 2021-03-02
相关资源
最近更新 更多