Home > Blockchain >  Flutter API : How to post an "int" to a Json file without converting to a String?
Flutter API : How to post an "int" to a Json file without converting to a String?

Time:04-02

    Future<DataModel?> submitData(String name, int age) async {
  var response = await http.post(Uri.http("localhost:3000", "users"), body: {
    "name" : name,
    "job"  : age,
  });
  var data = response.body;
  print(data);

  if(response.statusCode == 201){
    String responseString = response.body;
    return dataModelFromJson(responseString);
  }
  else return null!;
}

I want to Post the age as an int but couldn't find a way to do that, the only thing i have to do is to convert the age to a String which i don't want to do. Is there any solution !??

CodePudding user response:

You can you the jsonEncode function from the dart:convert library.

body: jsonEncode(
  {
    "name": name,
    "job": job,
    "age": age,
  },

Make sure to import

import 'dart:convert';

Your final HTTP request will look like this:

var response = await http.post(
  Uri.http("localhost:3000", "users"),
  body: jsonEncode({
    "name": name,
    "job": job,
    "age": age,
  }),
);

CodePudding user response:

I fixed this problem with Dio.

first i added this line to pubspec.yaml :

 dependencies:
  dio: ^4.0.6

make sure to import it :

import 'package:dio/dio.dart';

My final HTTP request :

var dio = Dio(); 
var response = await dio.post('http://localhost:3000/users', data: {
    "name" : name,
    "job"  : age,
  });
  • Related