Сброс списка радио в флаттере - PullRequest
0 голосов
/ 21 февраля 2020

Я все еще новичок с флаттером и сейчас работаю над приложением для викторины. В списке переключателей, когда приложение переходит к следующему вопросу, переключатели не сбрасываются, и я буду признателен, если кто-то может мне помочь как я могу сбросить переключатель при вызове функции следующего вопроса

Псевдокод

class _QuizPageState extends State<QuizPage> {
  List<dynamic> myQuestion;
  _QuizPageState(this.myQuestion);
  int i = 0;
  int count = 0;
  int selectedRadioTile;
  int marks = 0;
  var selected;

  Widget choiceButton(String k, int value) {
    return Padding(
      padding: EdgeInsets.symmetric(
        vertical: 10,
      ),
      child: RadioListTile(
        value: value,
        groupValue: selectedRadioTile,
        title: Container(
          child: Text(myQuestion[i][k] ?? "None"),
        ),
        onChanged: (val) {
          setSelectedRadioTile(val);
          selected = val;
        },
        activeColor: Colors.green,
        selected: true,
      ),
    );
  }

  void initState() {
    selectedRadioTile = 0;
    super.initState();
  }

  setSelectedRadioTile(int val) {
    setState(() {
      selectedRadioTile = val;
    });
  }

  void checkAnswer() {
    var e = int.parse(myQuestion[i]["Answer"]);
    if (e == selected) {
      marks = marks + 1;
    } else {
      print("wrong");
    }
    nextquestion();
  }

  void nextquestion() {



    setState(() {
      if (count < 9) {
        i = randomBetween(0, myQuestion.length);
      } else {
        Navigator.of(context).pushReplacement(MaterialPageRoute(
          builder: (context) => resultpage(marks: marks),
        ));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        return showDialog(
            context: context,
            builder: (context) => AlertDialog(
                  title: Text(
                    "Alert",
                  ),
                  content: Text("You Can't Go Back At This Stage."),
                  actions: <Widget>[
                    FlatButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                      child: Text(
                        'Ok',
                      ),
                    )
                  ],
                ));
      },
      child: Scaffold(
        appBar: AppBar(
          elevation: 30.0,
          title: Center(
            child: Text(
              'Quiz',
              style: TextStyle(
                color: Colors.white,
                fontSize: 20.0,
                fontFamily: "Quando",
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          backgroundColor: Colors.amber[800],
        ),
        body: LayoutBuilder(
          builder: (context, constraint) {
            return SingleChildScrollView(
              child: ConstrainedBox(
                constraints: BoxConstraints(minHeight: constraint.maxHeight),
                child: IntrinsicHeight(
                  child: Column(
                    children: <Widget>[
                      Expanded(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            Center(
                              child: Container(
                                padding: EdgeInsets.only(top: 20, left: 10),
                                child: Text(
                                  myQuestion[i]["Question"] ?? "None",
                                  style: TextStyle(
                                    fontSize: 15.0,
                                    fontFamily: "Quando",
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            ),
                            SizedBox(
                              height: 20,
                            ),
                            Expanded(
                              child: AspectRatio(
                                aspectRatio: 16 / 11,
                                child: ClipRect(
                                  child: SizedBox(
                                    height: 50,
                                    child: PhotoView(
                                      imageProvider: AssetImage(
                                          myQuestion[i]["Image"] ?? "None"),
                                      minScale:
                                      PhotoViewComputedScale.contained *
                                          0.5,
                                      maxScale:
                                      PhotoViewComputedScale.covered * 2,
                                      initialScale: 0.6,
                                      backgroundDecoration: BoxDecoration(
                                        color: Theme.of(context).canvasColor,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                            Text(
                              "To adjust the image double Tap",
                              style: TextStyle(
                                fontFamily: "Quando",
                                color: Colors.black26,
                                fontSize: 15.0,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Expanded(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            choiceButton("option1", 1),
                            choiceButton("option2", 2),
                            choiceButton("option3", 3),
                            choiceButton("option4", 4),
                          ],
                        ),
                      ),
                      Expanded(
                        flex: 0,
                        child: RaisedButton(
                          splashColor: Colors.blueAccent,
                          color: Colors.blueAccent,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(50.0),
                          ),
                          onPressed: () {
                            checkAnswer();
                            count = count + 1;
                            showDialog(
                                context: context,
                                builder: (context) => AlertDialog(
                                      title: Text(
                                        "Explaination",
                                      ),
                                      content: Text(
                                        myQuestion[i]["Explanation"] ?? "None",
                                        style: TextStyle(
                                          fontSize: 15.0,
                                          fontFamily: "Quando",
                                        ),
                                      ),
                                      actions: <Widget>[
                                        FlatButton(
                                          onPressed: () {
                                            Navigator.of(context).pop();
                                          },
                                          child: Text(
                                            'Ok',
                                          ),
                                        )
                                      ],
                                    ));
                          },
                          child: Text(
                            'Submit',
                          ),
                        ),
                      ),
                      SizedBox(
                        height: 40,
                      )
                    ],
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}

1 Ответ

1 голос
/ 21 февраля 2020

Вы можете просто установить selectedRadioTile на 0 в следующем вопросе:

  void nextquestion() {
    setState(() {
      selectedRadioTile = 0;
      if (count < 9) {
        i = randomBetween(0, myQuestion.length);
      } else {
        Navigator.of(context).pushReplacement(MaterialPageRoute(
          builder: (context) => resultpage(marks: marks),
        ));
      }
    });
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...