List of TextEditingController in Flutter
The TextEditingController
class in Flutter is used to provide an interface for controlling text fields, such as retrieving and modifying the text value, as well as responding to changes in the text field.
Below is an example of creating a list of TextEditingController
objects in Flutter:
import 'package:flutter/material.dart';
class MyWidget extends StatelessWidget {
List _controllers = [
TextEditingController(),
TextEditingController(),
TextEditingController(),
];
@override
Widget build(BuildContext context) {
return Container();
}
}
In the above example, we create a List
of TextEditingController
objects with 3 elements. Each element represents a text field that can be controlled using the corresponding TextEditingController
object.
Let’s say we have a screen with three text fields where users can enter their name, email, and password. We can associate each text field with a TextEditingController
to control its behavior. Here’s an example:
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State {
List _controllers = [
TextEditingController(),
TextEditingController(),
TextEditingController(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
TextField(
controller: _controllers[0],
decoration: InputDecoration(
labelText: 'Name',
),
),
TextField(
controller: _controllers[1],
decoration: InputDecoration(
labelText: 'Email',
),
),
TextField(
controller: _controllers[2],
decoration: InputDecoration(
labelText: 'Password',
),
obscureText: true,
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
String name = _controllers[0].text;
String email = _controllers[1].text;
String password = _controllers[2].text;
// Do something with the entered values
},
child: Icon(Icons.save),
),
);
}
}
In this example, we create a Scaffold
with a Column
widget as the body. Inside the column, we add three TextField
widgets, each associated with a TextEditingController
from the list.
We can access the text entered in each text field using the corresponding TextEditingController
. In the FloatingActionButton
‘s onPressed callback, we get the text from each controller and perform any desired actions with the entered values.