我尝试创建一个自定义TextformField列表,可以使用带有Map功能的按钮删除该列表,但TextformField无法正确删除。
它始终是最后删除的Widget。
有人有解决办法吗?
有没有可能创造出一个比他更好的东西
谢谢你!
下面是我的测试代码
您可以在Darpad中尝试以下代码
enter image description here
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late List<int> _listID = [0, 1, 2, 3];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: _listID.map((id) {
print(id);
return TestWidget(
id: id,
onPressed: () {
setState(() {
_listID.remove(id);
print(_listID);
});
},
);
}).toList()),
floatingActionButton: FloatingActionButton(
onPressed: () {},
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
class TestWidget extends StatefulWidget {
TestWidget({super.key, this.onPressed, required this.id});
late VoidCallback? onPressed;
late int id;
@override
State<TestWidget> createState() =>
_TestWidgetState(onPressed: this.onPressed, id: id);
}
class _TestWidgetState extends State<TestWidget> {
late VoidCallback? onPressed;
late int id;
_TestWidgetState({required this.id, this.onPressed});
@override
Widget build(BuildContext context) {
return TextFormField(
decoration: InputDecoration(
labelText: id.toString(),
suffixIcon: IconButton(
icon: const Icon(Icons.clear), onPressed: () => onPressed!()),
));
}
}
2条答案
按热度按时间wz3gfoph1#
你必须传递一个键给你的TestWidget来保存每个小部件的状态对象,方法如下:
你可以从youtube的Flutter频道了解更多关于密钥的信息
2ul0zpep2#
您不需要将数据传递给状态类,可以使用
widget.variableName