Asim Nasar siddiqui
Asim Nasar siddiqui

Reputation: 21

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()));
      },
    );
  }

 

Upvotes: 1

Views: 372

Answers (2)

Teja Reddy
Teja Reddy

Reputation: 1

You can do this.

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

void email() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    var email =  await preferences.getString("email");
     if (email?.isNotEmpty ?? true) {
          Navigator.pushReplacement(
            context,
            PageRouteBuilder(
                transitionDuration: Duration(milliseconds: 1500),
                pageBuilder: (_, __, ___) => Introduction_Screen()));
    }
    else{
       //navigaate to some other screen
     }
  } 

Upvotes: 0

srikanth7785
srikanth7785

Reputation: 1522

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.

Upvotes: 3

Related Questions