问题
I used SharedPreferences to make remember username and password to log in next time without asking a password. It was working well when I debug using my real device with USB cable. But it's not working in my device when I build APK and install it. I don't know what I'm missing.
I save data in login page like this`
Future<Null> loginUser(isLogin, name, fac, year, gender) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('Name', name);
prefs.setString('IsLogin', isLogin);
prefs.setString('Faculty', fac);
prefs.setString('Year', year);
prefs.setString('Gender', gender);
prefs.setString('Email', email);
print(prefs.getString('Faculty'));
}
I used this code in main page....
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return NewMain();
}
}
class NewMain extends StatefulWidget {
@override
_NewMainState createState() => _NewMainState();
}
class _NewMainState extends State<NewMain> {
var name, fac, year, gender, email;
var goToLogin = true;
@override
void initState() {
// TODO: implement initState
checkRem();
super.initState();
}
@override
Widget build(BuildContext context) {
if (goToLogin)
return MaterialApp(
home: Login(),
);
else
return MaterialApp(
home: MainClass(name, fac, year, gender, email),
);
}
void checkRem() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.getString('IsLogin') == 'Yes') {
goToLogin = false;
fac = prefs.getString('Faculty');
name = prefs.getString('Name');
gender = prefs.getString('Gender');
year = prefs.getString('Year');
email = prefs.getString('Email');
}
}
}
It will move to MainClass if goToLogin is false. It's working perfectly in debug. It's not working on the built apk app.
Solved
It was problem with my IDE. Updated and fixed
回答1:
Problem is u calling checkRem()
which is async in initState()
so build method getting called before complete execution of checkRem()
.
Soln:
wrap it with futureBuilder()
or calling setState()
after complete execution of method
来源:https://stackoverflow.com/questions/60808628/sharedpreferences-not-working-on-real-device-flutter