无法将参数类型“ x”分配给参数类型“ x”

时间:2018-08-21 07:57:51

标签: json dart flutter

下面是我的模型课:

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"])
    );
  }
}

这是 DependantModel类

中的 EntitlementsModel

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 是一个包含多个Maps类的类。

1 个答案:

答案 0 :(得分:2)

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

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

“ YOUR_PACKAGE”应为pubspec.yml name变量中所述的应用程序名称。

该目录将构成从lib文件夹(不包括该文件夹)到导入的dart文件的所有文件夹。

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