'Flutter Secure Storage not initializing as itended on app start up
I am working on an application with dynamic splash screen images. This is how I have implemented it.
class _SplashScreenState extends State<SplashScreen> {
loginState() async{
if(await FlutterSecureStorage().read(key: "Login")!=null){
isLoggedIn = true;
image = await StorageAccess().readFile();
}
}
bool isLoggedIn = false;
var image;
@override
void initState() {
loginState();
super.initState();
Timer(Duration(seconds: 4),
()=>Navigator.pushReplacement(context,
MaterialPageRoute(builder:
(context) =>
FirstPage()
)
)
);
}
@override
Widget build(BuildContext context) {
return isLoggedIn?Container(
color: Colors.white,
child:Image.memory(image),
):Container(
color: Colors.white,
child: Image.asset('images/logo.png'),
);
}
}
This works properly when I perform a hot restart but when I close and start the application variable isLoggedIn is taking way more time to get initialised and my dynamic image in the splash screen is not showing.
Anyone has any idea why it takes so much time to initialize on app boot up but not on hot restart and how do I fix this?
Thanks In Advance.
Solution 1:[1]
I used FutureBuilder to sort out this issue. Updated code is like this:
class _SplashScreenState extends State<SplashScreen> {
loginState() async{
if(await FlutterSecureStorage().read(key: "Login")!=null){
isLoggedIn = true;
image = await StorageAccess().readFile();
}
}
bool isLoggedIn = false;
var image;
@override
void initState() {
super.initState();
Timer(Duration(seconds: 4),
()=>Navigator.pushReplacement(context,
MaterialPageRoute(builder:
(context) =>
FirstPage()
)
)
);
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: loginState(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
return isLoggedIn?Container(
color: Colors.white,
child:Image.memory(image),
):Container(
color: Colors.white,
child: Image.asset('images/logo.png'),
);
},);
}
}
Solution 2:[2]
you can try run initState with async.
void initState() async {
loginState();
super.initState();
Timer(Duration(seconds: 4),
()=>Navigator.pushReplacement(context,
MaterialPageRoute(builder:
(context) =>
FirstPage()
)
)
);
}
similar problem I'm struggling too. For my case, I'm using getx, so that this may solve the problem you get.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rahul Kumar Jha |
Solution 2 | laolee010126 |