Search code examples
fluttersharedpreferences

Flutter LateInitializationError: Field 'docname' has not been initialized


I am getting the data from API only once a time when the user authenticates and I need to use that details in the drawer and homepage when my API function I saved the data and it returns the real value when I try to use that details on my drawer I'm getting this error

LateInitializationError: Field 'docname' has not been initialized.

this is the function in my drawer I called

  late var docemail;
  late var docname;
  late var doctelephone;
  late var docspecialization;
  late var docslmc;

  getdocdetails() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    docname = prefs.getString("DocName");
    docemail = prefs.getString("DocEmail");
    doctelephone = prefs.getString("DocTelephone");
    docspecialization = prefs.getString("Docspecialization");
    docslmc = prefs.getString("DocSLMC");
  }

this is the function I used to call the API

Future getDocDetails() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var uuid = prefs.getString("userId");
    try {
      final response = await http.get(
        Uri.parse(
            "$baseUrl/doctors?uuid=$uuid&search_phrase=&specialization=0"),
      );
      Logger().wtf(response.statusCode);
      if (response.statusCode == 200) {
        final jsonresponse = json.decode(response.body);
        DoctorModel doctor = DoctorModel.fromJson(jsonresponse[0]);
        await prefs.setString("DocName", doctor.doctorName);
        await prefs.setString("DocEmail", doctor.email);
        await prefs.setString("DocTelephone", doctor.telephone);
        await prefs.setString(
            "Docspecialization", doctor.specialization.specialization);
        await prefs.setString("DocSLMC", doctor.specialization.id.toString());
      } else {
        Logger().v("not found any data");
        throw Exception('Failed to load user');
      }
    } catch (e) {
      Logger().e(e);
      rethrow;
    }
  }

Solution

  • For those who had the same issue this is how I solved this

      String accessToken = "";
      String docemail = "";
      String docname = "";
      String doctelephone = "";
      String docspecialization = "";
      String docslmc = "";
    
      getdocdetails() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        setState(() {
          accessToken = (prefs.getString('acessToken') ?? "");
          docname = (prefs.getString("DocName") ?? "");
          docemail = (prefs.getString("DocEmail") ?? "");
          doctelephone = (prefs.getString("DocTelephone") ?? "");
          docspecialization = (prefs.getString("Docspecialization") ?? "");
          docslmc = (prefs.getString("DocSLMC") ?? "");
        });
      }