Search code examples
fluttersharedpreferences

how to check if key exist shared preferences value and then open a new screen


i want to open a new screen if an email value exist in shared preferences

i want to call email function
and get the value of email function and check if it contains any value
if email() is not empty then redirect to a new screen

class SplashScreen extends StatefulWidget {
  SharedPreferences sharedPreferences;
  Future<String> email() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    return await preferences.getString("email");
  }

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

class _SplashScreenState extends State<SplashScreen>
    with SingleTickerProviderStateMixin {
  @override
  void initState() {
    super.initState();
    Future.delayed(
      Duration(seconds: 3),
      () {
        Navigator.pushReplacement(
            context,
            PageRouteBuilder(
                transitionDuration: Duration(milliseconds: 1500),
                pageBuilder: (_, __, ___) => Introduction_Screen()));
      },
    );
  }

 

Solution

  • You can do it like this..

    Call the function in initState..

    void initState() {
    super.initState();
    email();
    }
    

    And..in email()

    void email(){
    SharedPreferences preferences = await SharedPreferences.getInstance();
    var a = preferences.getString("email");
    if(a != null && !a.isEmpty){
    //Navigate to one screen
    } else {
    //Navigate to another screen
    }
    }
    

    Hope it answers your question.