Adham Ali
Adham Ali

Reputation: 21

Flutter SharedPreferences from a static method of a class return null

I am trying to make an HTTP request from a static method of dart class from my main screen this static method retrieves a variable stored in SharedPreferences and sends it with the HTTP request as a parameter but the value of this shredPref is always null or empty because the HTTP request is sent before I get the SharedPreferences value. How to get the value before making the HTTP request? here is my code:

call the method from the main screen when the button is clicked

      onPressed: () {
        if(isUserLoggedIn){
          MyHelper.toggleFavoritesProperty(context, property.property_id);
        }else{
          //show alert to user to login
        }
      },

and this is MyHelper class:

class MyHelper {
 static Future<String> getSharedPreferencesString(String key) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    String storedValue = preferences.getString(key);
    return storedValue;
  }

  static Future<bool> toggleFavoritesProperty(BuildContext context, String propertyID) async{
    MyHelper.progressDialogIndicatorOnly(true, context);
    String url = "https://www.apps.com/services/";
    var myData = {
      'post_id': propertyID,
      'user_id': await getSharedPreferencesString("user_id") ,
      'user_token': await getSharedPreferencesString("user_token") ,
      'rand':MyHelper.generateRandomNumberForURL()
    };

    var params = new Map<String, dynamic>();
    params['action'] = 'toggle_favorites';
    params['data'] = json.encode(myData);
    print(params);

    Response response = await post(url, body: params);
    Navigator.pop(context);
    print(response.body);
    if(response.statusCode == 200){
      var jsonData = json.decode(response.body);
      print(jsonData);
      if(jsonData["success"] == true){
        // everything is ok
      }else {
// validate failed
      }
    }else{
      //Navigator.pop(context);
      throw Exception("We can not finish your request!!!!");
    }
  }
}

Upvotes: 1

Views: 398

Answers (1)

Adham Ali
Adham Ali

Reputation: 21

There was a spelling mistake, everything worked fine once I fixed it

'user_token': await getSharedPreferencesString("user_token") ,

TO

'user_token': await getSharedPreferencesString("stored_user_token") ,

The key was wrong

Upvotes: 1

Related Questions