artistAhmed
artistAhmed

Reputation: 325

Unable to post MAP values to https post in flutter

I have made a separate class which is my model class and has a function that posts to DISCORD WEB HOOK. I am setting the map values to true from the FORM UI screen. The textformfield value gets POSTED while MAP gives an error as following, just the textfield value gets posted and works fine but MAP doesn't work. Am I writing bad JSON?

P.S it is a discord hook so "content" is neccessary

I/flutter (26346): {"content": ["Could not interpret \"['testing options', {'Spot': True, 'Red': True, 'Thich': False, 'Dry': True, 'Strech': False}]\" as string."]}

Here is the code for the class

import 'dart:convert';

import 'package:http/http.dart';

class DataPush {
  static const String Spot = 'Spot';
  static const String Red = 'Red';
  static const String Thick = 'Thich';
  static const String Dry = 'Dry';
  static const String Strech = 'Strech';

  String firstName = '';
  Map<String, bool> passions = {
    Spot: false,
    Red: false,
    Thick: false,
    Dry: false,
    Strech: false,
  };
  save() {
    print("Saved");
  }

  makePostRequest() async {
    final uri = Uri.parse(
        'MY DISCORD WEBHOOK URL');
    final header = {'Content-Type': 'application/json'};
    Map<String, dynamic> body = {
      "content": [firstName, passions]
    };
    String jsonBody = json.encode(body);

    Response response = await post(
      uri,
      headers: header,
      body: jsonBody,
    );

    int statusCode = response.statusCode;
    String responseBody = response.body;

    print(statusCode);
    print(responseBody);
  }
}

Upvotes: 1

Views: 70

Answers (2)

Michael Horn
Michael Horn

Reputation: 4099

The Discord webhook documentation specifies the content field as a string, but you are sending an array as the value of that field - If you really want to send an array in the content field, you'll need to encode it as a json string itself first.

makePostRequest() async {
  final uri = Uri.parse(
      'MY DISCORD WEBHOOK URL');
  final header = {'Content-Type': 'application/json'};
  Map<String, dynamic> body = {
    "content": json.encode([firstName, passions]) // Change this line
  };
  String jsonBody = json.encode(body);

  Response response = await post(
    uri,
    headers: header,
    body: jsonBody,
  );

  int statusCode = response.statusCode;
  String responseBody = response.body;

  print(statusCode);
  print(responseBody);
}

Upvotes: 1

Madusha Lakruwan
Madusha Lakruwan

Reputation: 83

Remove this line and directly pass Map to post function.

String jsonBody = json.encode(body);

Upvotes: 1

Related Questions