4

i am building a log in screen using flutter and save user data in shared preference if it is right then i tested the saved data in the second screen and it has been already saved when the app is closed and open again i check the shared pref but it becomes null that's my saveData & getData Functions

String namePref,phonePref, typePref,statePref;
Future saveDataPref(String name,String phone, String type, String state )async{
  SharedPreferences pref = await SharedPreferences.getInstance();
  pref.setString('phone', phone);
  pref.setString('name', name);
  pref.setString('type', type);
  pref.setString('state', state);
  pref.commit();
  print('pref stored');
  print('${pref.getString('phone')}');
}

Future getDataPref() async{
  SharedPreferences pref = await SharedPreferences.getInstance();
  phonePref = pref.getString('phone');
  namePref = pref.getString('name');
  typePref = pref.getString('type');
  statePref = pref.getString('state');
}

i should mention two things "commit" function is deprecated the second one is that the code was working with the deprecated commit but it is not now i removed all the changes i have done but it still not working on my device and other devices and don't know understand why ! if there is no solution, is there any alternative to shared preference in flutter ? that's where i use saveDataPref()

Future login(BuildContext context) async {
  String password = passwordController.text;
  String phone = phoneController.text;
  print("entered login function");
  //check if the user is registered
  Map<String, User> users = new Map<String, User>();
  users = await getUserDataFromFireStore();
  if (await userCheck(phone)) {
    // user is registered check if it is the right password
    if (users[phone].password == password) {
      // check if the user have an order

saveDataPref( users[phone].phone, users[phone].name, "user", users[phone].ordered);

      if (users[phone].ordered == "true") {
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => OrderBinding()));
        return;
      } else {
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => UserApp(
                      userName: users[phone].name,
                      userPhone: users[phone].phone,
                    )));
        return;
      }
    } else {
      ShowDialogue(
          "تم إدخال كلمة السر بشكل خاطئ من فضلك تأكد من كلمة السر", context);
    }
  }

  Map<String, Driver> drivers = new Map<String, Driver>();
  drivers = await getDriverDataFromFireStore();
  if (await DriverCheck(phone)) {
    // user is registered check if it is the right password
    if (drivers[phone].password == password) {
      //check if driver account is activated
      if (drivers[phone].activation == "true") {
        saveDataPref(drivers[phone].phone, drivers[phone].name, "driver",
            drivers[phone].activation);
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => DriverApp()));
      } else {
        ShowDialogue(
            "لم يتم تفعيل حسابكم بعد يرجى الانتظار وسيتم التواصل معكم قريباً",
            context);
      }
    } else {
      ShowDialogue(
          "تم إدخال كلمة السر بشكل خاطئ من فضلك تأكد من كلمة السر", context);
    }
  } else {
    ShowDialogue(
        "لم يتم تسجيل هذا المستخدم من فضلك قم بانشاء حساب اولا", context);
  }
}

here i check if the login data is right i tested the function and i works it opens saveDataPref() and i use retrieve data from another screen and it works but when closing the app and open it again i use getDataPref() but the retrieved data is null here where i use getDataPref() to check if the user is already register so go tu UserApp screen and if not open home screen

checkSigned() {
  getDataPref();
  print("${phonePref}");
  print("${namePref}");
  if (phonePref != null) {
    print("${phonePref}");

    if (phonePref != "") {
      print("${phonePref}");

      return new UserApp(
        userName: namePref,
        userPhone: phonePref,
      );
    } else {
      return new MyHomePage();
    }
  } else {
    return new MyHomePage();
  }
}

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Generated App',
      theme: new ThemeData(
        primarySwatch: Colors.lightGreen,
        primaryColor: const Color(0xFF8BC34A),
        accentColor: const Color(0xFF8BC34A),
        canvasColor: const Color(0xFFEEEEEE),
      ),
      home: checkSigned(),
    );
  }
}
Ahmed El Sayed
  • 499
  • 1
  • 8
  • 17

4 Answers4

3

I came to the conclusion that i was using prefs.clear() in my app somewhere due to which the data was getting lost. Make sure there is no prefs.clear() written in any of your activity.

Abdullah Arshad
  • 156
  • 2
  • 6
1

Make sure you are not calling pref.clear(); anywhere in your code.

loadUserId() async {
SharedPreferences pref = await SharedPreferences.getInstance();
setState(() {
  userId = pref.getString("userId");
});}

And finaly call the above function inside your initState() like this:

@override
    void initState() {
     super.initState();
      loadUserId();
 }
Kashif Ahmad
  • 203
  • 3
  • 15
0

I found the solution in here:

Flutter: Shared Preferences null on Startup

And note that, shared preference will not work if you called it outside the main class as I did before. You should call it inside initState(). This works:

@override
  void initState() {
    super.initState();
    readFile('phone');
    SharedPreferences.getInstance().then((SharedPreferences sp) {
      sharedPreferences = sp;
      ph = sp.getString('phone');
      setState(() {});
    });
  }
Akif
  • 7,098
  • 7
  • 27
  • 53
Ahmed El Sayed
  • 499
  • 1
  • 8
  • 17
  • 1
    It still not working for me : [shared preferecences do not persist](https://stackoverflow.com/questions/54523760/flutter-sharedpreference-do-not-persist). – Jérémy Feb 05 '19 at 22:15
0

Removed the Line

SharedPreferences.setMockInitialValues({});

code working