有一个带有请求的方法:
Future<List<Product>> fetchAlbum() async {
final response = await http
.get(Uri.parse('https://fakestoreapi.com/products'));
if (response.statusCode == 200) {
Iterable l = json.decode(response.body);
List<Product> products= List<Product>.from(l.map((i) => Product.fromJson(i)));
return products;
} else {
throw Exception('Failed to load album');
}
}
它返回来自假商店的产品列表:https ://fakestoreapi.com/
例如,如何显示title
第二个元素?布局:
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Product>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);
}
}
一个东西:
class Product {
final int id;
final String title, description, category;
final double price;
final String image;
final Map rating;
Product({
@required this.id,
@required this.title,
@required this.description,
@required this.category,
@required this.price,
@required this.image,
@required this.rating
});
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
id: json['id'],
title: json['title'],
description: json['description'],
category: json['category'],
price: json['price'],
image: json['image'],
rating: json['rating'],
);
}
}
通用 FutureBuilder 不正确。它必须与返回未来的值相同。然后就可以引用第二个元素snapshot.data.products[2].title