我正在处理 Http 获取请求。我正在使用 jsonplaceholder.typicode.com。我从颤振文档中获取了参考,但目前,它只显示第一项。我想以卡片的形式显示所有 20 个项目。谁能帮助我实现这一目标?
这是我的代码:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
final response =
await http.get(Uri.https('jsonplaceholder.typicode.com', 'albums/1'));
if (response.statusCode == 200) {
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load album');
}
}
class Album {
final int userId;
final int id;
final String title;
Album({@required this.userId, @required this.id, @required this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}
我在这里使用这个:
class ShopScreen extends StatefulWidget {
static String id = 'shop_screen';
@override
_ShopScreenState createState() => _ShopScreenState();
}
class _ShopScreenState extends State<ShopScreen> {
Future<Album> futureAlbum;
@override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Shops'),
backgroundColor: Colors.deepOrangeAccent[700],
),
drawer: NavList(),
body: ListView(
children: <Widget>[
ShopCard(placeholderImage: 'https://picsum.photos/250?image=3'),
ShopCard(placeholderImage: 'https://picsum.photos/250?image=100'),
ShopCard(placeholderImage: 'https://picsum.photos/250?image=234'),
ShopCard(placeholderImage: 'https://picsum.photos/250?image=200'),
Container(
padding: EdgeInsets.all(5.0),
width: MediaQuery.of(context).size.width,
height: 130,
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Text('TITLE: ${snapshot.data.title}'),
),
Expanded(
child: Text('USER_ID: ${snapshot.data.userId}'),
),
Expanded(
child: Text('ID: ${snapshot.data.id}'),
),
],
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
),
),
elevation: 5.0,
),
)
],
),
);
}
这就是我现在得到的。(见最后一张卡片。只显示第一个数据。)
请帮帮我。