关闭应用程序后,共享的首选项将被删除 [英] shared preference is deleted when application is closed

查看:123
本文介绍了关闭应用程序后,共享的首选项将被删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用flutter构建登录屏幕,并以共享首选项保存用户数据(如果正确的是
),然后我在第二个屏幕中测试了保存的数据,并且在应用程序保存时已经保存了
关闭并再次打开,我检查共享的首选项,但它变为空
是我的saveData& getData函数

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并没有删除我所做的所有更改,但仍无法在我的设备和其他设备上运行
,并且不知道为什么!
如果没有解决方案,那么在扑扑中共享首选项是否有其他选择?
就是我使用saveDataPref()

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);

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

在这里,我检查登录数据是否正确
i测试了该功能,我工作
,它打开saveDataPref()
,我使用从另一个屏幕检索数据,它工作
,但是当关闭应用程序并再次打开它时,我使用getDataPref()但是检索到的数据为空
,在这里我使用getDataPref()来检查用户是否已经注册,因此请转到UserApp屏幕,如果未打开主屏幕,则显示

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


推荐答案

i在这里
中找到了解决方案 Flutter:启动时共享首选项为空
,请注意,如果您像在
之前那样在主类之外调用它,则
共享首选项将不起作用,您应该在initState()
内部调用它

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

这篇关于关闭应用程序后,共享的首选项将被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆