how to call api in flutter? the right way

Viewed 71

I am developing a flutter e-commerce app, and I have a few endpoints to connect with the network.

The problem is some of these endpoints (like login endpoint for example) don't work smoothly in the first time I call the endpoint(only the first time when I call the endpoint) otherwise it works just fine.

I don't know how is that possible, like if there was any logic problem it should happen every time I request it. ant idea??

for example in this situation

final response = await http.post(
          url,
          headers: {"Content-type": "application/json"},
          body: json.encode(
            {
              "usernameOrEmail": username,
              "password": password,
            },
          ),
        );
        final responseData = json.decode(response.body);
        _token = responseData['accessToken'];
        final prefs = await SharedPreferences.getInstance();
        final userData = json.encode(
          {
            'token': _token,
          },
        );
        prefs.setString('userData', userData);
        notifyListeners();

I am getting username and password from a form then i try to login and save profile details in shared preference.

now when I log in the first time it will not be logged in for quite a while sometimes it never login till I rebuild the app.

after the first time I log in, I can log in several times very smoothly without having any problem.

0 Answers
Related