我一直关注this youtube video来帮助我将在线JSON文件中的数据返回到列表视图中。我稍微修改了代码,包括更改了JSON文件的URL,因此代码现在请求不同的数据。
有些东西告诉我,因为我想要使用的JSON类型与我使用过的代码不兼容,但我不知道为什么会出错。我使用原始的' StarWarsData' StarWarsState' ,所提供视频的作者用于最小化我的代码中的差异。
谢谢,杰克
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() {
runApp(MaterialApp(
home: StarWarsData(),
));
}
class StarWarsData extends StatefulWidget {
@override
StarWarsState createState() => StarWarsState();
}
class StarWarsState extends State<StarWarsData> {
final String url = "https://api.coinmarketcap.com/v2/listings/";
List data;
Future<String> getSWData() async {
var res = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
setState(() {
var resBody = json.decode(res.body);
data = resBody["data"];
});
return "Success!";
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Star Wars Starships"),
backgroundColor: Colors.deepPurpleAccent,
),
body: ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
return new Container(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Card(
child: Container(
padding: EdgeInsets.all(15.0),
child: Row(
children: <Widget>[
Text("Id: "),
Text(data[index]["id"],
style: TextStyle(
fontSize: 18.0, color: Colors.black87)),
],
)),
),
Card(
child: Container(
padding: EdgeInsets.all(15.0),
child: Row(
children: <Widget>[
Text("Name: "),
Text(data[index]["name"],
style: TextStyle(
fontSize: 18.0, color: Colors.red)),
],
)),
),
Card(
child: Container(
padding: EdgeInsets.all(15.0),
child: Row(
children: <Widget>[
Text("Symbol: "),
Text(data[index]["symbol"],
style: TextStyle(
fontSize: 18.0, color: Colors.black87)),
],
)),
),
],
),
),
);
},
),
);
}
@override
void initState() {
super.initState();
this.getSWData();
}
}
修改
这个问题现在已经修复,但万一有人感兴趣,这是我以前遇到的错误:
I/flutter (31850): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY
╞═══════════════════════════════════════════════════════════I/flutter
(31850): type 'int' is not a subtype of type 'String' where I/flutter
(31850): int is from dart:core I/flutter
(31850): String is from dart:core
答案 0 :(得分:3)
问题就在这里,
Text(data[index]["id"],
其中"id"
字段是一个整数,您直接使用它来代替字符串。
将其更改为,
Text('${data[index]["id"]}',