Flutter ListView 的网络请求使用示例
必备操作
引入网络请求库:
在项目的根目录下找到 pubspec.yaml 文件,
dependencies 里面加入
http: ^0.12.0
就可以在代码中引入网络请求库了:
import 'package:http/http.dart';
完整代码:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
class DoubanTheatersWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
title: "豆瓣电影",
theme: ThemeData(
primaryColor: Colors.redAccent,
),
home: MyHomeApp(title: 'Movies',),
);
}
}
class MyHomeApp extends StatefulWidget {
final String title;
MyHomeApp({Key key, this.title}) : super(key: key);
@override
State<StatefulWidget> createState() {
return _MyHomeAppState();
}
}
class _MyHomeAppState extends State<MyHomeApp> {
List subjects = [];
String title = '';
@override
void initState() {
super.initState();
loadData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: getBody(),
),
);
}
loadData() async {
String loadURL = "https://api.douban.com/v2/movie/in_theaters";
http.Response response = await http.get(loadURL);
var result = json.decode(response.body);
setState(() {
title = result['title'];
print('title: $title');
subjects = result['subjects'];
});
}
getItem(var subject) {
var avatars = List.generate(subject['casts'].length, (int index) => Container(
margin: EdgeInsets.only(left: index.toDouble() == 0.0 ? 0.0 : 16.0),
child: CircleAvatar(
backgroundColor: Colors.white10,
backgroundImage: NetworkImage(
subject['casts'][index]['avatars']['small']
),
),
));
var row = Container(
margin: EdgeInsets.all(4.0),
child: Row(
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(4.0),
child: Image.network(
subject['images']['large'],
width: 100.0, height: 150.0,
fit: BoxFit.fill,
),
),
Expanded(child: Container(
margin: EdgeInsets.only(left: 8.0),
height: 150.0,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
subject['title'],
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
maxLines: 1,
),
Text(
"豆瓣评分: ${subject['rating']['average']}",
style: TextStyle(
fontSize: 16.0
),
),
Text(
"类型: ${subject['genres'].join('、')}"
),
Text(
"导演: ${subject['directors'][0]['name']}"
),
Container(
margin: EdgeInsets.only(top: 8.0),
child: Row(
children: <Widget>[
Text('主演:'),
Row(
children: avatars,
),
],
),
),
],
),
)),
],
),
);
return row;
}
getBody() {
if (subjects.length != 0) {
return ListView.builder(
itemCount: subjects.length,
itemBuilder: (BuildContext context, int position) {
return getItem(subjects[position]);
});
} else {
return CupertinoActivityIndicator();
}
}
}
main.dart:
import 'package:flutter/material.dart';
import 'DoubanTheaters.dart';
void main() {
return runApp(DoubanTheatersWidget());
}