Flutter在State类里获取Page类中的变量

Flutter在State状态类里获取Page页面类中定义的变量,通过widget的get方法实现

状态类直接继承State类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import 'package:flutter/material.dart';

class AppBlogPage extends StatefulWidget {
AppBlogPage({Key key, this.title}) : super(key: key);
final String title;

@override
State<StatefulWidget> createState() => new _AppBlogPageState();
}

class _AppBlogPageState extends State<AppBlogPage> {
int _counter = 0;

void _incrementCounter() {
setState(() {
_counter++;
});
}

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title), //取得页面类的title变量
),
body: Container(),
);
}
}

状态类间接继承State类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class BaseAuthPage extends StatefulWidget {
String title;
BaseAuthPage({Key key, this.title}) : super(key: key);

State<StatefulWidget> createState() => new BaseAuthPageState();
}

class BaseAuthPageState<T extends BaseAuthPage> extends State<BaseAuthPage> {
bool checkAuth = false;

@override
void initState() {
AuthUtil.checkAuthAsync().then((auth) {
checkAuth = auth;
if (!checkAuth) {
print('AuthUtil.checkAuth: failure');
Future.delayed(Duration(milliseconds: 100)).then((_) {
Navigator.pushReplacementNamed(context, '/sign_in');
});
} else {
print('AuthUtil.checkAuth: success');
}
});
}

T get auth_widget => widget; //注意复写widget的get方法

@override
Widget build(BuildContext context) {
return null;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class GoodsPage extends BaseAuthPage {
int goodsId;
GoodsPage({Key key, this.goodsId}) : super(key: key);

@override
State<StatefulWidget> createState() => new GoodsPageState();
}

class GoodsPageState extends BaseAuthPageState<GoodsPage> {
int goodsId;

@override
void initState() {
super.initState();
goodsId = auth_widget.goodsId; //取得页面类的goodsId变量
print('Goods Id: $goodsId');
}

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title), //取得页面父类的title变量
),
body: Container(),
);
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :