'How to manually delete a textfield in flutter?
I am making a growable Textfield widget that a user can add as many textfield as he wants. I am using a list of textfields in this case. If user presses button to add textfield , it will be added to the list .
Also have created a function to delete the textfield if user wants and ima useing listName.removeAt() method for this . But when i delete a textfield which got some value there is a mismatch . I am deleting the textfield of that index but the value it holds shifts to another field.
Where i implement the code is :
Consumer(
builder: (ctx, ref, child) {
final customCourse =
ref.watch(customCourseTypeNotifierProvider);
return ListView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: customCourse.customCourses.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: MinimalInputField(
onChanged: (String value) {
},
hintText: "",
suffixIcon: IconButton(
icon: const Icon(Icons.remove),
color: Colors.red,
onPressed: () {
ref
.read(customCourseTypeNotifierProvider)
.removeCourse(index);
},
),
),
);
},
);
},
),
In type_controller.dart
class CourseTypeNotifier extends ChangeNotifier {
List<CustomCourseModel> customCourses = [];
void addCourse() {
customCourses.add(
const CustomCourseModel(title: "", description: ""),
);
notifyListeners();
}
void removeCourse(int index) {
customCourses.removeAt(index);
notifyListeners();
}
Solution 1:[1]
When text in MinimalInputField changes, the model is not updated and when the model is changed, text in MinimalInputField is not updated.
Using TextField could go something like this:
TextField(
controller: TextEditingController()..text = customCourse.customCourses[index].title!,
onChanged: (String value) {
ref.read(customCourseTypeNotifierProvider).updateCourse(index, value);
},
...
)
class CourseTypeNotifier extends ChangeNotifier {
...
void updateCourse(int index, String title) {
customCourses[index] = CustomCourseModel(title: title, description: "");
}
...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user18309290 |
