【发布时间】:2019-06-09 02:27:57
【问题描述】:
我正在使用 Flutter 重建一个 iOS 应用程序,流程如下: 每次用户登陆主页时,都会从后端重新加载用户数据以检查是否有任何更改。
我在 Swift / iOS 中实现这一点的方法是使用 viewDidLoad() 函数。
我的 Flutter 代码是这样的:
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
User user = User();
@override
void dispose() {
super.dispose();
}
@override
void initState() {
super.initState();
_fetchData(context);
}
@override
Widget build(BuildContext context) {
return Container(
color: RColor.COLOR_main,
child: Column(
children: [
Container(
height: MediaQuery.of(context).size.height / 7,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.all(20),
child: Container(
child: Text("This is the homepage"),
alignment: Alignment.bottomCenter,
),
),
],
));
}
Future _fetchData(BuildContext context) async {
_fetchUserAPI(context);
}
Future _fetchUserAPI(BuildContext context) async {
try {
SharedPreferences prefs = await SharedPreferences.getInstance();
var accessToken = prefs.getString("access_token");
var url = RConstants.API_BASE_URL + "/v1/users/self";
Response response = await Dio()
.get(url, options: Options(headers: {"Authorization": accessToken}));
setState(() {
user = User.fromJson(response.data);
});
} catch (e) {
print(e.toString());
Alert(
context: context,
title: "Something Went Wrong",
desc: "Something went wrong while fetching your user data",
type: AlertType.error)
.show();
}
}
}
void initState() 但是,每次用户登陆主页时都不会触发。实现这一目标的正确方法是什么?
【问题讨论】:
-
每次打开屏幕都会执行build方法
-
@diegoveloper 但这不是唯一一次。每次状态变化时都会触发
-
@Rutger,你能找到解决方案吗?
-
@Jan 彻底改变了应用程序的架构。转移到使用 BLoC 模式。我建议调查一下