How to check auth token at entry point of flutter app

4,488

Solution 1

You can copy paste run full code below
You can get jwt token in main() and check jwt content is null or not in initialRoute

code snippet

String jwt;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  SharedPreferences prefs = await SharedPreferences.getInstance();
  jwt = await prefs.getString("jwt");
  print('jwt ${jwt}');
  runApp(MyApp());
}
...
return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: jwt == null ? "login" : "/",
      routes: {
        '/': (context) => MyHomePage(
              title: "demo",
            ),
        "login": (context) => LoginScreen(),
      },

working demo

enter image description here

full code

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart';

String jwt;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  SharedPreferences prefs = await SharedPreferences.getInstance();
  jwt = await prefs.getString("jwt");  
  print('jwt ${jwt}');
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: jwt == null ? "login" : "/",
      routes: {
        '/': (context) => MyHomePage(
              title: "demo",
            ),
        "login": (context) => LoginScreen(),
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Login"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'This is Login screen',
            ),
          ],
        ),
      ),
    );
  }
}

Solution 2

If you have a splash screen, you should create a function like below and invoke in initState.

countDownTime() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return Timer(
      Duration(seconds: 3),
      () async {
        String uid = await prefs.getString('jwt');
        if (uid != null) {
          Navigator.push(
             context,
             MaterialPageRoute(builder: (context) => HomeScreen()),
          );
        } else {
          Navigator.push(
             context,
             MaterialPageRoute(builder: (context) => LoginScreen()),
          );
        }
      },
    );
  }
   ...
   ...
  @override
  void initState() {
    super.initState();
    countDownTime();
  }

This works for me.:)

Share:
4,488
Sandun Sameera
Author by

Sandun Sameera

I'm an undergraduate of UCSC and a guy who passionate about android

Updated on December 20, 2022

Comments

  • Sandun Sameera
    Sandun Sameera over 1 year

    I need to know how to check the token at entry point of app. I have already saved that in shared preference by `

    _saveToken() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        String token = await response.data['token'];
        await prefs.setString('jwt', token);
      }
    

    ` and I need to bypass my login screen if this jwt is not null. How can I do this?

    • Viren V Varasadiya
      Viren V Varasadiya almost 4 years
      can you add more details about your what is your starting structure. which screen you are showing first. splash screen is best option to do so