按下按钮时删除小部件 Flutter

Delete Widget at button press Flutter

最近在按下“+”按钮时实现了一个 tagForm 小部件,我现在想在按下“删除”按钮时删除这些小部件,但是现在,即使我按下“删除”按钮,也没有任何效果发生了。

我该如何解决这个问题?

感谢任何帮助!

代码:

import 'package:flutter/material.dart';
import '../database/firestoreHandler.dart';
import '../models/todo2.dart';
import '../widgets/dialogs.dart';

class TodoEdit extends StatefulWidget {
  String? doctitle;
  String? doctdescription;
  String? docimage;
  String? docid;
  List? doctags;

  TodoEdit({Key? key, this.doctitle, this.doctdescription, this.docimage, this.docid,this.doctags}) : super(key: key);


  @override
  _TodoEditState createState() => _TodoEditState();

}


class _TodoEditState extends State<TodoEdit> {
  final _formKey = GlobalKey<FormState>();
  final tcontroller = TextEditingController();
  final dcontroller = TextEditingController();
  final icontroller = TextEditingController();

  var textEditingControllers = <TextEditingController>[];
//-----------------the list where the form is stored----------
  var textformFields = <Widget>[];

  void _addformWidget(controller) {
    setState(() {
      textformFields.add(tagForm(controller));
    });
  }
//------------------------------------------------------------------------
  Widget tagForm(controller){

    return TextFormField(
      controller: controller,
      style: TextStyle(color: Colors.white),
      decoration: InputDecoration(
          labelText: "Tag",
          labelStyle: TextStyle(color: Colors.white60),
          fillColor: Colors.black,
          filled: true,
          suffixIcon: IconButton(
            icon:Icon(Icons.delete, color: Colors.white,),
//--------------------- doesn't work?-------------------
            onPressed: (){
              setState(() {
                textformFields.remove(tagForm(controller));
              });
            },
--------------------------------------------------------------
          )
      ),
    );

  }

//-----------------------------------------------------------

  @override
  void initState() {

    super.initState();
    tcontroller.text = widget.doctitle.toString();
    dcontroller.text = widget.doctdescription.toString();
    icontroller.text = widget.docimage.toString();

    widget.doctags?.forEach((element) {
      var textEditingController = new TextEditingController(text: element);
      textEditingControllers.add(textEditingController);
      //return textformFields.add(tagForm(textEditingController)
      return _addformWidget(textEditingController);
      //);
    });
    
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.grey[900],
      appBar: AppBar(
        actions: [
          IconButton(onPressed: (){
            showDialog(
              barrierDismissible: false,
              context: context,
              builder: (context) {
                return AlertDialog(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                  title: Text('Delete TODO'),
                  actions: [
                    TextButton(
                      child: Text('Cancel'),
                      onPressed: () {
                        Navigator.pop(context);
                      },
                    ),
                    TextButton(
                      child: Text('Delete'),
                      onPressed: () {
                        deleteData(widget.docid.toString(), context);
                        setState(() {
                          showSnackBar(context, 'todo "${widget.doctitle}" successfully deleted!');
                        });
                      },
                    ),
                  ],
                );
              },
            );
          },
              icon: Icon(Icons.delete))
        ],
        backgroundColor: Colors.grey[900],
        title: Text("${widget.doctitle}"),
      ),
      body: Container(
        child: SafeArea(
        child:  Form(
          key: _formKey,
          child: Column(
            children: [
              SizedBox(height: 10),
              TextFormField(
                controller: tcontroller,
                style: TextStyle(color: Colors.white),
                decoration: InputDecoration(
                  labelText: "Title",
                  labelStyle: TextStyle(color: Colors.white60),
                  fillColor: Colors.black,
                  filled: true,
                ),
              ),
              SizedBox(height: 10),
              TextFormField(
                controller: dcontroller,
                style: TextStyle(color: Colors.white),
                decoration: InputDecoration(
                  labelText: "Description",
                  labelStyle: TextStyle(color: Colors.white60),
                  fillColor: Colors.black,
                  filled: true,
                ),
              ),
              SizedBox(height: 10),
              TextFormField(
                controller: icontroller,
                style: TextStyle(color: Colors.white),
                decoration: InputDecoration(
                  labelText: "Image url",
                  labelStyle: TextStyle(color: Colors.white60),
                  fillColor: Colors.black,
                  filled: true,
                ),
              ),
              SizedBox(height: 10),
              Row(children: [
                Text("Tags:", style:TextStyle(color: Colors.white)),
                IconButton(onPressed: (){
                  var textEditingController = new TextEditingController(text: "tag");
                  textEditingControllers.add(textEditingController);
                  _addformWidget(textEditingController);
                  print(textformFields.length);
                },
                  icon: Icon(Icons.add,color: Colors.white,),
                )
              ],),
              /*SingleChildScrollView(
                child: new Column(
                children: textformFields,
                )
              ),*/
              Expanded(
                  child: SizedBox(
                    height: 200.0,
                    child: ListView.builder(
                        itemCount: textformFields.length,
                        itemBuilder: (context,index) {
                          return textformFields[index];
                        }),
                  )
              ),
            ],
          ),
        ),
        ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: (){
            List<String> test = [];
            textEditingControllers.forEach((element) {
              test.add(element.text);
            });

            if(tcontroller == '' && dcontroller == '' && icontroller == ''){
              print("not valid");
            }else{
              var todo = Todo2(
                title: tcontroller.text,
                description: dcontroller.text,
                image: icontroller.text,
                tags: test,
              );
              updateData(todo, widget.docid.toString(),context);
              setState(() {
                showSnackBar(context, 'todo ${widget.doctitle} successfully updated!');
              });
            }
          },
          child: Icon(Icons.update),
    ),
    );
  }
}




您不能从列表中删除包含来自 tagForm(controller) 的对象的任何内容,因为这些对象是新创建的,因此与列表中的对象不同(只要 == 运算符是未覆盖)

如果您仍然希望将小部件放在列表中而不是仅仅存储控制器并且不需要做太多更改,您可以像这样删除小部件:

onPressed: (){
  setState(() {
    controller.dispose();
    textEditingControllers.remove(controller);
    textformFields.removeWhere((w) => w.controller = controller));
  });
},

并更改列表的类型:var textformFields = <TextFormField>[]; 和方法 TextFormField tagForm(controller)

一般来说,您当然可以优化状态管理,但使用此解决方案目前应该可以使用。

不要存储Widget,这是不好的方法。而是存储在那里 属性,由 List 渲染,然后在需要时由 index 删除。

ps: 部分代码语法错误,我是在浏览器上写的。

class _TodoEditState extends State<TodoEdit> {
  ...
  var textformFields = <String>[];
  ...
  void _addformWidget([String? initValue]) {
    setState(() => textformFields.add(initValue ?? ""));
  }
  ...
  Widget tagForm(String value, void Function(String) onChange, void Function() onRemove){
    var openEditor = () {
      // Open dialog with text field to edit from [value] call onChange with
      // new value
      OpenDialog().then((newvalue) {
        if(newvalue != null) onChange(newvalue);
      }
    };
    var delete = () {
      // Open confirm dialog then remove
      OpenConfirmDialog("your message").then((continue) {
        if(continue) onRemove();
      });
    };

    return InkWell(
      onTap: openEditor,
      child: Text(value), // render your tag value 
    );
  }
  ...
  @override
  void initState() {
    ...
    textformFields = List.filled(widget.doctags ?? 0, ""); // or List.generate/map if you want replace by own value.
  }
  ...
   @override
  Widget build(BuildContext context) {
    ...
    ListView.builder(
      itemCount: textformFields.length,
      itemBuilder: (context,index) => tagForm(
        textformFields[index],
        (newvalue) => setState(() => textformFields[index] = newvalue),
        () => setState(() => textformFields = textformFields..removeAt(index));,
      ),
    ),
    ...
  );
}