更快地实施到列表中的方法?

Quicker way to implement into a list?

我正在制作一个单选按钮列表。但无法想出一种方法来映射它们。目前的方法一个一个制作太多了,而且有 10 个以上的单选按钮,这占用了数百行代码。

enum SingingCharacter {char1, char2, char3, char4}
class _HomeScreenState extends State<HomeScreen> {
  SingingCharacter _character = SingingCharacter.char1;

  final List myList= ['One','Two','Thre' ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Home'),
        ),
        body: Container(
          child: Column(children: <Widget>[
            RadioListTile<SingingCharacter>(
              title: Text('${myList[0]}'),
              value: SingingCharacter.char1,
              groupValue: _character,
              onChanged: (SingingCharacter value) {
                setState(() {
                  _character = value;
                });
              },
            ),
            RadioListTile<SingingCharacter>(
              title: Text('${myList[1]}'),
              value: SingingCharacter.char2,
              groupValue: _character,
              onChanged: (SingingCharacter value) {
                setState(() {
                  _character = value;
                });
              },
            )
            ....
          ]),
        ));
  }
}

有什么方法可以遍历它并显示在 children 中? 谢谢

您可以将 List 更改为 Map,然后使用它将您的枚举值映射到小部件。像这样(免责声明:代码未经测试,但这样的事情应该是可能的):

enum SingingCharacter {char1, char2, char3}

class _HomeScreenState extends State<HomeScreen> {
  SingingCharacter _character = SingingCharacter.char1;

  final Map<SingingCharacter, String> radioMap = {SingingCharacter.char1: 'One', SingingCharacter.char2: 'Two', SingingCharacter.char3: 'Three'};

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: Container(
        child: Column(
          children: _generateRadioButtons()
        ),
      )
    );
  }

  List<Widget> _generateRadioButtons() {
    return SingingCharacter.values.map((char) {
      return RadioListTile<SingingCharacter>(
        title: Text('${radioMap[char]}'),
        value: char
        groupValue: _character,
        onChanged: (SingingCharacter value) {
          setState(() {
            _character = value;
          });
        },
      );
    }).toList();
  }
}

您可以利用扩展运算符并在 Column 上直接展开 for 循环。

final List myList= ['One','Two','Thre' ];

    return Column(children: [
      for (int i = 0; i < myList.length; i++)
        RadioListTile<SingingCharacter>(
          title: Text(myList[i]),
          value: SingingCharacter.values[i],
          groupValue: _character,
          onChanged: (SingingCharacter value) {
            setState(() {
              _character = value;
            });
          },
        ),
    ]);