Idea is to use GetX with Stateless widgets and generate TextFields on demand.
GetX says that if we use its state management then we won’t require Stateful widgets.
On the click of the + button, I want a TextField to get added to the List. Currently nothing is happening on the click of the + button.
Please point out the error.
What is the proper way to achieve this through GetX?
This is the screen file:
import 'package:flutter/material.dart';
import 'package:dynamic_lists/controllers/2_ListWithInputBoxGetxController.dart';
import 'package:get/get.dart';
class ListWithInputBoxGetx extends StatelessWidget {
ListWithInputBoxGetx({Key? argKey, this.title}) : super(key: argKey);
final String? title;
ListWithInputBoxGetxController controller =
Get.put(ListWithInputBoxGetxController());
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title!)),
body: Padding(
padding: const EdgeInsets.all(10),
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
height: 400,
color: Colors.limeAccent,
child: ListView.builder(
itemCount: controller.textFieldControllerList.length,
prototypeItem: const TextField(),
itemBuilder: ((context, index) {
return Obx(() => TextField(
controller: controller.getTextFieldController(
index),
));
}))),
const SizedBox(height: 10),
ElevatedButton(
onPressed: controller.addTextField, child: const Text("+")),
const SizedBox(height: 10),
ElevatedButton(
onPressed: controller.submit,
child: const Icon(Icons.sailing))
],
))),
);
}
}
This is the controller file:
import 'package:get/get.dart';
import 'package:flutter/material.dart';
class ListWithInputBoxGetxController extends GetxController {
RxList<TextEditingController> textFieldControllerList =
<TextEditingController>[].obs;
TextEditingController getTextFieldController(argIndex) {
return textFieldControllerList[argIndex];
}
void addTextField() {
textFieldControllerList.add(TextEditingController());
}
void submit() {}
}
2
Answers
Well, the solution is to wrap
Obx
around theListView.builder
, not around theTextField
inside the ListView.You can use this code, this code is the edited version of your code
it looks like this