我正在构建一个小型 Flutter 程序,该程序显示包含已创建并输入类型 List 的任务信息的卡片。在主页上,任务列表上方有过滤选项,可按完成情况过滤任务。过滤选项有四种类型,其中 3 种在“Task”对象中具有相应的枚举值。我的问题在于访问这些值并仅显示具有与过滤器相对应的任务的卡片。我尝试了很多方法,其中我决定使用“List.where”创建一个单独的
filteredList
列表,其中包含与所选过滤器相对应的卡片;如果选择默认过滤器“所有任务”,则会显示所有卡片。任何帮助将不胜感激,因为我对 Flutter 还很陌生。
'home_page.dart' 当前包含我的大部分代码,并且当前在按下第 188 行创建的按钮时测试
statusText
的值,但是无论选择哪个过滤器,它总是返回“未启动”;我认为这是由于我错误地使用了 setState
,尽管我不确定当 setState 的另一个实例已经存在时如何实现这一点。
home_page.dart
class MyHomePage extends StatefulWidget {
static const routeName = '/home';
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
//Variable declaration
CompletionStatus statusType = "" as CompletionStatus;
Iterable<Task> filteredList = [];
class _MyHomePageState extends State<MyHomePage> {
String selectedFilter = "All tasks";
String statusText = "";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Task Management'),
centerTitle: true,
leading: const Icon(Icons.person),
),
body: Column(
children: [
FilterPills(onSelected: (value) {
setState(() {
if (selectedFilter != "All tasks") {
if (selectedFilter == "Not started") {
statusType = CompletionStatus.notStarted;
} else if (selectedFilter == "In progress") {
statusType = CompletionStatus.inProgress;
} else {
statusType = CompletionStatus.completed;
}
}
filteredList = taskList.where((task) {
return task.status == statusType;
});
});
}),
Expanded(
child: Container(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
width: double.maxFinite,
child: ListView.builder(
itemCount: taskList.length,
itemBuilder: ((context, index) {
final Task task = taskList.toList()[index];
if (task.status == CompletionStatus.notStarted) {
statusText = "Not started";
} else if (task.status == CompletionStatus.inProgress) {
statusText = "In progress";
} else if (task.status == CompletionStatus.completed) {
statusText = "Completed";
} else {
statusText = "Cancelled";
}
return Card(
//Code for the cards, with the button previously mentioned
//displayed below
child: TextButton(
style: ButtonStyle(
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(24.0),
side: const BorderSide(
color: Colors.black),
)),
),
//print statement for statusText
onPressed: () =>
// ignore: avoid_print
print(statusText),
),
)
],
),
)
],
),
)
],
),
]),
),
);
}),
),
),
),
],
),
);
}
}