最近應邀票圈小伙伴躺坑Flutter
,項目初步雛形完結。以原來的工具鏈版本為基礎做了Flutter
版本,不過后面還是需要優化下項目接入Redux
,以及擴展一些Native方法。
這里記錄一下在開發過程中碰到的一些小問題。
首先是搭建Tab的時候,切換tab子頁面,上一個頁面會被釋放,導致切換回來時會重新觸發initState
等生命周期(網絡請求是放在這個里面的)
問了一下前同事:“需要使用 bool get wantKeepAlive => true;
”,於是網上搜了一下這個玩意兒,以及其他解決方案。
首先說說使用wantKeepAlive
的方案:這是Flutter
官方提供並推薦的,源自於AutomaticKeepAliveClientMixin
用於自定義保存狀態。
先看看實現Tab的代碼(有幾種實現Tab的方式,后續博客更新):
class _TabPageState extends State<TabPage> with SingleTickerProviderStateMixin {
//屬性
int _tabindex;
PageController _pageController;
@override
void initState() {
print("tabController");
super.initState();
_pageController = new PageController();
_tabindex = 0;
}
//當整個頁面dispose時,記得把控制器也dispose掉,釋放內存
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
print("tabIndex $_tabindex");
return Scaffold(
body: new PageView(
children: [new ListPage(), new AppletPage()],
controller: _pageController,
physics: new NeverScrollableScrollPhysics(),
onPageChanged: onPageChanged,
),
bottomNavigationBar: new BottomNavigationBar(
onTap: navigationTapped,
currentIndex: _tabindex,
items: <BottomNavigationBarItem>[
new BottomNavigationBarItem(
icon: new Icon(Icons.brightness_5), title: new Text("工具鏈")),
new BottomNavigationBarItem(
icon: new Icon(Icons.map), title: new Text("小程序"))
],
),
);
}
void navigationTapped(int page) {
//Animating Page
_pageController.jumpToPage(page);
}
void onPageChanged(int page) {
setState(() {
this._tabindex = page;
});
}
}
根據官網的要求:
PageView
的children需要繼承自StatefulWidget
PageView
的children的State
需要繼承自AutomaticKeepAliveClientMixin
具體實現如下:
import 'package:flutter/material.dart';
class AppletPage extends StatefulWidget {
//構造函數
AppletPage({Key key}) : super(key: key);
@override
_AppletPageState createState() => _AppletPageState();
}
class _AppletPageState extends State<AppletPage>
with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true; // 返回true
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text("小程序"),
backgroundColor: Colors.blue, //設置appbar背景顏色
centerTitle: true, //設置標題是否局中
),
body: new Center(
child: new Text('敬請期待'),
),
),
);
}
}