【问题标题】:Delete textView in listView删除listView中的textView
【发布时间】:2020-10-09 04:02:03
【问题描述】:

当按下添加按钮时,它将添加一个文本字段。当我单击减号按钮时,我希望删除 TextField。但它不断删除错误的TextField。

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  var commentList = List();
  TextEditingController _commentsController = TextEditingController();


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Sample"),
        ),
        body: SingleChildScrollView(
            child: Padding(
                padding: EdgeInsets.all(10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(children: [
                      Text("Comments", style: TextStyle(color: Colors.grey)),
                      SizedBox(width: 20),
                      Container(
                          height: 35,
                          padding: const EdgeInsets.all(10.0),
                          child: InkWell(
                              onTap: () {
                                setState(() {
                                  commentList.insert(
                                      0, _commentsController.text);
                                });
                              },
                              child: Row(children: [
                                Icon(
                                  Icons.add,
                                  color: Colors.white,
                                  size: 15,
                                ),
                                SizedBox(width: 5),
                                Text(
                                  "Add",
                                  style: TextStyle(color: Colors.white),
                                )
                              ])),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10.0),
                            color: const Color(0xff0000ff),
                          )),
                    ]),
                    SizedBox(height: 15),
                    Padding(
                        padding: EdgeInsets.all(10),
                        child: _showListViewComments()),
                  ],
                ))));
  }

  Widget _showListViewComments() {
    return ListView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemCount: commentList.length + 1,
        itemBuilder: (BuildContext ctxt, int index) {
          if (index < commentList.length) {
            return Padding(
                padding: EdgeInsets.only(bottom: 10),
                child: Row(children: [
                  Expanded(
                      child: TextField(
                          maxLines: 3,
                          decoration: InputDecoration(
                            border: OutlineInputBorder(
                                borderRadius: const BorderRadius.all(
                                    const Radius.circular(5.0))),
                            contentPadding: EdgeInsets.all(10),
                          ))),
                  SizedBox(width: 10),
                  Container(
                      width: 30,
                      height: 30,
                      child: FloatingActionButton(
                        backgroundColor: Colors.red,
                        onPressed: () {
                          setState(() {
                            print(index);
                            commentList.removeAt(index);
                          });
                        },
                        child: Icon(
                          Icons.remove,
                          color: Colors.white,
                        ),
                      ))
                ]));
          }
        });
  }
}

例如:我有文本 1 和文本 2。我想删除文本 1 而不是文本 2。

【问题讨论】:

  • @pskink type 'TextEditingController' 不是类型 'String' 的子类型
  • 只需复制/粘贴此代码,无需任何修改:它工作得很好,无论如何这里你都有完整的代码:paste.ubuntu.com/p/bWv2jg9W56
  • 顺便说一句,不要将那些 SingleChildScrollView + ListView.builderphysics: NeverScrollableScrollPhysics() 技巧一起使用,因为它会一次构建 ListView.builder 中的所有项目
  • Coulmn(children: [Header1(), Header2(), Expanded(child: ListView.builder(...))])

标签: flutter listview textfield


【解决方案1】:

每个 TextField 都应该与定义的 TextEditingController 配对。我将您的代码编辑为

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<TextEditingController> commentList = List();
  //TextEditingController _commentsController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Sample"),
        ),
        body: SingleChildScrollView(
            child: Padding(
                padding: EdgeInsets.all(10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(children: [
                      Text("Comments", style: TextStyle(color: Colors.grey)),
                      SizedBox(width: 20),
                      Container(
                          height: 35,
                          padding: const EdgeInsets.all(10.0),
                          child: InkWell(
                              onTap: () {
                                setState(() {
                                  commentList.add(TextEditingController());
                                  // commentList.insert(
                                  //     0, _commentsController.text);
                                });
                              },
                              child: Row(children: [
                                Icon(
                                  Icons.add,
                                  color: Colors.white,
                                  size: 15,
                                ),
                                SizedBox(width: 5),
                                Text(
                                  "Add",
                                  style: TextStyle(color: Colors.white),
                                )
                              ])),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10.0),
                            color: const Color(0xff0000ff),
                          )),
                    ]),
                    SizedBox(height: 15),
                    Padding(
                        padding: EdgeInsets.all(10),
                        child: _showListViewComments()),
                  ],
                ))));
  }

  Widget _showListViewComments() {
    return ListView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemCount: commentList.length + 1,
        itemBuilder: (BuildContext ctxt, int index) {
          if (index < commentList.length) {
            return Padding(
                padding: EdgeInsets.only(bottom: 10),
                child: Row(children: [
                  Expanded(
                      child: TextField(
                          maxLines: 3,
                          controller: commentList[index],
                          decoration: InputDecoration(
                            border: OutlineInputBorder(
                                borderRadius: const BorderRadius.all(
                                    const Radius.circular(5.0))),
                            contentPadding: EdgeInsets.all(10),
                          ))),
                  SizedBox(width: 10),
                  Container(
                      width: 30,
                      height: 30,
                      child: FloatingActionButton(
                        backgroundColor: Colors.red,
                        onPressed: () {
                          setState(() {
                            print(index);
                            commentList.removeAt(index);
                          });
                        },
                        child: Icon(
                          Icons.remove,
                          color: Colors.white,
                        ),
                      ))
                ]));
          }
        });
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 2015-08-18
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多