【问题标题】:The argument type 'List<Plants>?' can't be assigned to the parameter type 'List<Plants>'参数类型 'List<Plants>?'不能分配给参数类型“List<Plants>”
【发布时间】:2021-12-10 03:19:03
【问题描述】:
Widget build(BuildContext context) => Scaffold(
    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);
          }
        }
      }, 
    ),
  );

我对这个有误。用户是错误的

当我将 buildPlants(users) 更改为 buildPlants(users!) 时,我收到此错误:

 Error: Member not found: 'fromJson'.
    return body.map<Plants>(Plants.fromJson).toList();
                                   ^^^^^^^^
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'package:oplantapp/model/plantData.dart';

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>(Plants.fromJson).toList();
  }
}

这是我的获取数据

【问题讨论】:

    标签: json flutter dart parsing


    【解决方案1】:

    我认为您没有在 Plants 类中实现 Plants.fromJson 方法。参考official documentation

    ...
    Plants.fromJson(Map<String, dynamic> json)
          : name = json['name'],
            email = json['email'];
    ...
    

    植物中实现Plants.fromJson 方法后。尝试更改您的退货声明

    return body.map<Plants>((e) => Plants.fromJson(e)).toList();
    

    【讨论】:

    • 感谢 Error: Member not found: 'fromJson' 的错误。 return body.map(Plants.fromJson).toList(); ^^^^^^^^ 是固定的。谢谢。
    猜你喜欢
    • 2021-07-04
    • 2021-10-24
    • 2022-11-05
    • 2021-11-05
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 2021-11-06
    相关资源
    最近更新 更多