如何制作单选列表

How to make a list with single selection

目前,我正在尝试更深入地学习状态管理。我正在尝试通过单一选择实现一个列表。这是我到目前为止所做的。这就是 UI 的样子。

class AccountCategory extends StatefulWidget {

  bool isSelected = false;

  @override
  State<AccountCategory> createState() => _AccountCategoryState();
}

class _AccountCategoryState extends State<AccountCategory> {
  @override
  Widget build(BuildContext context) {
    return Column( 
      children: const <Widget>[ 
        Card( 
          child: ListTile( 
            title: Text('Akaun Individu', style: TextStyle(fontWeight: FontWeight.bold),), 
            subtitle: Text('Membuat pembayaran untuk diri sendiri'),
            trailing: Icon(Icons.more_horiz),

            )
          ),
        
        Card(child: ListTile( 
            title: Text('Akaun Syarikat', style: TextStyle(fontWeight: FontWeight.bold)), 
            subtitle: Text('Membuat pembayaran untuk organisasi'),
            trailing: Icon(Icons.more_vert),
          ),)
      ],
      
    );
  }
}

你可以像这样使用 onTap 和 setState,如果你想构建一个包含很多项目的列表,你应该使用 ListView.builder 并通过索引更改 _isSelected 并检查索引是否正确

class AccountCategory extends StatefulWidget {
      bool isSelected = false;
    
      @override
      State<AccountCategory> createState() => _AccountCategoryState();
    }
    
    class _AccountCategoryState extends State<AccountCategory> {
      late bool _isSelected;
    
      @override
      void initState() {
        super.initState();
        _isSelected = widget.isSelected;
      }
    
      @override
      Widget build(BuildContext context) {
        return Column(
          children: <Widget>[
            InkWell(
              onTap: () {
                setState(() {
                  _isSelected = true;
                });
              },
              child: Card(
                  child: ListTile(
                title: Text(
                  'Akaun Individu',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                subtitle: Text('Membuat pembayaran untuk diri sendiri'),
                trailing: _isSelected ? const Icon(Icons.check_circle) : const Icon(Icons.circle),
              )),
            ),
            InkWell(
              onTap: () {
                setState(() {
                  _isSelected = false;
                });
              },
              child: Card(
                child: ListTile(
                  title: Text('Akaun Syarikat', style: TextStyle(fontWeight: FontWeight.bold)),
                  subtitle: Text('Membuat pembayaran untuk organisasi'),
                  trailing: !_isSelected ? const Icon(Icons.check_circle) : const Icon(Icons.circle),
                ),
              ),
            )
          ],
        );
      }
    }

使用 listView 或 gridView 生成器,添加一个 onTap 事件,调用一个将项目索引作为参数的函数,return 随心所欲地使用该函数。但是,如果您有一个有限列表,请自己指定索引

简单的方法是将所选项目的 index 存储在 list 中,这样您就可以知道选择了什么项目并更改列表需要的时候。