Skip to content
Advertisement

http.post is not working /sending null value in Flutter

The HTTP.POST method is not sending any variable back to the php script – I checked it using isset()

Code:

class QuizFin extends StatelessWidget{
  final List<Question> questions;
  final Map<int,dynamic> answers;
  int correctAnswers;
  QuizFin({Key key, @required this.questions, @required this.answers}): super(key: key);

  addData(String score) async{
    final response = await http.post("http://10.0.2.2/addscore.php", body:{
        "score" : score,
    });
  }
  @override
  Widget build(BuildContext context) {
    String s;
    int correct = 0;
    this.answers.forEach((index,value){
      if(this.questions[index].correctAnswer == value)
      correct++;
    });
    double score = ((correct/questions.length)* 100);
    s = score.toString();
    addData(s);

Beyond this is all UI and when I use debugPrint(s) – it prints the value

Advertisement

Answer

If you already checked up that the service is working, just add the headers in your request to indicate that you are using a json in your body and encode your map as json, try the follow:

addData(String score) async {
  final response = await http.post(
    "http://10.0.2.2/addscore.php",
    headers: {
      "Content-Type": "application/json; charset=utf-8",
    },
    body: json.encode(
      {
        "score": score,
      },
    ),
  );
}

Hope it helps, for more info please check the section Send data to the internet in the Flutter documentation.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement