這個小例子使用的是豆瓣 API 中 正在上映的電影
的開放接口,要實現的主要效果以下:git
Item 的結構是一個 Card
包含着一個 Row
而後這個 Row
裏面左邊是一個 Image
,右邊是一個 Column
github
要實現上面四個功能,咱們首先須要在 .dart
文件中引入以下代碼json
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
複製代碼
網絡請求api
loadData() async {
String loadRUL = "https://api.douban.com/v2/movie/in_theaters";
http.Response response = await http.get(loadRUL);
var result = json.decode(response.body);
setState(() {
title = result['title'];
print('title: $title');
subjects = result['subjects'];
});
}
複製代碼
ListView && 加載菊花網絡
getBody() {
if (subjects.length != 0) {
return ListView.builder(
itemCount: subjects.length,
itemBuilder: (BuildContext context, int position) {
return getItem(subjects[position]);
});
} else {
// 加載菊花
return CupertinoActivityIndicator();
}
}
複製代碼
Item編寫數據結構
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 Card(
child: row,
);
}
複製代碼
主要代碼就是上述這些... 效果圖,源碼地址async