使用Flutter開發一款App是一件非常愉快的事情,其出色的效能、跨多端以及數量眾多的原生元件都是我們選擇Flutter的理由!今天我們就來使用Flutter開發一款電影類的App,先看下App的截圖。
從main.dart開始
在Flutter裡main.dart是應用開始的地方:
import 'package:flutter/material.dart';
import 'package:movie/utils/router.dart' as router;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: '電影',
theme: ThemeData(
primarySwatch: Colors.blue,
),
onGenerateRoute: router.generateRoute,
initialRoute: '/',
);
}
}
複製程式碼
一般的,在Flutter中管理路由有兩種方式,一種是直接使用Navigator.of(context).push()
,這種方式比較適合非常簡單的應用,隨著應用的不斷髮展,邏輯越來越多,推薦使用具名路由來管理應用,本文也是使用的這種方式。直接將路由掛在MaterialApp
的onGenerateRoute
欄位上即可,具體的路由定義放在了單獨的檔案中進行管理utils/router.dart
:
import 'package:flutter/material.dart';
import 'package:movie/screens/home.dart';
import 'package:movie/screens/detail.dart';
import 'package:movie/screens/videoPlayer.dart';
Route<dynamic> generateRoute(RouteSettings settings) {
switch (settings.name) {
case '/':
return MaterialPageRoute(builder: (context) => Home());
case 'detail':
var arguments = settings.arguments;
return MaterialPageRoute(
builder: (context) => MovieDetail(id: arguments));
case 'video':
var arguments = settings.arguments;
return MaterialPageRoute(
builder: (context) => VideoPage(url: arguments));
default:
return MaterialPageRoute(builder: (context) => Home());
}
}
複製程式碼
真是像極了前端的路由定義,先將元件import進來,然後在各自的路由中return即可。
首頁
在首頁中使用TabBar來展示"正在熱映"和"TOP250":
import 'package:flutter/material.dart';
import 'package:movie/screens/hot.dart';
class Home extends StatefulWidget {
Home({Key key}) : super(key: key);
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> with SingleTickerProviderStateMixin {
TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(vsync: this, initialIndex: 0, length: 2);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: TabBar(
controller: _tabController,
tabs: <Widget>[
Tab(text: '正在熱映'),
Tab(text: 'TOP250'),
],
),
),
body: TabBarView(
controller: _tabController,
children: <Widget>[
Hot(),
Hot(history: true),
],
),
);
}
}
複製程式碼
兩個頁面的佈局是一樣的,只有資料是不同的,所以我們複用這個頁面Hot
,傳入history
引數來代表是否為Top250頁面
複用的Hot元件
- 在這個元件中,通過history欄位來區分成兩個頁面。
- 在頁面
initState
的生命週期中,請求資料,再進行相應的展示。 - 下拉重新整理的功能是使用的RefreshIndicator元件,在其
onRefresh
中進行下拉時的邏輯處理。 - Flutter沒有直接提供上拉載入的元件,但是也是很容易實現,通過
ListView
的controller來做判斷即可:當前滾動的位置是否到達最大滾動位置_scrollController.position.pixels == _scrollController.position.maxScrollExtent
- 為了獲得良好的使用者體驗,Tab來回切換的時候,我們不希望頁面重新渲染,Flutter提供了混入類AutomaticKeepAliveClientMixin,過載
wantKeepAlive
即可,下面是完整的程式碼:
import 'package:flutter/material.dart';
import 'package:movie/utils/api.dart' as api;
import 'package:movie/widgets/movieItem.dart';
class Hot extends StatefulWidget {
final bool history;
Hot({Key key, this.history = false}) : super(key: key);
_HotState createState() => _HotState();
}
class _HotState extends State<Hot> with AutomaticKeepAliveClientMixin {
List _movieList = [];
int start = 0;
int total = 0;
ScrollController _scrollController = ScrollController();
@override
void initState() {
super.initState();
_scrollController.addListener(() {
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
getMore();
}
});
this.query(init: true);
}
query({bool init = false}) async {
Map res = await api.getMovieList(
history: widget.history, start: init ? 0 : this.start);
var start = res['start'];
var total = res['total'];
var subjects = res['subjects'];
setState(() {
if (init) {
this._movieList = subjects;
} else {
this._movieList.addAll(subjects);
}
this.start = start + 10;
this.total = total;
});
}
Future<Null> _onRefresh() async {
await this.query(init: true);
}
getMore() {
if (start < total) {
query();
}
}
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
return RefreshIndicator(
onRefresh: _onRefresh,
child: ListView.builder(
controller: _scrollController,
itemCount: this._movieList.length,
itemBuilder: (BuildContext context, int index) =>
MovieItem(data: this._movieList[index]),
),
);
}
}
複製程式碼
電影的詳情頁面
點選單條電影時使用Navigator.pushNamed(context, 'detail', arguments: data['id']);
即可跳轉詳情頁,在詳情頁中通過id
再請求介面獲取詳情:
import 'package:flutter/material.dart';
import 'package:movie/widgets/detail/detailTop.dart';
import 'package:movie/widgets/detail/rateing.dart';
import 'package:movie/widgets/detail/actors.dart';
import 'package:movie/widgets/detail/photos.dart';
import 'package:movie/widgets/detail/comments.dart';
import 'package:movie/utils/api.dart' as api;
class MovieDetail extends StatefulWidget {
final id;
MovieDetail({Key key, this.id}) : super(key: key);
_MovieDetailState createState() => _MovieDetailState();
}
class _MovieDetailState extends State<MovieDetail> {
var _data = {};
@override
void initState() {
super.initState();
this.init();
}
init() async {
var res = await api.getMovieDetail(widget.id);
setState(() {
_data = res;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: _data.isEmpty
? Center(child: CircularProgressIndicator(),)
: SafeArea(
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: ListView(
scrollDirection: Axis.vertical,
children: <Widget>[
MovieDetailTop(data: _data),
Rate(count: _data['ratings_count'], rating: _data['rating']),
Container(padding: EdgeInsets.all(10),child: Text(_data['summary'])),
Actors(directors: _data['directors'], casts: _data['casts']),
Photos(photos: _data['photos'],),
Comments(comments: _data['popular_comments']),
],
),
),
),
);
}
}
複製程式碼
在詳情頁面中,我們封裝了一些元件,這樣能讓專案更加容易閱讀和維護,元件的具體實現就不詳細介紹了,都是一些常用的原生元件,這些元件分別是:
widgets/detail/detailTop.dart
頁面頂部的電影概述widgets/detail/rateing.dart
評分元件widgets/detail/actors.dart
演員表widgets/detail/photos.dart
劇照widgets/detail/comments.dart
評論元件
真實資料來自哪裡?
應用中的資料都是從豆瓣開發者api中拉取的,分別是,正在熱映in_theaters
,top250top250
和電影詳情subject/id
三個介面,請求這些介面是需要apikey
的,為了大家能方便請求資料,我將apikey
上傳到了github上,還請大家溫柔點,不要將這個apikey
幹爆了。