listView中的组单选按钮 [英] Group radio button in listView

查看:126
本文介绍了listView中的组单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在listView中使用组按钮?在每一行中,都有两个单选按钮. 现在的问题是,如果我选择了单选按钮之一,则未显示单选按钮的状态也被选中.

How to use group button in listView ? In each row, it has two radio button. The problem now is if I select one of the radio button , the radio button not showing it is selected.

      int value;
      Map<int, bool> answers = {};
      String _radioValue;
      String choice;
      int count = 0;
      
    ...item['questions']
                                      .asMap()
                                      .entries
                                      .map((items) {
                                    count++;
                                    return TableRow(children: [
                                      Padding(
                                          padding: EdgeInsets.all(10),
                                          child: Text(items.value['name'])),
                                      Row(
                                        children: [
                                          Radio(
                                            value: items.value['id'],
                                            groupValue: count,
                                            onChanged: (val) {
                                              setSelectedRadioTile(val);
                                            },
                                          ),
                                          Text("Yes"),
                                          Radio(
                                            value: items.value['id'] + count,
                                            groupValue: count,
                                            onChanged: (val) {
                                              setSelectedRadioTile(val);
                                            },
                                          ),
                                          Text("N/A")
                                        ],
                                      )
                                    ]);
                                  }).toList()

 setSelectedRadioTile(int val) {
    print(val);
    setState(() {
      count = val;
    });
  }

推荐答案

好的,我已经根据您在此处提供的内容为您构建了一个有效的版本.请记住,更深入地阅读文档可能是一个好主意,以便您了解某些小部件的行为以及特定属性(例如groupValue)的用途.还请记住,以下代码并未经过优化,无论如何,我只是为您的案例解决了这些问题-考虑如何总体构建数据是您应该研究的一些基本知识.也许尝试一些可用的flutter课程,或者查看来自已知flutter编码器的一些youtube内容.现在回到一些代码方面.

Okay well I have built you a working version based on what you provided here. Please keep in mind that it would probably be a good idea to look at the documentation more in-depth so you get a feeling of how some widgets behave and what specific properties (like groupValue) are for. Also keep in mind that the following code is not optimised or whatsoever, I just got it worked out for your case - thinking about how to structure your data overall is some fundamental thing you should take a look at. Maybe try some out some flutter courses which are available or look at some youtube content from known flutter coders. But now back to some code stuff.

我在StatefulWidget中使用了这些属性.由于您使用了某种问题图,而且我不知道它的外观,所以我只用了一些裸露的东西:

I used those properties in my StatefulWidget to work with. Since you use some kind of question map and I don't know how it looks like, I just used something bare bones:

/// Map which has the question ID as its key and the answer from the user (currently true for yes and false for no (or n/a as in your case)
Map<int, bool> _answers = {};

/// Map which holds the information of your questions. Right now only an ID to be able to reference it and the actual question - again very bare bones
Map<String, dynamic> _item = {
  'questions': [
     {
      'id': 0,
      'question': 'Is this legit?',
    },
    {
      'id': 1,
      'question': 'Oh really?',
    },
  ]
};

然后触发onChanged时将由Radio小部件调用的方法:

Then the method which will be called by the Radio widget once onChanged is triggered:

/// We need to know which question has been answered (therefore the ID) and which (bool) answer has been clicked by the user
_setSelectedRadioTile(int id, bool answer) {
  setState(() {
    _answers[id] = answer;
  });
}

现在是小部件部分-由于您的代码从您遍历问题的地方开始,因此我也专门分享此部分:

And now the widget part - since your code starts where you iterate over the questions, I also share this part specifically:

/// Since the map itself is typed as <String, dynamic>, accessing 'questions' will return dynamic. Only we, as we know the structure, know that this is indeed a list. Therefore we need to cast this as "List<dynamic>" so we can iterate over it and won't get exceptions
(_item['questions'] as List<dynamic>)
.map(
  (question) => TableRow(children: [
    Padding(
        padding: EdgeInsets.all(10),
        child: Text(question['question'])),
    Row(
      children: [
        Radio(
          /// The [value] property of Radio tells us, which property is used in [onChanged] - therefore now once this Radio is clicked, true is provided in the [onChanged] callback 
          value: true,
          /// [groupValue] is the value which this Radio is bound to. As you probably know, only one Radio button should be active for a group. So if you have a question which has several possible answers as radio buttons, we only want one of them to be active at a time. Thats what the [groupValue] is for. Since we iterate over all questions and every entity of a question (currently) has two possible answers (Yes and N/A), both those answers are for a specific question - the question with the current ID
          groupValue: _answers[question['id']],
          onChanged: (answer) {
            _setSelectedRadioTile(question['id'], answer);
          },
        ),
        Text("Yes"),
        Radio(
          value: false,
          groupValue: _answers[question['id']],
          onChanged: (answer) {
            _setSelectedRadioTile(question['id'], answer);
          },
        ),
        Text("N/A")
      ],
    )
  ]),
)
.toList(),

在更新了此示例以使其适合数据模型后,这应该对您有利.再说一次:我建议您考虑一下数据的总体结构.

This should work on your side once you updated this example to fit with your data model. Again: I advise you to think about how you structure your data generally.

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

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