Home > Software design >  How do I create a list of map values on a button pressed in flutter
How do I create a list of map values on a button pressed in flutter

Time:03-16

I'm trying to create a List of values like

{ 
"name1" : "one"
},

where I get the "one" mentioned above from a textfield. Suppose I input three of such values in three separate textFields. Now I have to create a List called "names" as follows when I press a submit button

names: [
{ 
"name1" : "one"
},
{ 
"name2" : "two"
},
{ 
"name3" : "three"
},
]

here "one", "two", "three" are the textField values and I need to generate the rest when there is a button click event

(I have to create many of these for a http post I'll have to do later, So please feel free to let me know a better method if exists or please correct me if the procedure I'm heading with is wrong)

CodePudding user response:

you can do like this:

List names = [
    {"name1": "one"},
    {"name2": "two"},
    {"name3": "three"},
  ];
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 300,
      width: 300,
      child: ListView.builder(
        itemCount: names.length,
        shrinkWrap: true,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
              onTap: () {
                //do what you want here for each item
                print(names[index].keys.first.toString());
              },
              child: Text(names[index].keys.first.toString()));
        },
      ),
    );
  }

here you generate a ListView of Texts that are wrapped with GestureDetector, so you generate a list of Texts according to your list, and when you click on one of the texts you can do what ever you want according to the item you clicked on.

so for example, the output for the previous code would look like this: enter image description here

and when you click on one of the texts, you can do what you whatever you want according to the clicked item (here I just print the item to the consol).

CodePudding user response:

You need to add all TextField value in list look like below on button tap event

var nameOne = TextEditingController();
var nameTwo = TextEditingController();
var nameThree = TextEditingController();

List<Map<String,String>> names = [];


 void _submite() {

    if (nameOne.text.isEmpty) {
      print('Enter nameOne name');
    } else if (nameTwo.text.isEmpty) {
      print('Enter nameTwo name');
    } else if (nameThree.text.isEmpty) {
      print('Enter nameThree name');
    } else {
        names.add({"name1": nameOne.text});
        names.add({"name2": nameTwo.text});
        names.add({"name3": nameThree.text});
    }
  
 }

After call _submite() method

//OUTPUT : [{"name1" : "one"},{"name2" : "two"},{"name3" : "three"},]

  • Related