In this example, I will share how to create dynamic number of texteditingcontrollers in your flutter application. I think its easy to call textEditingControllers with key value pairs. Modified code block.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: "MyHomePage", theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage( title: "MyHomePage", ), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { var stringListReturnedFromApiCall = ["first", "second", "third", "fourth", "..."]; // This list of controllers can be used to set and get the text from/to the TextFields Map<String,TextEditingController> textEditingControllers = {}; var textFields = <TextField>[]; stringListReturnedFromApiCall.forEach((str) { var textEditingController = new TextEditingController(text: str); textEditingControllers.putIfAbsent(str, ()=>textEditingController); return textFields.add( TextField(controller: textEditingController)); }); return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: SingleChildScrollView( child: new Column( children:[ Column(children: textFields), RaisedButton( child: Text("Print Values"), onPressed: (){ stringListReturnedFromApiCall.forEach((str){ print(textEditingControllers[str].text); }); }) ] ))); } } |
Here is the output:
1 2 3 4 5 | flutter: first controller text flutter: second controller text flutter: third controller text flutter: fourth controller text flutter: so on ....... |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.