如何从 JSON 数据中获取列表以显示在小部件中?
Posted
技术标签:
【中文标题】如何从 JSON 数据中获取列表以显示在小部件中?【英文标题】:How to get list from JSON data to display in widget? 【发布时间】:2021-12-31 18:29:30 【问题描述】:我一直在制作一个简单的应用程序,它显示加密货币及其价格、数据、市值等。我正在使用 CoinGeckGo API。
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
class Coin
String? coinName;
String? coinPrice;
String? coinImgUrl;
String? coinVol;
Coin(
@required this.coinName,
@required this.coinPrice,
@required coinImgUrl,
@required coinVol);
class Coins
Future<List<Coin>> fetchCoinsData() async
var uri = Uri.parse(
"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false");
final response = await http.get(uri);
final json = await jsonDecode(response.body);
List<Coin> coins = [];
for (int i = 0; i < json.length; i++)
Coin coin = Coin(
coinImgUrl: json[i]["image"].toString(),
coinName: json[i]["symbol"].toString(),
coinPrice: json[i]["current_price"].toString(),
coinVol: json[i]["total_volume"].toString(),
);
coins.add(coin);
return coins;
这是我从 json api 获取数据并将它们添加到列表中的函数,以便我从该列表中获取值以显示在小部件中。
但是当我在初始化状态下调用这个函数并将获取的返回值分配给一个列表时,我得到输出“'Coin'的实例,但它应该像coinName:'btc',coinPrice: '48000', coinVol: 478965455
像那样
下面是我在 initstate 中调用函数的代码。
class _MyHomePageState extends State<MyHomePage>
List<Coin> my_list = [];
bool? _isLoading;
@override
void initState()
// TODO: implement initState
super.initState();
_isLoading = true;
Coins().fetchCoinsData().then((List<Coin> value)
print(value);
my_list = value;
_isLoading = false;
);
【问题讨论】:
【参考方案1】:试试下面的代码希望它对你有帮助。如果您从 API 获取数据,请参考我的回答 here 或 here 或 here 希望对您有所帮助
您的 API 调用函数:
Future<List<dynamic>> getCoinsData() async
String url =
'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false';
var response = await http.get(Uri.parse(url), headers:
'Content-Type': 'application/json',
'Accept': 'application/json',
);
return json.decode(response.body);
您的小部件:
Column(
children: <Widget>[
Expanded(
child: FutureBuilder<List<dynamic>>(
future: getCoinsData(),
builder: (context, snapshot)
if (snapshot.hasData)
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data!.length,
itemBuilder: (context, index)
var name = snapshot.data![index]['name'];
var symbol = snapshot.data![index]['symbol'];
var image = snapshot.data![index]['image'];
var currentPrice =
snapshot.data![index]['current_price'];
var totalVolume =
snapshot.data![index]['total_volume'];
var id = snapshot.data![index]['id'];
return Card(
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.green.shade300),
borderRadius: BorderRadius.circular(15.0),
),
child: Column(
children: [
ListTile(
leading: CircleAvatar(
backgroundColor: Colors.transparent,
child: Image.network(image),
),
title: Text(name),
subtitle: Text(
"Symbol - " +
symbol +
"\nTotal Volume -" +
totalVolume.toString() +
"\nCurrent Price -" +
currentPrice.toString(),
),
trailing: Text(id),
),
],
),
);
,
),
);
return CircularProgressIndicator();
,
),
),
],
),
您的结果屏幕:
【讨论】:
以上是关于如何从 JSON 数据中获取列表以显示在小部件中?的主要内容,如果未能解决你的问题,请参考以下文章