【问题标题】:The argument type 'x' can't be assigned to the parameter type 'x'参数类型“x”不能分配给参数类型“x”
【发布时间】:2019-01-27 08:58:37
【问题描述】:

下面是我的模型类:

crm_dependent_list_model.dart(模型类)

import 'crm_dep_entitlement_model.dart';

class DependantModel{

  String name;
  String relationship;
  EntitlementsModel entitlements;

  DependantModel({this.name, this.relationship, this.entitlements});

  factory DependantModel.fromJson(Map depjson){

    return DependantModel(
      name: depjson["Name"].toString(),
      relationship: depjson["Relationship"].toString(),
      entitlements: EntitlementsModel.fromJson(depjson["Entitlements"])
    );
  }
}

这是 EntitlementsModel 位于 DependantModel 类

crm_dep_entitlement_model.dart

class EntitlementsModel{

  final GP gp;
  final OPS ops;
  final IP ip;
  final Dental dental;
  final Optical optical;
  final EHS ehs;

  EntitlementsModel({this.gp, this.ops, this.ip, this.dental, this.optical, this.ehs});

  factory EntitlementsModel.fromJson(Map ejson){

    return EntitlementsModel(

      gp: GP.fromJson(ejson["GP"]),
      ops: OPS.fromJson(ejson["OPS"]),
      ip: IP.fromJson(ejson["IP"]),
      dental: Dental.fromJson(ejson["Dental"]),
      optical: Optical.fromJson(ejson["Optical"]),
      ehs: EHS.fromJson(ejson["EHS"])
    );
  }

}


//GP class
class GP{

  final String entitlement, utilisation, balance;

  GP({this.entitlement, this.utilisation, this.balance});

  factory GP.fromJson(Map gjson){

    return GP(
      entitlement: gjson["Entitlement"].toString(),
      utilisation: gjson["Utilisation"].toString(),
      balance:  gjson["Balance"].toString()
    );
  }
}


//OPS class
class OPS{

  final String entitlement, utilisation, balance;

  OPS({this.entitlement, this.utilisation, this.balance});

  factory OPS.fromJson(Map gjson){

    return OPS(
        entitlement: gjson["Entitlement"].toString(),
        utilisation: gjson["Utilisation"].toString(),
        balance:  gjson["Balance"].toString()
    );
  }
}

//IP class
class IP{

  final String entitlement, utilisation, balance;

  IP({this.entitlement, this.utilisation, this.balance});

  factory IP.fromJson(Map gjson){

    return IP(
        entitlement: gjson["Entitlement"].toString(),
        utilisation: gjson["Utilisation"].toString(),
        balance:  gjson["Balance"].toString()
    );
  }
}


//Dental class
class Dental{

  final String entitlement, utilisation, balance;

  Dental({this.entitlement, this.utilisation, this.balance});

  factory Dental.fromJson(Map gjson){

    return Dental(
        entitlement: gjson["Entitlement"].toString(),
        utilisation: gjson["Utilisation"].toString(),
        balance:  gjson["Balance"].toString()
    );
  }
}


//Optical class
class Optical{

  final String entitlement, utilisation, balance;

  Optical({this.entitlement, this.utilisation, this.balance});

  factory Optical.fromJson(Map gjson){

    return Optical(
        entitlement: gjson["Entitlement"].toString(),
        utilisation: gjson["Utilisation"].toString(),
        balance:  gjson["Balance"].toString()
    );
  }
}


//EHS class
class EHS{

  final String entitlement, utilisation, balance;

  EHS({this.entitlement, this.utilisation, this.balance});

  factory EHS.fromJson(Map gjson){

    return EHS(
        entitlement: gjson["Entitlement"].toString(),
        utilisation: gjson["Utilisation"].toString(),
        balance:  gjson["Balance"].toString()
    );
  }
}

这个模型类目前被用来从这个类的 JSON 中拉取数据:

Fifth.dart(调用 JSON 数据的类)

import 'package:flutter/material.dart';
import 'package:emas_app/Dependant.dart' as Dep;
import 'model/crm_dependent_list_model.dart';
import 'dart:convert';
import 'dart:async';
import 'package:http/http.dart' as http;

final String url = "http://crm.emastpa.com.my/MemberInfo.json";

//Future to get list of dependent names
Future<List<DependantModel>> fetchUserInfo() async{

  http.Response response = await http.get(url);
  var responsejson = json.decode(response.body);

  return(responsejson[0]['Dependents'] as List)
      .map((user) => DependantModel.fromJson(user))
      .toList();
}

class Fifth extends StatefulWidget {
  @override
  _FifthState createState() => _FifthState();
}

class _FifthState extends State<Fifth> {

  static Future<List<DependantModel>> depState;

  @override
  void initState() {
    depState = fetchUserInfo();
    super.initState();
  }

    @override
  Widget build(BuildContext context) {

      //ListView.builder inside FutureBuilder
      var futureBuilder = new FutureBuilder(
          future: depState,
          builder: (context, snapshot){
            switch(snapshot.connectionState){
              case ConnectionState.none:
              case ConnectionState.waiting:
                return new Center(
                  child: new CircularProgressIndicator(),
                );
              default:
                if(snapshot.hasError){
                  return new Text(snapshot.error);
                }else{

                  List<DependantModel> user = snapshot.data;

                  return new ListView.builder(
                      itemCount: user.length,
                      itemBuilder: (context, index){

                        return new Column(
                          children: <Widget>[
                            new ListTile(
                              title: new Text(user[index].name,
                                  style: TextStyle(fontSize: 20.0)),
                              subtitle: new Text(user[index].relationship,
                                  style: TextStyle(fontSize: 15.0)),
                              trailing: new MaterialButton(color: Colors.greenAccent,
                                  textColor: Colors.white,
                                  child: new Text("More"),
                                  onPressed: (){
                                    Navigator.push(context,
                                        new MaterialPageRoute(builder: (context) => Dep.Dependents(name: user[index].name, entitlementsModel: user[index].entitlements))
                                    );
                                  }
                              ),
                            )
                          ],
                        );
                      });
                }
            }
          });

      return new Scaffold(
          body: futureBuilder,
      );
  }
}

Fifth.dart 类将通过该类中的构造函数发送数据:

Dependent.dart(带有构造函数的类)

import 'model/crm_dep_entitlement_model.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'model/crm_dependent_list_model.dart';
import 'package:flutter/foundation.dart';

final String url = "http://crm.emastpa.com.my/MemberInfo.json";

//Future method to fetch information
Future<EntitlementsModel> fetchEntitlements() async{

  final response =  await http.get(url);
  final jsonresponse = json.decode(response.body);

  var res = jsonresponse[0]["Dependents"][0]["Entitlements"];

  return EntitlementsModel.fromJson(jsonresponse[0]["Dependents"][0]["Entitlements"]);
}

//void main() => runApp(Dependents());
class Dependents extends StatefulWidget {

  final String name;
//  final Map entitlement;
  final EntitlementsModel entitlementsModel;

  //Constructor to accept the value from Fifth.dart
//  Dependents({Key key, this.name, this.dependantModel) : super(key: key);
  Dependents({Key key, this.name, this.entitlementsModel}) : super(key:key);

  @override
  _DependentsState createState() => _DependentsState();
}

class _DependentsState extends State<Dependents> {

  Future<EntitlementsModel> entitlement;

  @override
  void initState() {
    entitlement = fetchEntitlements();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    //new body widget
    Widget body = new Container(
      child: new Center(
        child: new FutureBuilder(
            future: entitlement,
            builder: (context, snapshot){
              if(snapshot.hasData){
                var entitledata = snapshot.data;

                //retrieve data from snapshot
                var gpentitlement = entitledata.gp.entitlement;
                var gputilisation = entitledata.gp.utilisation;
                var gpbalance = entitledata.gp.balance;

                var opsentitle = entitledata.ip.entitlement;
                var opsutilisation = entitledata.ip.utilisation;
                var opsbalance = entitledata.ip.balance;

                return new Column(
                  children: <Widget>[
                    new ListTile(
                      title: new Text("Name: "),
                      subtitle: new Text("${widget.name}"),
                    )  ,
                    new Divider(
                      color: Colors.black,
                    ),
                    new ListTile(
                      title: new Text("Clinic GP",
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ) ,
                    new ListTile(
                      title: new Text("Entitlement"),
                      trailing: new Text(gpentitlement),
                    ),
                    new ListTile(
                      title: new Text("Utilisation"),
                      trailing: new Text(gputilisation),
                    ),
                    new ListTile(
                      title: new Text("Balance"),
                      trailing: new Text(gpbalance),
                    ),
                    new Divider(
                      color: Colors.black,
                    ),
                    new ListTile(
                      title: new Text("IP",
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    new ListTile(
                      title: new Text("Entitlement"),
                      trailing: new Text(opsentitle),
                    ),
                    new ListTile(
                      title: new Text("Utilisation"),
                      trailing: new Text(opsutilisation),
                    ),
                    new ListTile(
                      title: new Text("Balance"),
                      trailing: new Text(opsbalance),
                    ),
                  ],
                );


              }else if(snapshot.hasError){
                return new Text(snapshot.error);
              }

              //loading the page
              return new Center(
                child: new CircularProgressIndicator(),
              );
            }),
      ),
    );

    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('${widget.name}'),
          ),
          body: body
      ),
    );
  }
}

这是我遇到的错误:

compiler message: lib/Fifth.dart:72:155: Error: The argument type '#lib1::EntitlementsModel' can't be assigned to the parameter type '#lib2::EntitlementsModel'.
compiler message: Try changing the type of the parameter, or casting the argument to '#lib2::EntitlementsModel'.
compiler message:                                         new MaterialPageRoute(builder: (context) => Dep.Dependents(name: user[index].name, entitlementsModel: user[index].entitlements))
compiler message:

还有:

I/flutter ( 6816): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 6816): The following assertion was thrown building FutureBuilder<List<DependantModel>>(dirty, state:
I/flutter ( 6816): _FutureBuilderState<List<DependantModel>>#bdb2c):
I/flutter ( 6816): type 'NoSuchMethodError' is not a subtype of type 'String'

我的问题是:

我该如何解决这个错误,因为它说我应该转换参数,但我不知道如何解决,因为 EntitlementsModel 是一个包含多个地图类的类。

【问题讨论】:

  • 不仔细查看您的代码 - 请确保您在 lib/main.dart 中没有相对导入,并且您没有在任何地方导入 main.dart
  • @GünterZöchbauer 是的,我已经检查过了,我没有在任何地方导入 main.dart。
  • main.dart 中的相对导入怎么样(导入不以 'dart:...''package:...' 开头)

标签: json dart flutter


【解决方案1】:

EntitlementsModel 的导入似乎存在冲突。尝试将所有导入重写为以下形式:

import 'package:YOUR_PACKAGE/../...dart'

'YOUR_PACKAGE' 应该是应用程序的名称,如 pubspec.yml name 变量中所述。

以及从lib文件夹(不包括它)到导入的dart文件的所有文件夹的目录结构。

(您在 Fifth.dart 文件的第二行使用此导入方案)

【讨论】:

  • 我也尝试将导入重写为您所指的表单,但没有解决问题。
  • 您是否在所有文件中都这样做了,而不仅仅是在 Fifth.dar 中?当你在#lib1和#lib2中出现相同类型的错误时,通常是因为它认为类型来自不同的库,通常是因为使用了不同的导入机制。
  • 我已经设法修复了库错误。几次尝试后以某种方式更改包导入工作。谢谢你。
  • 尝试查看我发布的第二个错误。 FutureBuilder>(dirty, state: I/flutter (6816): _FutureBuilderState>#bdb2c): I/flutter (6816): type 'NoSuchMethodError' is not a subtype 是什么意思'字符串'类型的
  • 尝试去掉depState这个静态变量,直接在FutureBuilder中使用fetchUserInfo()
猜你喜欢
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-25
  • 1970-01-01
  • 2021-03-02
  • 2019-09-12
相关资源
最近更新 更多