我正在尝试在按下按钮时使用 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'),
),),
],
),
],
),
),
);
}
}