关于ListView.builder()颤动中的单选按钮 [英] About Radio Button in ListView.builder() flutter

查看:38
本文介绍了关于ListView.builder()颤动中的单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ListView.builder()中的单选按钮,但是当我选择任何一个单选按钮时,它将选择每个单选按钮,而不是选定的一个.

I am working on Radio Button in a ListView.builder() but when I select any of the radio button it is selecting each and every radio button rather than selected one.

我的代码如下:

ListView.builder(
                    itemCount: 67,
                    itemBuilder: (BuildContext context, int index) {
                      return _buildCheckListItems(index);
                    }),


Widget _buildCheckListItems(int index) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Text(
          'Seat Belts',
          style: TextStyle(fontSize: 17),
        ),
        Container(
          width: 200,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Radio(
                value: 1,
                groupValue: selectedRadio,
                activeColor: Colors.green,
                onChanged: (val) {
                  changeValue(val);
                },
              ),
              Radio(
                value: 2,
                groupValue: selectedRadio,
                activeColor: Colors.green,
                onChanged: (val) {
                  changeValue(val);
                },
              )
            ],
          ),
        ),
      ],
    );
  }


changeValue(int val) {
    setState(() {
      selectedRadio = val;
    });
  }

以上代码的输出结果如下:

The output result of above code is as follow:

输出结果

推荐答案

此处的关键点是您使用相同的 groupValue:selectedRadio 每个单选按钮组必须具有不同的 groupValue,否则它将共享相同的更改.

The key point here is that you are using a same groupValue: selectedRadio, Each radio button group must have different groupValue otherwise it will shared the same change.

如果您不想为每个单选按钮组指定名称,则可以创建一个新的.dart文件:

If you do not want to specify name for each radio button group you can just create a new .dart file:

import 'package:flutter/material.dart';

class buildCheckListItems extends StatefulWidget {
  final int index;
  buildCheckListItems(this.index); //I don't know what is this index for but I will put it in anyway
  @override
  _buildCheckListItemsState createState() => _buildCheckListItemsState();
}

class _buildCheckListItemsState extends State<buildCheckListItems> {
  int selectedRadio = -1;

  changeValue(int val) {
    setState(() {
      selectedRadio = val;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        ...
      ],
    );
  }
}

现在一切都应该正常了.

and now everything should be working just fine.

这篇关于关于ListView.builder()颤动中的单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆