Last active
June 25, 2021 02:04
-
-
Save hectorAguero/74fc6f34f6ad025ae0676d5ecaccffa0 to your computer and use it in GitHub Desktop.
Simple Flutter token cache Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatefulWidget { | |
@override | |
State<MyApp> createState() => _MyAppState(); | |
} | |
class _MyAppState extends State<MyApp> { | |
late Future<bool> _myFuture; | |
@override | |
void initState() { | |
super.initState(); | |
_myFuture = _validateToken(); | |
} | |
Future<bool> _validateToken() async { | |
// SharedPreferences prefs = await SharedPreferences.getInstance(); | |
// final token = prefs.getString('userToken'); | |
final String? token = | |
await Future.delayed(const Duration(seconds: 2), () => 'userToken'); | |
if (token != null) { | |
return true; | |
} | |
return false; | |
} | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: FutureBuilder<bool>( | |
future: _myFuture, | |
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) { | |
if (snapshot.hasData) { | |
if (snapshot.data!) { | |
return const HomePage(); | |
} else { | |
return const LoginPage(); | |
} | |
} | |
return const LoadingPage(); | |
}, | |
), | |
); | |
} | |
} | |
class LoadingPage extends StatelessWidget { | |
const LoadingPage({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return const Scaffold(body: Center(child: CircularProgressIndicator())); | |
} | |
} | |
class LoginPage extends StatelessWidget { | |
const LoginPage({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return const Scaffold(body: Center(child: Text('Login Page'))); | |
} | |
} | |
class HomePage extends StatelessWidget { | |
const HomePage({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return const Scaffold(body: Center(child: Text('Home Page'))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment