gpt4 book ai didi

android - Flutter JSON 列表未正确返回

转载 作者:IT王子 更新时间:2023-10-29 07:10:13 25 4
gpt4 key购买 nike

我一直在关注 this youtube video帮助我将在线 JSON 文件中的数据返回到 ListView 中。我稍微更改了代码,包括更改 JSON 文件的 URL,因此,代码现在请求不同的数据。

有些东西告诉我这是因为我想使用的 JSON 类型与我使用的代码不兼容,但我不知道为什么并且可能是错误的。我使用所提供视频的作者使用的原始“StarWarsData”、“StarWarsState” 只是为了尽量减少代码中的差异。

谢谢, jack

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

最佳答案

问题就在这里,

Text(data[index]["id"],

其中 “id” 字段是一个整数,您直接使用它代替字符串。

改成,

Text('${data[index]["id"]}',

关于android - Flutter JSON 列表未正确返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50656812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com