Flutter. Как отобразить Future> в интерфейсе
Есть метод с запросом:
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'],
);
}
}
Ответы (1 шт):
Автор решения: Anastasia Ya
→ Ссылка
Дженерик FutureBuilder указан неправильно. Он должен быть таким же, как возвращаем значение future. Тогда можно будет обратиться ко второму элементу snapshot.data.products[2].title