【发布时间】:2021-07-05 16:37:07
【问题描述】:
所以我想要实现的是,使用ListView.builder,当用户点击特定的ListTile 项目时,它将打开一个AlertDialog 表单,在该表单的顶部,我想要显示一个Text 小部件,它将显示ListView.builder 的特定索引(在这种情况下,eventList list 内的String eventName)。
问题是,我不知道如何将该索引调用到ListView.builder 之外的文本小部件。
我正在努力实现的目标是可能的,还是有另一种方法可以做到这一点?
此外,如果它有帮助,当我尝试在文本小部件中传递索引时,我会收到错误“未定义的名称'索引'”。
关于我想要达到的目标的更多信息(请原谅我的笔迹): The AlertDialog Form
这是我的代码:
import 'package:flutter/material.dart';
import 'package:smc_app/Models/events.dart';
class EventsConfirmation extends StatefulWidget {
const EventsConfirmation({Key? key}) : super(key: key);
@override
_EventsConfirmationState createState() => _EventsConfirmationState();
}
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
List<EventList> schoolEvents = [
EventList(eventName: 'SMC General Assembly', location: 'College Gym', time: '9AM-11AM',),
EventList(eventName: 'College Finals Week', location: 'SMC', time: 'ALL DAY',),
EventList(eventName: 'College Baccalaureate and Graduation Day', location: 'TBA', time: 'TBA',),
EventList(eventName: 'Semester Break', location: 'N/A', time: 'N/A',),
];
class _EventsConfirmationState extends State<EventsConfirmation> {
Future<void> showInformationDialog(BuildContext context) async {
return await showDialog(context: context,
builder: (context){
return AlertDialog(
content: Form(
child: Column(
children: [
Text(schoolEvents[index].eventName), //HERE IS WHERE I'M HAVING PROBLEMS
TextFormField(
validator: (val) => val!.isEmpty ? 'This field is required' : null,
decoration: InputDecoration(hintText: "Name/Student ID"),
),
],
),
),
);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Upcoming Events, Confirm Your Attendance.'),
),
body: ListView.builder(
itemCount: schoolEvents.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 1.0, horizontal: 4.0),
child: Card(
child: InkWell(
child: ListTile(
onTap: () async {
await showInformationDialog(context);
},
title: Text(schoolEvents[index].eventName),
subtitle: Text(schoolEvents[index].location),
),
),
),
);
}
),
);
}
}
EventList 的类:
class EventList {
String eventName;
String location;
String time;
EventList({required this.eventName, required this.location, required this.time});
}
希望有人帮助我,谢谢。
【问题讨论】:
-
您需要将索引传递给
showInformationDialog()。这样的事情会起作用:将顶部的函数更改为Future<void> showInformationDialog(BuildContext context, int index),将 onTap 更改为await showInformationDialog(context,index);