There are no errors shown in my code. I don't understand why the list of names of crypto assets under ListView.builder aren't showing on my app screen?
All I see in my 'Hello World' page is an empty list.
My code is modified from this tutorial: https://github.com/toxicOxygen/fetching_data_from_api/tree/master/lib
import 'package:flutter/material.dart';
import '../models/asset.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../widgets/searchPage.dart';
class AddAssetScreen extends StatefulWidget {
@override
_AddAssetScreenState createState() => _AddAssetScreenState();
}
class _AddAssetScreenState extends State<AddAssetScreen> {
List<Asset> _assets = [];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Hello World'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (ctx) => SearchPage(
assets: _assets,
)));
},
)
],
),
body: FutureBuilder(
future: _getData(),
builder: (ctx, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return CircularProgressIndicator();
return ListView.builder(
itemBuilder: (ctx, i) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
title: Text(_assets[i].name!),
),
Divider(
height: 0,
)
],
);
},
itemCount: _assets.length,
);
},
),
);
}
Future<void> _getData() async {
var url =
'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false';
http.get(Uri.parse(url)).then((data) {
return json.decode(data.body);
}).then((data) {
for (var json in data) {
_assets.add(Asset.fromJson(json));
}
}).catchError((e) {
print(e);
});
}
}
The asset model code is as follows:
class Asset {
String? id;
String? name;
String? image;
double? currentPrice;
double? priceChange24h;
double? priceChangePercentage24h;
Asset({
required this.id,
required this.name,
required this.image,
required this.currentPrice,
required this.priceChange24h,
required this.priceChangePercentage24h,
});
Asset.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
image = json['image'];
currentPrice = json['current_price'];
priceChange24h = json['price_change_24h'];
priceChangePercentage24h = json['price_change_percentage_24h'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['image'] = this.image;
data['current_price'] = this.currentPrice;
data['price_change_24h'] = this.priceChange24h;
data['price_change_percentage_24h'] = this.priceChangePercentage24h;
return data;
}
}
CodePudding user response:
_getData needs to return something other than void like a List.