我正在努力从生成的列表中删除项目。我对颤振和编程还很陌生。有人可以帮忙吗?我已经阅读了几篇文章,但我听不懂。
class AddPoll extends StatefulWidget {
AddPoll({
Key key,
this.items,
this.index,
}): super(key: key);
final Map items;
final int index;
@override
AddPollState createState() => new AddPollState();
}
class AddPollState extends State < AddPoll > {
int _index = 0;
String q;
Map formData = {};
Map answers = {};
var _items = List < Widget > ();
_remove(keyValue) {
print(keyValue);
// List.from(_items)..removeAt(keyValue);
answers.remove(keyValue);
// answers.
}
void _add() {
int keyValue = _index;
_items = List.from(_items)..add(
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
child: TextField(
decoration: InputDecoration(
labelText: 'Answer ${keyValue+1}',
suffixIcon: IconButton(icon: Icon(Feather.minus_circle), onPressed: () {
_remove(keyValue);
})
),
onChanged: (val) {
answers["a$keyValue"] = val;
},
),
),
);
setState(() => ++_index);
}
@override
void initState() {
super.initState();
_add();
}
save() async {
formData = {
'q': q,
'a': answers
};
print(formData);
Navigator.pop(context, formData);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: Text("Add Question"),
actions: < Widget > [
FlatButton(
child: Text("Save"),
textColor: Theme.of(context).primaryColor,
onPressed: () {
save();
},
)
],
),
body: ListView(
shrinkWrap: true,
children: < Widget > [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
child: TextField(
decoration: InputDecoration(
labelText: 'Question ${widget.index + 1}'
),
onChanged: (val) => q = val,
),
),
ListView(
shrinkWrap: true,
children: _items,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
child: FlatButton(onPressed: _add, child: Text("Add another answer"),
)
],
),
);
}
}
答案 0 :(得分:0)
您的删除方法应如下所示,
_remove(keyValue) {
setState(() {
_items = List.from(_items)..removeAt(keyValue);
--keyValue;
--_index;
});
}