flutter - 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,但它显示了上面给定的错误。有人可以帮我吗?
解决方案
您可以在下面复制粘贴运行完整代码
因为返回类型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}"));
}
}
推荐阅读
- javascript - 将 JSON 数组输出到行中的 Google Apps 脚本
- git - 如何签出远程分支并与其他团队成员协作处理它?
- sql-server - 在将新表添加回历史表之前,在历史表中的新表上设置值
- html - Cognos 11 本地分析 - 运行报告时保存生成的 html 代码
- java - 套接字实例不会连接到本地服务器
- python - 如何直接在 Ubuntu 终端中运行 Python 模块?
- angular - 解析 http://localhost:8080/home 期间的 Http 失败
- python - Anaconda 不会更新:“无默认基础环境”错误
- php - 如何在 VSCode Snippet 的制表位内使用 Emmet 快捷方式?
- java - 向用户显示 pdf 文件夹及其内容