Checking if item have value 'required'

Issue

so i make a survey form and the data/question is from api every data item has key ‘required’ if the question answer is not filled in yet the button to go to the next page is unavailable. How to make the if else condition for it ?

The form

enter image description here

The data

{
      "success": true,
      "msg": "OK",
      "data": [
        {
          "id": 4,
          "label":
              "Is this a test ride period or demonstration period in this PoC?",
          "required": true,
          "options": [
            {"label": "Test ride", "value": "1"},
          ],
        },
        {
          "id": 3,
          "label": "Have you answered this survey before?",
          "required": true,
          "options": [
            {"label": "No, for the first time", "value": "1"},
          ],
        }
      ]
    },

Solution

One way to do is using callbacks from the widgets for options.

class Data {
 int id; // Will be unique
 String label;
 bool requireds;
 List<Map<String, String>> options;
 bool added; // Add an extra parameter in the class to manage if the value is selected or not.

 Data({
  required this.id,
  required this.label,
  required this.requireds,
  required this.options,
  this.added = false, // Set the default value as false
 });
}

// Contains the list of data objects
List<Data> listData = [...];

// Callback from widgets to the parent widget
void updateData(bool isAdded, int id) {
 listData.firstWhere((element) => element.id == id).added = true; // Update the added bool to true whenever a value is selected for the widget
}

// On click condition, can be added to state updater as well to make
// the button disabled or enabled
void checkConditions() {
  List<Data> filter = [];
  filter.addAll(listData);
  // Filter the list for the condition
  filter.retainWhere((data){
    return data.requireds && !data.added; // If required and not added
  });

  // If the filter list is empty then all the required fields are answered
  if (filter.isEmpty) {
    // Go to next page or do an operation
  } else {
    // Do operation based on filter list values
  }
}

This is the snippet I wrote in dart, haven’t tried on a Flutter project. Let me know if this helps or you facing some other issues.

Answered By – pradyot1996

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *