简体   繁体   中英

Flutter - How check string value from sharedPreferences

How check string value from sharedPreferences list is null or empty? If null or empty go to Login page else print value.

SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final myStringList = sharedPreferences.getStringList('my_sharedPreferences_list') ?? [];

if ( **myStringList[0]  is null or empty**   ) {
  print('> EMAIL not found!');
  Navigator.of(context).pushReplacement(MaterialPageRoute(
      builder: (context) => Login()
  ));
}
else { print(myStringList[0].toString()); }

getStringList returns nullable list of String List<String>? . You can simply check

SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final myStringList =
        sharedPreferences.getStringList('my_sharedPreferences_list');

if(myStringList==null ){ 
 print('> EMAIL not found!');
  Navigator.of(context).pushReplacement(MaterialPageRoute(
      builder: (context) => Login()
  ));
}
else { print(myStringList[0].toString()); }

You can check if your list is null or empty using this command myStringList == null || myStringList.isEmptymyStringList == null || myStringList.isEmpty .

|| indicates or operator

You have two way to check null The first likes Yeasin if(myStringList==null ) and the second set default value when you get like this

final myStringList =
    sharedPreferences.getStringList('my_sharedPreferences_list') ?? '';

Then check with empty or not empty

if (myStringList.isEmpty) {}
if (myStringList.isNotEmpty) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM