Reputation: 69
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.
Upvotes: 0
Views: 2084
Reputation: 69
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'),
);
},);
}
}
Upvotes: 0
Reputation: 11
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.
Upvotes: 1