问题描述
在我的项目中,用户可以添加和编辑列表项。问题是,如果用户添加一个已经存在的 List 名称的 List 项目,旧的将被覆盖,并出现错误“多个小部件使用相同的 GlobalKey”。如何避免这种情况,以便用户可以添加多个同名项目?
import 'package:Flutter/material.dart';
class PlanOverview extends StatefulWidget {
const PlanOverview({Key key}) : super(key: key);
@override
_PlanOverviewState createState() => _PlanOverviewState();
}
class _PlanOverviewState extends State<PlanOverview> {
List<String> plans = ['Plan A','Plan B'];
void addplan(String newPlan) {
setState(() {
plans.add(newPlan);
});
Navigator.of(context).pop();
}
void newEntry() {
showDialog(
context: context,builder: (BuildContext context) {
return AlertDialog(
content: TextField(
onSubmitted: addplan,decoration: Inputdecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),icon: Icon(Icons.text_snippet_outlined),labelText: 'Name des Plans'),),);
});
}
void edit(int i) => showDialog(
context: context,builder: (context) {
final plan = plans[i];
return AlertDialog(
content: TextFormField(
decoration: Inputdecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),icon: Icon(Icons.text_snippet_outlined)),initialValue: plan,onFieldSubmitted: (_) => Navigator.of(context).pop(),onChanged: (name) => setState(
() {
plans[i] = name;
},)));
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Trainingspläne'),shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.only(bottomLeft: Radius.circular(10.0),bottomright: Radius.circular(10.0)),actions: [
IconButton(
onpressed: newEntry,icon: Icon(Icons.add),],body: ReorderableListView.builder(
itemCount: plans.length,onReorder: (oldi,newi) => setState(() {
final i = newi > oldi ? newi - 1 : newi;
final plan = plans.removeAt(oldi);
plans.insert(i,plan);
}),itemBuilder: (context,i) {
final plan = plans[i];
return ListTile(
tileColor: Color.fromARGB(255,34,34),key: ValueKey(plan),contentPadding: EdgeInsets.symmetric(horizontal: 20,vertical: 5),title: Text(plans[i]),onTap: () {
Navigator.push<Widget>(
context,MaterialPageRoute(
builder: (context) =>
ExerciseTable(key: GlobalKey(),title: plans[i])));
},trailing: IconButton(
icon: Icon(Icons.edit),onpressed: () {
edit(i);
}),);
}),);
}
}
解决方法
当用户创建一个元素并将其添加到列表中时,您可以检查列表中是否存在同名元素,如果存在,则将其索引添加到其名称中,这样就不能有两个同名元素.
如果您不想,您不需要向用户显示名称的索引部分,这只是为了控制目的。
如果您有一个搜索栏,用户可以在其中键入他想要访问的元素的名称,您可以使用自动完成功能来显示包含用户正在键入的内容的元素。