Home > Mobile >  How to store a List of strings in a TextFormField
How to store a List of strings in a TextFormField

Time:07-13

How to properly assign a List to a textformfield OnSaved

class _ProductsState extends State<Products> {
  List<String>? products;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Container(
        height: 100,
        width: 80,
        child: TextFormField(
          onSaved: (input){
            products=input; // A value of type 'String?' can't be assigned to a variable 
                                                       // of type 'List<String>?'
          },
        ),
)
);
}
}

I want whatever i type in the textfield gets stored in the List of products like this [0]['Whatever i type'],[1]['sdsdw']

CodePudding user response:

As the error message says:

A value of type 'String?' can't be assigned to a variable of type 'List?'

Your products variable is declared as a List<String>?, but you're then trying to assign an optional string value to it, but you can't assign a string to a list.

What you can do is add the input value to the list:

products.add(input);

Or you can declare products to be of the correct type:

String? products;

CodePudding user response:

I think your problem will be solved.

List<String>? products;
    
    return Scaffold(
        body:Container(
          height: 100,
          width: 80,
          child: TextFormField(
            onSaved: (input){
              products!.add(input!); 
            },
          ),
        )
    );
  • Related