将 ListView.builder 转换为单选 RadioListTile

在 Flutter 中,您可以使用 RadioListTile 组件将 ListView.builder 转换为单选列表。每个选项都将包裹在 RadioListTile 中,并使用 groupValueonChanged 属性来管理选择状态。

代码示例

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;
              });
            },
          );
        },
      ),
    );
  }
}

解释

  1. 定义 _selectedIndex 变量:State 类中定义一个名为 _selectedIndex 的变量,并将其初始值设置为 -1。该变量用于跟踪当前选中的选项索引。
  2. 使用 RadioListTile:ListView.builderitemBuilder 中,使用 RadioListTile 组件包裹每个选项。
  3. 设置 value 和 groupValue: value 属性设置为选项的索引,groupValue 属性设置为当前选中的索引 _selectedIndex
  4. 使用 onChanged: onChanged 属性是一个回调函数,当选项被选中时会触发。在这个回调函数中,将 _selectedIndex 设置为当前选中的索引,并使用 setState 刷新界面。

注意事项

  • RadioListTile 组件必须在同一 groupValue 下才能实现单选功能。
  • 如果需要在列表中显示复选框,可以使用 CheckboxListTile 组件。
  • 可以根据需求自定义 RadioListTile 组件的外观和样式。

通过以上步骤,您就可以将 ListView.builder 转换为单选 RadioListTile,并实现选项的选择和管理功能。

Flutter 中将 ListView.builder 转换为单选 RadioListTile

原文地址: https://www.cveoy.top/t/topic/lQrC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录