如何使用 Listview 生成器在动态卡中设置 TextFormFields 和控制器

How to set TextFormFields and Controllers in dynamics Cards using Listview builder

我正在尝试在按下按钮时使用 textformfields 构建每张卡片,直到它达到某个限制,比如只有 10 张卡片,所以当我按下浮动按钮时,卡片正在添加,但 textformfields 中的文本每次按下都会被擦除.任何人都可以帮助我使用 textformfields 动态构建卡片而不用每次按下都擦除吗?下面我附上应用程序的屏幕截图。

 import 'package:flutter/material.dart';

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

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CardWithTextformfield(),
    );
  }
}

class CardWithTextformfield extends StatefulWidget {
  const CardWithTextformfield({Key? key}) : super(key: key);

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

class _CardWithTextformfieldState extends State<CardWithTextformfield> {

  var name =<TextEditingController>[];
  var id =<TextEditingController>[];

  var addCard =0;

  void incrementcard(){
    setState(() {
      if(addCard >=7){
        return;
      }
      addCard++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Card with TextformField'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: incrementcard,
        child: Icon(Icons.add),
      ),
      body: Container(
        child:ListView.builder(
          itemCount: addCard,
            itemBuilder: (context,index){
            return cardslist();
            }
        ),
      ),
    );
  }
  Widget cardslist(){
    var nameController = TextEditingController();
    var idController = TextEditingController();
    name.add(nameController);
    id.add(idController);
    return Card(
      margin: EdgeInsets.all(10),
      child: Container(
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                    margin: EdgeInsets.all(10),
                    child: Text('Name: ')),
                Expanded(child: TextFormField(
                  controller: nameController,
                    decoration: InputDecoration(hintText: 'Name'),
                ),),
                Container(
                  margin: EdgeInsets.all(10),
                  child: Text('EmpId: '),),
                Expanded(child: TextFormField(
                  controller: idController,
                    decoration: InputDecoration(hintText: 'EmpId'),
                ),),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

您的方法存在问题,即在插入新卡时重新创建每个控制器,这就是输入的值丢失的原因。相反,您应该检查当前卡的控制器是否已存在于您的阵列中,如果是,则使用现有控制器,否则创建一个新控制器。

为此,您必须将 index 作为参数添加到 cardsList 方法中。我认为下面的代码可以解决您的问题。

重要提示:销毁此控件时应销毁控制器,请添加该部分。您应该覆盖 _CardWithTextformfieldState 中的 dispose 方法,遍历两个数组中的所有控制器,并在每个控制器上调用 dispose()。最后别忘了调用 super.dispose().

import 'package:flutter/material.dart';

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

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CardWithTextformfield(),
    );
  }
}

class CardWithTextformfield extends StatefulWidget {
  const CardWithTextformfield({Key? key}) : super(key: key);

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

class _CardWithTextformfieldState extends State<CardWithTextformfield> {
  final _name = <TextEditingController>[];
  final _id = <TextEditingController>[];
  int _addCard = 0;

  void _incrementcard() {
    setState(() {
      if (_addCard >= 7) {
        return;
      }
      _addCard++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Card with TextformField'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementcard,
        child: Icon(Icons.add),
      ),
      body: Container(
        child: ListView.builder(
            itemCount: _addCard,
            itemBuilder: (context, index) {
              return cardslist(index);
            }),
      ),
    );
  }

  Widget cardslist(int index) {
    if (_name.length <= index) {
      _name.add(TextEditingController());
      _id.add(TextEditingController());
    }

    return Card(
      margin: EdgeInsets.all(10),
      child: Container(
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(margin: EdgeInsets.all(10), child: Text('Name: ')),
                Expanded(
                  child: TextFormField(
                    controller: _name[index],
                    decoration: InputDecoration(hintText: 'Name'),
                  ),
                ),
                Container(
                  margin: EdgeInsets.all(10),
                  child: Text('EmpId: '),
                ),
                Expanded(
                  child: TextFormField(
                    controller: _id[index],
                    decoration: InputDecoration(hintText: 'EmpId'),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}