I am trying to make game score tracked game, and I have a page where the user enters the number of players and go to another page to enter their names, so he is going to PlayersIntroductionScreen() with the number of players, in the players introduction screen I need to display several TextFormField() based on the players number and I can made this with for(), but the problem is I need a TextEditingController() for each TextFormField()
class PlayersIntroductionScreen extends StatelessWidget {
const PlayersIntroductionScreen({Key? key, required this.playersNumber}) : super(key: key);
final int playersNumber;
@override
Widget build(BuildContext context) {
return Placeholder();
}
}
I tried to make a for loop before the overriden build() but it says Expected a class member.
How can I achieve that with unique name for every controller like
var firstPlayerController = TextEditingController()
and so on
2
Answers
To create a dynamic number of text editing controllers with unique names in Flutter, you can use a
List
to store the controllers and assign a unique name to eachcontroller
based on its position in the list.Each text field will be manage by a unique controller with unique instance. So i think you no need to add name for each of these. (Your player isn’t place their name, so all of them still anonymous)
You could make a List to manage each field and access by index.
Your class could be