Home > OS >  Map list of strings to a array of TextEditingControllers
Map list of strings to a array of TextEditingControllers

Time:08-03

I have a list of textFormfields in a slider and I'm getting a list of data from the api which contains a description.I need to map that descriptions to the TextEditingControllers to show them on the textFormfield.Can someone please give me a solution for this?

Example: List<TextEditingController> _controllers = [];

    "data": [
        {
            "id": 1,
            "value": "Title 1”,
            “description: "description 1”,
            "userId": 1,
            
        },
{
            "id": 2,
            "value": "Title 2”,
            "description": "description 2”,
            "userId": 2,
            
        },
{
            "id": 3,
            "value": "Title 3”,
            "description": "description 3”,
            "userId": 3,
            
        },
        
        
    ],
    
}

CodePudding user response:

First of All create Model of your response like below

class MyModelData {

  int? id;
  String? value;
  TextEditingController? description = TextEditingController();
  int? userId;

  MyModelData({
    this.id,
    this.value,
    this.description,
    this.userId,
  });
  MyModelData.fromJson(Map<String, dynamic> json) {
    id = json['id']?.toInt();
    value = json['value']?.toString();
    description = json['description'];
    userId = json['userId']?.toInt();
  }
  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['id'] = id;
    data['value'] = value;
    data['description'] = description;
    data['userId'] = userId;
    return data;
  }
}

then create list like this

List<MyModelData> dataList = <MyModelData>[];

below list?.forEach is the list for data that you are getting from API's response

list?.forEach((element) {
         dataList.add(RoomDimensionModel(
            id: element.id,
            value: element.id,
            description: TextEditingController(element.description),
            userId: element.userId,
          ));
        });

then use dataList every where you would like to use in UI.

CodePudding user response:

Assuming you parsed the response successfully. What you need is to use the map function provided for dart lists:

List<String> descriptions = dataList.map((e) => e.description).toList();
          print(descriptions);

And then just use a loop to assign these descriptions to the TextControllers list:

for (var i = 0; i < controllersList.length;   i) {
            var textController = controllersList[i];
            var desc = descriptions[i];
            textController.text = desc;
          }

of course the textControllers list is as the same length as the descriptions list.

  • Related