flutter - 如何手动删除 flutter 中的文本字段?

我正在制作一个可增长的文本字段小部件,用户可以根据需要添加任意数量的文本字段。在这种情况下,我使用的是文本字段列表。如果用户按下按钮添加文本字段,它将被添加到列表中。

如果用户想要并且我为此使用 listName.removeAt() 方法,还创建了一个删除文本字段的函数。但是当我删除一个有一些 value 的文本字段时,就会出现不匹配。我正在删除该索引的文本字段,但它保存的 value 转移到另一个字段。

我实现代码的地方是:

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);
                              },
                            ),
                          ),
                        );
                      },
                    );
                  },
                ),

在 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();
  }

回答1

MinimalInputField 中的 text 更改时,模型不会更新,而当模型更改时,MinimalInputField 中的 text 不会更新。

使用 TextField 可以是这样的:

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: "");
  }
...
}

相似文章

随机推荐

最新文章