繁体   English   中英

如何在 flutter 中使用列表视图生成器制作动态单选按钮?

[英]how to make dynamic radio button with listview builder in flutter?

我想通过向学生提供出勤状态来使其像出勤一样。我创建的概念是一个带有名称数据的列表视图构建器,然后通过循环单选按钮的数量来进行行。 但是,我对这个问题感到很困惑

部分收音机

 Row( children: [ for(var i = 0; i < 2; i++) Radio<int>( value: i, groupValue: radioValue, activeColor: Colors.blueAccent, onChanged: handleRadioValueChanged ), ], ),

https://stackoverflow.com/questions/67385094/dynamically-create-radio-button-group-in-listview-builder-flutter

当我 select 是列表的一部分而不是其他部分时,我正在为上述代码使用 listview builder

在下面的代码中,我动态地展示了如何创建单选按钮列表。

使用以下代码,您可以为单选按钮创建独特的样式。

class RootPage extends StatefulWidget {
  const RootPage({Key key}) : super(key: key);

  @override
  State<RootPage> createState() => _RootPageState();
}

class _RootPageState extends State<RootPage> {
  List<RadioItem> items = <RadioItem>[];
  int groupValue = 0; 

  @override
  void initState() {
     for (int i = 0; i < 10; i++) {
       items.add(RadioItem(index: i, name: 'radio ' + i.toString()));
     }
     super.initState();
  }
  
  @override Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
      children: items
          .map(
            (data) => Card(
              elevation: 3,
              shadowColor: const Color(0xFFAAAAAA),
              margin: const EdgeInsets.only(left: 30, right: 30, top: 15),
              color: Colors.white,
              shape: RoundedRectangleBorder(
                side: const BorderSide(color: Colors.transparent, width: 0),
                borderRadius: BorderRadius.circular(20),
              ),
              child: InkWell(
                borderRadius: BorderRadius.circular(20),
                onTap: () {
                  setState(() {
                    groupValue = data.index;
                  });
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 10.0),
                  child: Directionality(
                    textDirection: TextDirection.rtl,
                    child: Row(
                      children: <Widget>[
                        Radio(
                          groupValue: groupValue,
                          value: data.index,
                          onChanged: (index) {
                            setState(() {
                              groupValue = index;
                            });
                          },
                        ),
                        Expanded(child: Text(data.name)),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          )
          .toList(),
       ),
    );
  }
}

然后添加以下class

class RadioItem {
  String name;
  int index;
  RadioItem({this.name, this.index});
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM