问题描述
我正在开发一个带有波动性的应用程序.
I'm developing an app with flutter.
一切正常,但我需要一些东西.
All goes fine, but I need something.
我需要检查应用程序进入前台时用户的令牌是否已过期.
I need check if user's token has expired when app comes to foreground.
我通过以下方式获取应用状态
I get the app state with
didChangeAppLifecycleState(AppLifecycleState state)
.
我的代码示例是这样的(我无法编写真实的代码,因为它在我工作的计算机中,现在我在家里):
An example of my code is this (I can't write the real code because is in my job's computer, and now I'm in home):
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
@override
void initState() {
WidgetsBinding.instance.addObserver(this);
super.initState();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
void didChangeAppLifecycleState(AppLifecycleState state) {
var isLogged = boolFunctionToCheckLogin();
if (state == AppLifecycleState.resume && isLogged) {
// THIS IS THE PLACE WHEN I TRY TO CODE THE MAGIC
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Tutorial Lifecycle'),
),
body: Center(),
);
}
但是,在didChangeAppLifecycleState函数内部:
But, inside of didChangeAppLifecycleState function:
- 我尝试使用Navigator.push进行showDialog登录
- 我尝试直接制作Navigator.push
- 我尝试重新启动应用程序
所有这些都有相同的问题:context为null或相似.
All of these have the same problem: context is null or similar.
如果我直接使用button或其他按钮执行任何这些选项,则可以使用.
但是当应用程序出现在前台时,系统会告诉我上下文为null或Material
If I do any of these options directly with button or whatever, works.
But when app comes to foreground, the system says me that context is null or Material
任何人都可以帮助您知道该怎么做?
Anybody can help to know how to do it??
谢谢大家!
推荐答案
我已经解决了.
在带有魔术"的条件标记中,我在setState内调用了"showDialog":
Into the conditional mark with "magic", I've call "showDialog" inside of setState:
void didChangeAppLifecycleState(AppLifecycleState state) {
var isLogged = boolFunctionToCheckLogin();
if (state == AppLifecycleState.resume && isLogged) {
setState(() {
showDialog(
context: context,
builder: (BuildContext context) {
... blablabla ...
}
});
}
}
这篇关于扑重启应用程序或重定向到第一个小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!