首页 文章

Dart代码在我的Flutter应用程序中的行为有所不同 . 列表<dynamic> ' is not a subtype of type ' List <Map <String,dynamic >>

提问于
浏览
1

当我在“Dart”中运行时,一切正常,我得到一份与会者名单 . 但是,当我在Flutter应用程序中调用它时,我收到错误:

flutter:类型'List'不是'List>类型的子类型

Dart中出现了“not a subtype”错误,我一直都是这样的 . 我终于能够让所有的强制类型转换为来自REST接口的json数据 .

有人能告诉我,为什么在Flutter中轰炸而在Dart中没有?我该如何解决这个问题?

Future<List<Attendee>> callLogin() async {
return http.get(
        "http://www.somesite.com")
    .then((response) {
  try {
    List<Attendee> l = new List();
    final List<Map<String, dynamic>> responseJson =
        json.decode(response.body)['attendees'];
    responseJson.forEach((f) => l.add(new Attendee.fromJson(f)));
    return l;
  } catch (e) {
    print(e);  // Just print the error, for SO
  }
});

}

class Attendee {
  String nameFirst;
  String nameLast;
  String company;
  ...
factory Attendee.fromJson(Map<String, dynamic> json) {
  return new Attendee(
    nameLast: json['nameLast'],
    nameFirst: json['tnameFirst'],
    company: json['company'],
    city: json['city'],
    state: json['state'],
    country: json['country'],
  );
}


class AttendeeSearch extends StatefulWidget {
  AttendeeSearch({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _AttendeeSearchPageState createState() => new 
  _AttendeeSearchPageState();
}

class _AttendeeSearchPageState extends State<AttendeeSearch> {

  String search;

  final _suggestions = new List<Attendee>();
  final _smallerFont = const TextStyle(fontSize: 12.0);
  final formKey = new GlobalKey<FormState>();

  void _submit() {
    final form = formKey.currentState;
    if (form.validate()) {
      form.save();
    }
    AttendeeSummaryRequest asr = new AttendeeSummaryRequest();
    setState(() {
      asr.callLogin().then((item) { // Calling WebService
      setState(() {
        _suggestions.addAll(item);  
      });
    });
  });
}

1 回答

  • 1

    对于遇到这个问题的人,我做了以下......

    Future<List<Attendee>> callLogin() async {
    return http.get(
        "http://www.somesite.com")
    .then((response) {
      try {
        List<Attendee> l = new List();
    
    //  final Map<String, dynamic> responseJson = // REPLACED 
        final dynamic responseJson =              // <<== REMOVED CAST to Map<String, dynamic>
                                                  // 
            json.decode(response.body)['attendees'];
        responseJson.forEach((f) => l.add(new Attendee.fromJson(f)));
        return l;
      } catch (e) {
        print(e);  // Just print the error, for SO
      }
    });
    

    通常我不会尝试回答我自己的问题 . 并且,在这种情况下,我仍然没有一个真正的答案为什么Flutter的行为不同于运行Dart main中的代码 . 我从Android Studio运行它们 . 所以,我认为Dart在两种情况下都是相同的版本 . 但是,这就是我接下来要看的地方 . 如果我有更多信息,我会发布 .

相关问题