1

So below is the JSON Structure which we are sending it as a request back. We are sending all three values as 3 separate text fields. But still very new to flutter and I am not able to figure out how to send it as a array.

{
  "name333": "myvarientName",
  "environment": "test1",
  "description": "Desc",
  "testcases": [
    {
      "name": "testname",
      "desc": "testdesc",
      "condition": "testname"
    },
    {
      "name": "testname",
      "desc": "testdesc",
      "condition": "testname"
    },
    {
      "name": "testname",
      "desc": "testdesc",
      "condition": "testname"
    }
  ]
}

Below is the code for sending the data (making api call)

ElevatedButton(
      onPressed: () {
        if (_formKey.currentState.validate()) {
          String variantName = variantNameController.text;
          String environment = environmentController.text;
          String varianDescription = variantDescriptionController.text;
          String testCaseName = testCaseNameController.text;
          String testCaseDescription = testCaseDescriptionController.text;
          String testCaseCondition = testCaseConditionController.text;

          Future<http.Response> createVaraint(Variant post) async {
            final response = await http.post(Uri.parse('Api Call URL'),
                headers: {HttpHeaders.contentTypeHeader: 'application/json'},
                body: variantToJson(post));
            return response;
          }

          Variant variant = Variant(
            name333: variantName,
            environment: environment,
            description: varianDescription,
          );

          createVaraint(variant).then((value) {
            if (value.statusCode > 200) {
              print(value.body);
            } else {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text(
                    'Variant has been created!',
                    style: TextStyle(fontSize: 18),
                  ),
                  behavior: SnackBarBehavior.floating,
                  duration: const Duration(seconds: 4),
                  elevation: 6.0,
                  margin: EdgeInsets.all(40.0),
                ),
              );
              print('Successssssss!' + value.statusCode.toString());
            }
          });
        }
      },
      style: ElevatedButton.styleFrom(
        primary: Color(0xff0962ff),
        textStyle: TextStyle(
          fontSize: 20,
          color: Colors.white,
          fontWeight: FontWeight.bold,
        ),
        shape: new RoundedRectangleBorder(
            borderRadius: new BorderRadius.circular(15)),
      ),
      child: Text("Create Variant"),
    )

Just to make sure, the testCaseName, testCaseDescription, testCaseCondition are the controllers for the array

1 Answer 1

1

Create model for Varient and use toJson and fromJson method to encode and decode map.

Varient class

class Variant {
  String name333;
  String environment;
  String description;
  List<Testcases> testcases;

  Variant({this.name333, this.environment, this.description, this.testcases});

  Variant.fromJson(Map<String, dynamic> json) {
    name333 = json['name333'];
    environment = json['environment'];
    description = json['description'];
    if (json['testcases'] != null) {
      testcases = new List<Testcases>();
      json['testcases'].forEach((v) {
        testcases.add(new Testcases.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name333'] = this.name333;
    data['environment'] = this.environment;
    data['description'] = this.description;
    if (this.testcases != null) {
      data['testcases'] = this.testcases.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Testcases {
  String name;
  String desc;
  String condition;

  Testcases({this.name, this.desc, this.condition});

  Testcases.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    desc = json['desc'];
    condition = json['condition'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['desc'] = this.desc;
    data['condition'] = this.condition;
    return data;
  }
}

How to create varient object with array of test cases

void onButtonPressed() {
  var varient = Variant(
    description: "Some Description",
    environment: "Add environment here",
    name333: "Add name here",
    testcases: [
      /// Test case 1
      Testcases(
        condition: "Some condition here",
        desc: "Some description here",
        name: "Add name here",
      ),

      /// Test case 2
      Testcases(
        condition: "Some condition here",
        desc: "Some description here",
        name: "Add name here",
      )
    ],
  );

  /// Send this data to the server or use it accordingly
}

Use case of Varient class

ElevatedButton(
      onPressed: () {
        if (_formKey.currentState.validate()) {
          String variantName = variantNameController.text;
          String environment = environmentController.text;
          String varianDescription = variantDescriptionController.text;
          String testCaseName = testCaseNameController.text;
          String testCaseDescription = testCaseDescriptionController.text;
          String testCaseCondition = testCaseConditionController.text;

          Future<http.Response> createVaraint(Variant post) async {
            final response = await http.post(Uri.parse('Api Call URL'),
                headers: {HttpHeaders.contentTypeHeader: 'application/json'},
                
               /// `post.toJson()` create Map<String,dynamic> object 
                body: post.toJson());
            return response;
          }

          Variant variant = Variant(
            name333: variantName,
            environment: environment,
            description: varianDescription,
          );

          createVaraint(variant).then((value) {
            if (value.statusCode > 200) {
              print(value.body);
            } else {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text(
                    'Variant has been created!',
                    style: TextStyle(fontSize: 18),
                  ),
                  behavior: SnackBarBehavior.floating,
                  duration: const Duration(seconds: 4),
                  elevation: 6.0,
                  margin: EdgeInsets.all(40.0),
                ),
              );
              print('Successssssss!' + value.statusCode.toString());
            }
          });
        }
      },
      style: ElevatedButton.styleFrom(
        primary: Color(0xff0962ff),
        textStyle: TextStyle(
          fontSize: 20,
          color: Colors.white,
          fontWeight: FontWeight.bold,
        ),
        shape: new RoundedRectangleBorder(
            borderRadius: new BorderRadius.circular(15)),
      ),
      child: Text("Create Variant"),
    )
Sign up to request clarification or add additional context in comments.

6 Comments

Hi, Yes I created model class exactly as you showed, just wondering how the request would look for array as in json structure I have an array as well. The rest all fields where fine with me, I was able to handle it, array is where i am not able to find anything :) Thanks for help!
Just curious on one thing, do we need to pass the List in Variant Model class, as i just see 3 things passed in dart code. But seems it has 4 fields in model
Yes @DarpalDhyani testcases is a mandatory field. you have to pass it, TheAlphamerc might have missed that.
The request will looks like exactly the json that you shared aboove.
If you didn't have data for test cases to send in api then you can skip it other wise create Variant object and initialise testcases as a list in model and create map by using toJason and send it to api.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.