skip to Main Content

So I am using rest api as back end , I am unable to edit so I found that the token needs to be passed , from login to this change-profile api , so that the user can succesfully edit his or her details .

Future updateProfile() async {
String url = "http://167.71.232.83:8000/myprofile/${userId}/";

// Build the query parameters with updated user information
Map<String, String> queryParams = {
  "email": _emailController.text,
  "password": passwordController.text,
  "repassword": repasswordController.text,
  "firstname": firstname.text,
  "lastname": lastname.text,
  "phonenumber": phonenumber.text,
  "state": state.text,
  "city": city.text,
  "Zip": zip.text,
  "mailing": _value.toString(),
  "referred_by": selectedItem,
  "flag": "business",
  "businessname": businesscontroller.text,
};
String queryString = Uri(queryParameters: queryParams).query;
url += '?' + queryString;

try {
  final response = await http.put(
    Uri.parse(url),
    headers: {
      "Content-Type": "application/json",
      "User-Agent": "PostmanRuntime/7.28.4",
      "Accept": "*/*",
      "Accept-Encoding": "gzip, deflate, br",
      "Connection": "keep-alive",
    },
  );

  var data = jsonDecode(response.body);

  print(url);
  print(response.statusCode);
  print(data);

  if (response.statusCode == 200) {
    // Success
    _showSuccessDialog();
    // Navigate to the next page or perform any other actions
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (_) => BottomPage(),
      ),
    );
  } else {
    // Error
    _showErrorDialog('Failed to update profile. Please try again.');
  }

  print(response.body);
} catch (e) {
  print('Error updating profile: $e');
  _showErrorDialog('Failed to update profile. Please try again.');
}

}

I attached the code snippet above of what I tried
I need to modify it in such a way that it can access the token from succesful login which can help to edit information .

2

Answers


  1. This should help

        final token = "your-backend-token";
    
        final response = await http.put(
          Uri.parse(url),
          headers: {
            "Content-Type": "application/json",
            "User-Agent": "PostmanRuntime/7.28.4",
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate, br",
            "Connection": "keep-alive",
            HttpHeaders.authorization: token,
          },
        );
    

    Additionally you could have something like this

    class ApiHandler {
      ApiHandler.instance(); // for instantiating request withou token
    
      String? _token;
    
      ApiHandler.tokenInstance() {
        _token = getToken() ?? throw "No Token found";
        // `getToken()` gets token from shared preferences or wherever you have stored.
      }
    
      // use this for public api requests
      Map<String, String> get jsonHeaders = {
        HttpHeaders.contentType: "application/json",
      }
    
      // use this for authorized api requests
      Map<String, String> get tokenHeaders = {
        HttpHeaders.contentType: "application/json",
        HttpHeaders.authorization: _token,
      }
    
      // your other api request methods  
    }
    
    Login or Signup to reply.
  2. You need to use SharedPreferences package to store the token from successful login this:

    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('token', '$<yourToken>');
    

    then when you need to access a token just call:

    final SharedPreferences prefs = await SharedPreferences.getInstance();
    final String? token = prefs.getString('token');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search