',flutter,dart"/>

首页 > 解决方案 > Flutter 应用程序无法调用 API。未处理的异常:键入“列表”' 不是类型 'Map 的子类型'

问题描述

我正在开发一个使用外部 API 链接的颤振应用程序。但是每当我尝试访问 API 时,它都会显示以下错误:

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

以下是我的代码:

Future GetSurvey() async {

    var txtfieldresponse = surveyidcontroller.text;
    var apisurveyid;


    if(isNumeric(txtfieldresponse) == true){
      if(rememberMe == true){ //rememberME is  a checkbox if it is checked all the under operations are performed
        var response = await http.get(
            apilink,
            headers: {
              "Accept": "application/json"
            }
        );
        if (response.statusCode == 200) {
          // If the server did return a 200 OK response,
          // then parse the JSON.
          Map<String, dynamic> map = json.decode(response.body);
          Surveyuuidget surveyuuidget = new Surveyuuidget.fromjson(map);
          if(surveyuuidget.surveyid == apisurveyid){
            var surveyuuid = surveyuuidget.surveyuuid;
            Navigator.push(context, MaterialPageRoute(builder: (context) => DescPage(description,surveyidcontroller.text)));
          }

        } else {
          // If the server did not return a 200 OK response,
          // then throw an exception.
          throw Exception('Please enter a valid survey ID');
        }
      }
    }


  }


class Surveyuuidget{
  String surveyid;
  String surveyuuid;

  Surveyuuidget({this.surveyid,this.surveyuuid});

  factory Surveyuuidget.fromjson(Map<String, dynamic> json){
    return new Surveyuuidget(
        surveyid: json['SurveyId'],
        surveyuuid: json['json']
    );
  }

}

class uuidlist{
  List<Surveyuuidget> list;

  uuidlist({
    this.list
  });

  factory uuidlist.fromjson(List<dynamic> json){

    List<Surveyuuidget> list1 = new List<Surveyuuidget>();
    list1 = json.map((e) => Surveyuuidget.fromjson(e)).toList();
    return new uuidlist(
      list: list1
    );
  }

}

以下是我的 API 结构:

[{"SurveyId":"1","SurveyUUIID":"284ba-4d51-b98f-0355f190914c"},
 {"SurveyId":"2","SurveyUUIID":"284ba-4d51-b98f-0355f190914c"},
 {"SurveyId":"3","SurveyUUIID":"2c74d40d-84ba-0355f190914c"}]

我想要surveyId 和SurveyUUIID,但它显示了上面给定的错误。有人可以帮我吗?

标签: flutterdart

解决方案


您可以在下面复制粘贴运行完整代码
因为返回类型List<Surveyuuidget>不是Surveyuuidget所以您可以调用
List<Surveyuuidget> surveyuuidgetList = surveyuuidgetFromJson(response.body);
And for 循环List<Surveyuuidget>来执行Navigate
代码片段

List<Surveyuuidget> surveyuuidgetFromJson(String str) =>
List<Surveyuuidget>.from(
    json.decode(str).map((x) => Surveyuuidget.fromJson(x)));
...
Future GetSurvey() async {
    String apisurveyid = "2";

    String jsonString = '''
        [{"SurveyId":"1","SurveyUUIID":"284ba-4d51-b98f-0355f190914c"},
 {"SurveyId":"2","SurveyUUIID":"284ba-4d51-b98f-0355f190914c"},
 {"SurveyId":"3","SurveyUUIID":"2c74d40d-84ba-0355f190914c"}]
        ''';
    var response = await http.Response(jsonString, 200);
    if (response.statusCode == 200) {
      List<Surveyuuidget> surveyuuidgetList =
          surveyuuidgetFromJson(response.body);

      for (int i = 0; i < surveyuuidgetList.length; i++) {
        if (surveyuuidgetList[i].surveyId == apisurveyid) {
          var surveyuuid = surveyuuidgetList[i].surveyUuiid;
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => DescPage(surveyuuidgetList[i])));
        }
      }

工作演示

在此处输入图像描述

完整代码

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

List<Surveyuuidget> surveyuuidgetFromJson(String str) =>
    List<Surveyuuidget>.from(
        json.decode(str).map((x) => Surveyuuidget.fromJson(x)));

String surveyuuidgetToJson(List<Surveyuuidget> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Surveyuuidget {
  Surveyuuidget({
    this.surveyId,
    this.surveyUuiid,
  });

  String surveyId;
  String surveyUuiid;

  factory Surveyuuidget.fromJson(Map<String, dynamic> json) => Surveyuuidget(
        surveyId: json["SurveyId"],
        surveyUuiid: json["SurveyUUIID"],
      );

  Map<String, dynamic> toJson() => {
        "SurveyId": surveyId,
        "SurveyUUIID": surveyUuiid,
      };
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  Future GetSurvey() async {
    String apisurveyid = "2";

    String jsonString = '''
        [{"SurveyId":"1","SurveyUUIID":"284ba-4d51-b98f-0355f190914c"},
 {"SurveyId":"2","SurveyUUIID":"284ba-4d51-b98f-0355f190914c"},
 {"SurveyId":"3","SurveyUUIID":"2c74d40d-84ba-0355f190914c"}]
        ''';
    var response = await http.Response(jsonString, 200);
    if (response.statusCode == 200) {
      List<Surveyuuidget> surveyuuidgetList =
          surveyuuidgetFromJson(response.body);

      for (int i = 0; i < surveyuuidgetList.length; i++) {
        if (surveyuuidgetList[i].surveyId == apisurveyid) {
          var surveyuuid = surveyuuidgetList[i].surveyUuiid;
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => DescPage(surveyuuidgetList[i])));
        }
      }
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Please enter a valid survey ID');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('Click'),
              onPressed: () {
                GetSurvey();
              },
            ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class DescPage extends StatelessWidget {
  final Surveyuuidget surveyuuidget;
  DescPage(this.surveyuuidget);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("test"),
        ),
        body: Text("${surveyuuidget.surveyId} ${surveyuuidget.surveyUuiid}"));
  }
}

推荐阅读