Reputation: 226
i am designing a splash screen for my application ...i want to show my splash screen for 3 seconds for which i am having a condition in a Future.delayed function in which i am checking whether user is logged in or not if he is logged in then i want to Navigate to the MainPage otherwise i want to navigate to the LoginPage. But my UI is stuck in splash screen and my Future.delayed function is not compiling.
class Splash_Screen extends StatefulWidget {
@override
_Splash_ScreenState createState() => _Splash_ScreenState();
@override
void initState() {
Future.delayed(Duration(seconds: 3), () {
return Obx(() {
return Get
.find<FirebaseController>()
.user != null ? MainPage() : LoginPage();
});
});
}
}
class _Splash_ScreenState extends State<Splash_Screen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size(0, 0),
child: AppBar(
backgroundColor: AppColors.colorPrimary,
elevation: 0,
),
),
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
AppColors.colorAccent,
AppColors.colorPrimary,
],
begin: const FractionalOffset(0.0, 1.0),
end: const FractionalOffset(1.0, 0.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp),
),
child: Center(
child: SizedBox(
width: 120,
height: 120,
child: Image.asset(
'assets/images/s_book_splash_logo.png',
fit: BoxFit.contain,
),
),
),
),
);
}
}
For your kind information the initState() function was available only in statefull widget that's why i am using this stateful widget and i don't know it is right approach to call an Obx() method in a stateful widget.
Upvotes: 3
Views: 959
Reputation: 1172
You can try this replace your code with this
splash_screen.dart
class SplashScreen extends StatelessWidget {
const SplashScreen({Key? key}) : super(key: key);
SplashController con = Get.put(SplashController());
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size(0, 0),
child: AppBar(
backgroundColor: AppColors.colorPrimary,
elevation: 0,
),
),
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
AppColors.colorAccent,
AppColors.colorPrimary,
],
begin: const FractionalOffset(0.0, 1.0),
end: const FractionalOffset(1.0, 0.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp),
),
child: Center(
child: SizedBox(
width: 120,
height: 120,
child: Image.asset(
'assets/images/s_book_splash_logo.png',
fit: BoxFit.contain,
),
),
),
),
);
}
}
splash_controller.dart
-> Here i checked token available then navigate to MainPage() otherwise LoginPage() -> You need to check your condition it will work
class SplashController extends GetxController {
void _checkIfIsLogged() async {
Future.delayed(Duration(seconds: 3)).then((val) {
LocalStorage.token.toString() != "null" && LocalStorage.token != ""
? MainPage()
: LoginPage;
});
}
@override
void onInit() {
// TODO: implement onInit
_checkIfIsLogged();
super.onInit();
}
}
Upvotes: 2