0%

flutter启动页、导航页、广告页

在 APP 中,启动页、导航页、广告页必不可少,本文记录在 Flutter 中的实现方式。

我们需要把启动页作为整个项目的开始页面,并在路由中添加主页面的路由:

1
2
3
4
5
6
7
8
MaterialApp(
...
routes: {
'/MainPage': (ctx) => MainPage(),
},
home: SplashPage(),
...

SplashPage 中我们需要创建 StatefulWidget 来保存状态。

定义 status 来标注页面的状态。

0 默认启动页
1 引导页
2 广告页

render 页面的时候通过改变 status 来确定展示什么页面。

通过重写 initState 来初始化数据,我们在里面进行模拟通过网络请求拉取数据来判断展示页面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// SplashPage.dart
int status = 0;

@override
void initState() {
super.initState();
print('init splash');
// mock network
Future.delayed(Duration(seconds: 2)).then((_) {
return Random().nextInt(2) + 1;
}).then((_sta) {
if (_sta == 1)
_initGuide();
else
_initAds();
setState(() {
status = _sta;
});
});
}

通过 Future 来模拟网络请求的延时, 获取数据来判断显示那种页面,这里用随机返回 1 或 2 来模拟数据。

页面通过 Stack Widget 进行堆叠,使用 Offstage Widget 来判断是否显示该 Widget。

页面具体实现请看 这里