如何在Flutter中仅选择单选按钮的一组值?

2023-12-28

我正在使用 Flutter-Dart-SQLite 开发测验应用程序。在这里,我使用 RadioListTile 来实现单选按钮功能。我将文本值从数组传递到此StatefulWidget。 这是我正在使用的代码,

    import 'package:flutter/material.dart';
    import 'package:get/get_state_manager/get_state_manager.dart';
    import 'package:loginform_validation_demo/QuizApp/controllers/question_controller.dart';
    import 'package:loginform_validation_demo/resource-file/constants.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    import 'package:flutter/src/material/radio_list_tile.dart';

    class OptionRadio extends StatefulWidget {
      final String text;
      final int index;
      final VoidCallback press;

      const OptionRadio({
        Key key,
        this.text,
        this.index,
        this.press,
      }) : super();

      @override
      OptionRadioPage createState() =>
          OptionRadioPage(this.text, this.index, this.press);
    }

    class OptionRadioPage extends State<OptionRadio> {
      final String text;
      int index;
      final VoidCallback press;
      QuestionController controllerCopy =QuestionController();

      int id = 1;
      int selectedButton = null;
      bool _isButtonDisabled;

      OptionRadioPage(this.text, this.index, this.press);

      @override
      void initState() {
        _isButtonDisabled = false;
      }

      int _selected = null;

      @override
      Widget build(BuildContext context) {
        return GetBuilder<QuestionController>(
            init: QuestionController(),
            builder: (qnController) {
              Color getTheRightColor() {
                if (qnController.isAnswered) {
                  if (index == qnController.selectedAns &&
                      qnController.selectedAns == qnController.correctAns) {

                    return kBlackColor;
                  } else if (index == qnController.selectedAns &&
                      qnController.selectedAns != qnController.correctAns) {
                    return kBlackColor;
                  }

                }
                return kBlackColor;
              }

              return InkWell(
                onTap: press,
                child: Container(
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Container(
                            // height: 60.0,
                            child: Theme(
                              data: Theme.of(context).copyWith(
                                  unselectedWidgetColor: Colors.grey,
                                  disabledColor: Colors.blue),
                              child: Column(children:
                              [
                                RadioListTile(
                                  title: Text(
                                    "${index + 1}. $text",
                                    style: TextStyle(
                                        color: getTheRightColor(), fontSize: 16),
                                    softWrap: true,
                                  ),
                                  /*Here the selectedButton which is null initially takes place of value after onChanged. Now, I need to clear the selected button when other button is clicked */
                                  groupValue: selectedButton,
                                  value: index,
                                  activeColor: Colors.green,
                                  onChanged:
                                      (val) async {

                                    debugPrint(
                                        'Radio button is clicked onChanged $val');
                                    setState(() {
                                      debugPrint('Radio button setState $val');
                                      selectedButton = val;
                                      debugPrint('Radio button is clicked onChanged $index');
                                    
                                    });
                                    SharedPreferences prefs = await SharedPreferences.getInstance();
                                    prefs.setInt('intValue', val);
                                  },
                                  toggleable: true,
                                ),
                              ]
                              ),
                            )),
                      ),
                    ],
                  ),
                ),
              );
            });
      }

      @override
      State<StatefulWidget> createState() {
        throw UnimplementedError();
      }
    }

这里,最初为 null 的 selectedButton 取代了之后的组值的值onChanged。现在,我需要在单击另一个按钮时清除所选按钮。

我猜我在团体价值部分做错了什么。

我使用OptionRadio的部分,

class QuestionCardWidgetRadio extends StatelessWidget {
  OptionRadio optionRadio = OptionRadio();
  QuestionCardWidgetRadio({
    Key key,
    this.note,
    this.index,
    this.questionLength,
  }) : super(key: key);

  final BlazorQuiz note;
  final int index;
  final int questionLength;
  bool _isAnswered = false;
  bool get isAnswered => this._isAnswered;
  int selectedButton;

  @override
  Widget build(BuildContext context) {
    QuestionController _questionController =
        Get.put(QuestionController());
    debugPrint("Answer Print : ${note.Answer.split(",")}");
    return Container(
        margin: EdgeInsets.symmetric(horizontal: kDefaultPadding, vertical: 35),
        decoration: BoxDecoration(
          color: Colors.white,
        borderRadius: BorderRadius.circular(25),
        ),
        padding: EdgeInsets.all(kDefaultPadding),
    child: SingleChildScrollView(
    scrollDirection: Axis.vertical,
        child: Column(
          children: [
            ...List.generate(
              note.Answer.split(",").length,
              (index) => OptionRadio(
                index: index,
                text: note.Answer.split(",")[index],
                press: (val) => setState(() {
                  selectedButton = int.parse(val.toString());
                  print("$selectedButton");
                }),
                selectedButton: selectedButton,
                // press:
                //       () =>{
                //   _isAnswered = true,
                //   _questionController.checkAns(note, index),
                //     selectedButton,
                // }
              ),

            SingleChildScrollView(
              scrollDirection: Axis.vertical,
              child: TextButton(
                onPressed: () async {
                  debugPrint("Clicked options : ${note.Answer.isNotEmpty} isAnswered: $isAnswered");
                  debugPrint('Check Index : ${index} check quiz model Lenght : ${QuizModel.question.length} check note Id : ${note.Id}');
                  if(index+1 == questionLength){
                    // score screen
                    debugPrint('Navigate to score screen');
                    Text(
                      "Submit",
                      style: Theme.of(context)
                          .textTheme
                          .button
                          .copyWith(color: Colors.white),
                    );
                    _questionController.scoreNavigation(index, context);
                  }
                  else{
                    if (note.Answer.isNotEmpty == !isAnswered) {
                      debugPrint('Clicked RadioBtn ${optionRadio.index}');
                      SharedPreferences prefs = await SharedPreferences.getInstance();
                      //Return int
                      int intValue = prefs.getInt('intValue');
                      debugPrint('Int value from sharedPrefs: $intValue');
                      _questionController.nextQuestion(note,intValue,"","",[]);
                      prefs.remove("intValue");
                    }else{
                      debugPrint('Click proper option for Radio');
                    }
                  }
                },

                child: Container(
                  width: double.infinity,
                  alignment: Alignment.center,
                  padding: EdgeInsets.all(kDefaultPadding * 0.75),
                  margin: EdgeInsets.all(37),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                      color: Color(ColorData.button)
                  ),
                  child: Text(
                    "Next Question",
                    style: Theme.of(context)
                        .textTheme
                        .button
                        .copyWith(color: Colors.white),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  setState(Null Function() param0) {}
}

我从数组中获取值,其中选项以逗号分隔。 “答案”:“男、女”


Here is sample code by using your 'OptionRadioPage' Widget.
(but some code deleted because of leak of code)
As I commented, 'groupValue' should shared with two 'OptionRadioPage' widgets.
So I store that value 'OptionRadioPage' parent widget and
also pass the that value to 'OptionRadioPage' widgets.
enter image description here

import 'package:flutter/material.dart';
import 'package:flutter/src/material/radio_list_tile.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Main(),
    );
  }
}

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

  @override
  _MainState createState() => _MainState();
}

class _MainState extends State<Main> {
  int selectedButton;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            OptionRadio(
                text: 'Male',
                index: 0,
                selectedButton: selectedButton,
                press: (val) {
                  selectedButton = val;
                  setState(() {});
                }),
            OptionRadio(
                text: 'Female',
                index: 1,
                selectedButton: selectedButton,
                press: (val) {
                  selectedButton = val;
                  setState(() {});
                }),
          ],
        ),
      ),
    );
  }
}

class OptionRadio extends StatefulWidget {
  final String text;
  final int index;
  final int selectedButton;
  final Function press;

  const OptionRadio({
    Key key,
    this.text,
    this.index,
    this.selectedButton,
    this.press,
  }) : super();

  @override
  OptionRadioPage createState() => OptionRadioPage();
}

class OptionRadioPage extends State<OptionRadio> {
  // QuestionController controllerCopy =QuestionController();

  int id = 1;
  bool _isButtonDisabled;

  OptionRadioPage();

  @override
  void initState() {
    _isButtonDisabled = false;
  }

  int _selected = null;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        widget.press(widget.index);
      },
      child: Container(
        child: Row(
          children: <Widget>[
            Expanded(
              child: Container(
                  // height: 60.0,
                  child: Theme(
                data: Theme.of(context).copyWith(
                    unselectedWidgetColor: Colors.grey,
                    disabledColor: Colors.blue),
                child: Column(children: [
                  RadioListTile(
                    title: Text(
                      "${widget.index + 1}. ${widget.text}",
                      style: TextStyle(color: Colors.black, fontSize: 16),
                      softWrap: true,
                    ),
                    /*Here the selectedButton which is null initially takes place of value after onChanged. Now, I need to clear the selected button when other button is clicked */
                    groupValue: widget.selectedButton,
                    value: widget.index,
                    activeColor: Colors.green,
                    onChanged: (val) async {
                      debugPrint('Radio button is clicked onChanged $val');
                      // setState(() {
                      //   debugPrint('Radio button setState $val');
                      //   selectedButton = val;
                      //   debugPrint('Radio button is clicked onChanged $widget.index');
                      // });
                      // SharedPreferences prefs = await SharedPreferences.getInstance();
                      // prefs.setInt('intValue', val);
                      widget.press(widget.index);
                    },
                    toggleable: true,
                  ),
                ]),
              )),
            ),
          ],
        ),
      ),
    );
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Flutter中仅选择单选按钮的一组值? 的相关文章

随机推荐

  • 如何在玻璃上获得可读的文本(wpf)

    这是两个屏幕截图 白色背景上的全玻璃窗 http trotsenko com ua stackoverflow 2010 01 13 20Glass 20Window 20over 20a 20white 20background png
  • openAi-gym 名称错误

    我正在尝试在 WSL 上使用 OpenAI 著名的 Gym 模块并在 python 3 5 2 上执行代码 当我尝试运行环境时正如这里所解释的 https gym openai com docs 使用代码 import gym env gy
  • 是什么导致了这个“关闭句柄延迟读取”错误?

    我刚刚从最新的源安装了 GHC 现在我的程序给了我一条关于 关闭句柄延迟读取 的错误消息 这是什么意思 基本的惰性 I O 原语 hGetContents 产生一个String惰性地 它只根据需要从句柄中读取 以生成程序实际需要的字符串部分
  • 使用 Jquery 过滤表行

    我发现一个 Jquery 脚本可以根据输入字段进行表过滤 该脚本基本上采用过滤器 分割每个单词并使用每个单词过滤表行 因此 最后您将得到一个包含输入字段中所有单词的行列表 http www marceble com 2010 02 simp
  • Boost Graph Library - 有向图的最小生成树

    我有一个问题 要求我在 Boost Graph Library 中找到有向图的最小生成树 我的第一次尝试是使用深度优先搜索和 DFS 访问者 我的计划是忽略除树边回调之外的所有边 这是行不通的 我用下面的例子来说明原因 我的问题是我是否可以
  • 在 Scala Spark 中加入不同 Dataframe 时动态选择多个列

    我有两个 Spark 数据框df1 and df2 有没有办法在连接这两个数据帧时动态选择输出列 以下定义在内部联接的情况下输出 df1 和 df2 中的所有列 def joinDF df1 DataFrame df2 DataFrame
  • Doctrine2...最佳补水模式?

    我正在设计一个房间预订系统 它有九个实体 它们都相互关联 在此特定实例中 我从实体中检索 10 30 行entry其中有 25 个属性 每个条目都有一个room其中有 10 个属性 我需要所有的条目信息以及entry gt room gt
  • 来自 Maven 的 Java OpenCV

    有没有办法从存储库获取 OpenCV 我应该添加到哪个工件pom xml 我找到的每个教程都是从 14 年开始的 似乎有些东西发生了变化 他们说它还没有出现在官方 Maven 存储库中 但我找到了条目
  • 创建使用 .NET 4.0 的应用程序池

    我使用以下代码创建应用程序池 var metabasePath string Format IIS 0 W3SVC AppPools serverName DirectoryEntry newpool DirectoryEntry appp
  • 上传到谷歌云存储时转换音频文件

    我有一个应用程序 用户可以在其中录制音频 然后相互 发送 我写的是 发送 因为实际上文件存储在服务器上 并且只是在收件人想要收听时提供给他们 我的问题是 我需要将录音 当前为 caf 重新格式化为 mp3 这样它们就会更小 这样我就可以用我
  • MySQL 的 C++ 连接器

    EDITED 我的问题是这篇文章底部的错误 这是我的附加包含目录 C Program Files boost C Program Files MySQL MySQL Connector C 1 1 3 include C Program F
  • 对未使用的变量使用占位符时出现 MatchError

    使用 Scala 2 13 x 我得到scala MatchError null当我对未使用的变量使用占位符时 scala gt object Test val Any null object Test scala gt Test scal
  • 如何在 Linux 中获取 .Net 文件的 AssemblyVersion

    有没有办法在不使用 mono 的情况下在 Linux 中获取 Net 可执行文件的 AssemblyVersion 我想要的是一个脚本或命令 可以让我在 Linux 机器上获取 AssemblyVersion 我试过 strings fil
  • 我的 NgRx 效果不起作用,没有任何反应

    我的 NgRx 效果有问题 该应用程序正确地添加到商店 不幸的是我的请求效果没有执行 即在启动添加新车时 将其添加到商店 仅此而已 问题是我的效果没有控制台日志 没有由于错误的网址而导致的 http 错误 什么也没有 我的应用程序代码 Re
  • Android textview 用作标签和值

    我想将两个文本视图分组为一个组并使用标签和值 android中是否有任何组件可以将两个textview分组 在android布局中如何实现呢 您可以使用
  • 节点拒绝应用样式,因为其 MIME 类型('text/html')不是受支持的样式表 MIME

    我要提供静态服务index html with main css使用此节点服务器 该serve js var express require express var cors require cors var app express var
  • RuntimeError:只能计算浮点类型的平均值。取而代之的是字节。对于平均值 += images_data.mean(2).sum(0)

    我有以下代码 Device configuration device torch device cuda 0 if torch cuda is available else cpu seed 42 np random seed seed t
  • 显示所有 jinja 对象属性

    有没有办法在 jinja 模板中显示给定对象的所有属性的名称 内容 功能 这将使调试未按预期运行的模板变得更加容易 我正在使用以下方式建立一个网站hyde框架 这会非常方便 因为我仍在学习 jinja 和 hyde 的复杂性 最初 我以为使
  • c 中的快速模 10

    我正在寻找一种快速的模 10 算法 因为我需要加速我的程序 该程序在循环中执行许多模运算 我已经结帐了这一页 http cc davelozinski com c sharp use the modulus operator or alte
  • 如何在Flutter中仅选择单选按钮的一组值?

    我正在使用 Flutter Dart SQLite 开发测验应用程序 在这里 我使用 RadioListTile 来实现单选按钮功能 我将文本值从数组传递到此StatefulWidget 这是我正在使用的代码 import package