我正试图通过将node.js上的mysql与express连接在一起创建的api(以json格式)显示我的数据在我的flutter应用程序中显示。
我正在android studio控制台中运行此错误
[VERBOSE-2:dart_error.cc(16)] Unhandled exception:
type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type
'List<dynamic>'
api当前看起来像这样
{
"error": false,
"data": [
{
"name": "conner",
"age": 24
},
{
"name": "andrew",
"age": 20
}
],
"message": "Todos list."
}
我正在使用本教程,只是将其值“ title”替换为我的“ name” https://www.youtube.com/watch?v=-PRrdG163to
这是我正在运行的代码
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(new MaterialApp(
home: new HomePage(),
));
}
class HomePage extends StatefulWidget {
@override
HomePageState createState() => new HomePageState();
}
class HomePageState extends State<HomePage> {
Map<String,dynamic> data;
Future<String> getData() async {
var response = await http.get(
Uri.encodeFull("http://10.1.0.109:8080/names"),
headers: {
"Accept": "application/json"
}
);
this.setState(() {
data = JSON.decode(response.body);
});
print (data[1]["data"]);
return "Success!";
}
@override
void initState() {
super.initState();
this.getData();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Listviews"),
),
body: new ListView.builder(
itemCount: data == null ? 0 : data["data"].length,
itemBuilder: (BuildContext context, int index) {
return new Card(
child: new Text(data[index]["data"]),
);
},
),
);
}
}
答案 0 :(得分:1)
问题出在JSON文件的结构中,与本教程中的内容不同,因此请尝试
data["data"][1]["name"]
注意:
将数据从list
更改为var
或Map<String,dynamic>
Map<String,dynamic> data;
之后,您需要获取列表长度,因此在itemCount中将其更改为
itemCount: data == null ? 0 : data["data"].length,