Home > Net >  Submitting a Post to API from Flutter app always returning Exception: type 'int' is not a
Submitting a Post to API from Flutter app always returning Exception: type 'int' is not a

Time:01-03

I have the following API in a Django project where I am trying to send a log with some variables that are Int and String.

Here is the Api/views.py:

@api_view(['POST', 'GET'])
@permission_classes([IsAuthenticated])
def addlog(request,username, id):
    workout = Workout.objects.get(id=id, user=request.user)
    if request.method == 'POST':
        if workout.active:
            active_session = ActiveSession.objects.get(id=ActiveSession.objects.last().id)
            form = LogForm(request.POST)
            if form.is_valid():
                data = Log()
                data.user = request.user
                data.log_workout = request.POST.get('log_workout')
                data.log_exercise = request.POST.get('log_exercise')
                data.log_order = request.POST.get('log_order')
                data.log_repetitions = form.cleaned_data['log_repetitions']
                data.log_weight = form.cleaned_data['log_weight']
                data.workout_id = Workout.pk
                data.save()

In my flutter app I have created the api_service.dart as following:

  static Future<http.Response> addLog(int logWeight, int logRepetitions,
      int logOrder, String logExercise, String logWorkout, int id) async {
    var url = Uri.parse(Config.apiURL  
        Config.userAddlogAPI.replaceFirst("{id}", id.toString()));
    try {
      final response = await http.post(url, headers: {
        HttpHeaders.authorizationHeader:
            'Token xxxxxxxxxxxx',
      }, body: {
        'log_weight': logWeight,
        'log_repetitions': logRepetitions,
        'log_order': logOrder,
        'log_exercise': logExercise,
        'log_workout': logWorkout,
      });
     #.......if to catch error but it doesn't reach this part........................
  }

Here the screen.dart

 Form(
    child: Expanded(
      child: Column(
        children: [
          TextFormField(keyboardType:TextInputType.number,
            onChanged:(value) {final int?parsedValue = int.tryParse(value);
              if (parsedValue !=null) {setState(() { logWeight = parsedValue;});
              } else {}
            },),
          TextFormField(keyboardType:TextInputType.number,
            onChanged:(value) {
              final int?parsedValue = int.tryParse(value);
              if (parsedValue != null) {setState(() {logRepetitions = parsedValue;});
              } else {}},),
          OutlinedButton(child: Text('Add Log'),
            onPressed:
                () async {
              final Map<String, dynamic> arguments = ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
              final int id = arguments['id'] ??0;
              final String logWorkout = arguments['logWorkout'] ??'';
              final String logExercise = snapshot.data![index].name; // <-- set logExercise here
              final int logOrder = breakdown.order;
              print("$logRepetitions, $logWeight, $logOrder, $logExercise, $logWorkout, $id");
              print(id.runtimeType); 
              try {
                final http.Response response = await APIService.addLog(
                    logWeight, logRepetitions, logOrder, logExercise, logWorkout, id);
                if (response.statusCode == 200) {
                  print('Log submitted successfully');} else {
                  print('Failed to submit log');}
              } catch (error) { print(error);
                await showDialog( context: context, builder: (context) {
                    return AlertDialog(title:Text('Error'),
                      content: Text(error.toString()),
                      actions: [ OutlinedButton(
                          child: Text('OK'),
                          onPressed: () {Navigator.of(context).pop();
                          },),],); },); } }, ), ],),),),

So in the dart file there are 2 textfields and an outline button inside a form. The textfields are where users add their inputs in numeric values and when the user clicks on the submit I receive this error. I have made sure that the only 2 strings which are logExercise, logWorkout are actually strings. I am not sure what I am doing wrong and how to fix it. I am fairly new to flutter.

CodePudding user response:

You need to convert your int variables to String to use them inside http body

Sends an HTTP POST request with the given headers and body to the given URL. body sets the body of the request. It can be a String, a List<int> or a Map<String, String>. If it's a String, it's encoded using [encoding] and used as the body of the request. The content-type of the request will default to "text/plain".

If body is a List, it's used as a list of bytes for the body of the request.

If body is a Map, it's encoded as form fields using [encoding]. The content-type of the request will be set to "application/x-www-form-urlencoded"; this cannot be overridden.

encoding defaults to utf8.

CodePudding user response:

Before all please put all static value to check if this work or not then check below.

 final http.Response response = await APIService.addLog(
                    logWeight, logRepetitions, logOrder, logExercise, logWorkout, id);
TextFormField(keyboardType:TextInputType.number,onChanged:(value) {
              final int?parsedValue = int.parse(value == '' ? '0' : value);  /// Here Please use this
              if (parsedValue != null) {
                 setState(() {
                 logRepetitions = parsedValue;
                 });
                 } else {

                   }
                },),

and Also Runtime datatype all variables.

print("$logRepetitions, $logWeight, $logOrder, $logExercise, $logWorkout, $id");

  • Related