Flutter 中将 ListView.builder 转换为单选 RadioListTile
将 ListView.builder 转换为单选 RadioListTile
在 Flutter 中,您可以使用 RadioListTile 组件将 ListView.builder 转换为单选列表。每个选项都将包裹在 RadioListTile 中,并使用 groupValue 和 onChanged 属性来管理选择状态。
代码示例
import 'package:flutter/material.dart';
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
int _selectedIndex = -1;
final List<Map<String, String>> _filteredStringList = [
{"act": "选项 1", "prompt": "年龄 1"},
{"act": "选项 2", "prompt": "年龄 2"},
{"act": "选项 3", "prompt": "年龄 3"},
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: _filteredStringList.length,
itemBuilder: (BuildContext context, int index) {
String name = _filteredStringList[index]['act'];
String age = _filteredStringList[index]['prompt'];
return RadioListTile(
title: Text(name),
subtitle: Text('Age: $age'),
value: index,
groupValue: _selectedIndex,
onChanged: (int value) {
setState(() {
_selectedIndex = value;
});
},
);
},
),
);
}
}
解释
- 定义 _selectedIndex 变量: 在
State类中定义一个名为_selectedIndex的变量,并将其初始值设置为 -1。该变量用于跟踪当前选中的选项索引。 - 使用 RadioListTile: 在
ListView.builder的itemBuilder中,使用RadioListTile组件包裹每个选项。 - 设置 value 和 groupValue:
value属性设置为选项的索引,groupValue属性设置为当前选中的索引_selectedIndex。 - 使用 onChanged:
onChanged属性是一个回调函数,当选项被选中时会触发。在这个回调函数中,将_selectedIndex设置为当前选中的索引,并使用setState刷新界面。
注意事项
RadioListTile组件必须在同一groupValue下才能实现单选功能。- 如果需要在列表中显示复选框,可以使用
CheckboxListTile组件。 - 可以根据需求自定义
RadioListTile组件的外观和样式。
通过以上步骤,您就可以将 ListView.builder 转换为单选 RadioListTile,并实现选项的选择和管理功能。
原文地址: https://www.cveoy.top/t/topic/lQrC 著作权归作者所有。请勿转载和采集!