Обновление родительской формы из дочерней с помощью радио - PullRequest
0 голосов
/ 10 июля 2020

Я разрабатываю форму с 11 вопросами с множественным выбором.

Я создал виджет с полным состоянием, который принимает вопрос и отображает его вместе с 3 переключателями, как показано ниже.

Каждый вопрос должен быть обновить другое свойство в модели, определенной в родительском виджете.

например:

RadioQuestionWidget("What colour is the sky?", model.ColourOfSky),
RadioQuestionWidget("What colour is the grass?", model.ColourOfGrass)

Ниже мой RadioQuestionWidget

import 'package:flutter/material.dart';

class RadioQuestionWidget extends StatefulWidget {
  RadioQuestionWidget({Key key, this.question}) : super(key: key);
  final String question;

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

class _RadioQuestionWidgetState extends State<RadioQuestionWidget> {
  String question;
  var _radioValue;

  @override
  void initState() {
    super.initState();
    question = widget.question;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          new Text(
            question,
            style: new TextStyle(
                fontSize: 16.0,
                color: Colors.black,
                fontWeight: FontWeight.bold),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              children: <Widget>[
                Radio(
                  value: "Yes",
                  groupValue: _radioValue,
                  onChanged: (val) {
                    setState(() {
                      _radioValue = val;
                    });
                  },
                  activeColor: Colors.green,
                  focusColor: Colors.black,
                ),
                new Text(
                  'Yes',
                  style: new TextStyle(fontSize: 16.0, color: Colors.black),
                ),
                Radio(
                  value: "No",
                  groupValue: _radioValue,
                  onChanged: (val) {
                    setState(() {
                      _radioValue = val;
                    });
                  },
                  activeColor: Colors.green,
                  focusColor: Colors.black,
                ),
                new Text(
                  'No',
                  style: new TextStyle(fontSize: 16.0, color: Colors.black),
                ),
                Radio(
                  value: "Three",
                  groupValue: _radioValue,
                  onChanged: (val) {
                    setState(() {
                      _radioValue = val;
                    });
                  },
                  activeColor: Colors.red,
                  focusColor: Colors.black,
                ),
                new Text(
                  'Not applicable',
                  style: new TextStyle(fontSize: 16.0, color: Colors.black),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

Ответы [ 2 ]

1 голос
/ 10 июля 2020

Прежде всего, определите одну функцию в родительском виджете с обязательными аргументами, то есть с номером вашего вопроса и ответом.

void _updateProperty(int que_num, String ans) {
    //update property according to your question number and ans
}

Теперь передайте вашу функцию дочернему виджету в качестве аргумента конструктора.

RadioQuestionWidget(question : "What colour is the sky?", updatePropertyHandler : _updateProperty)

Получите свою функцию в дочернем виджете, как показано ниже.

class RadioQuestionWidget extends StatefulWidget {
  RadioQuestionWidget({Key key, this.question, this.updatePropertyHandler}) : super(key: key);
  final String question;
  final Function updatePropertyHandler;

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

Теперь в своем дочернем виджете, когда вы отвечаете на вопрос, вызовите функцию _updateUi в соответствии с вашими потребностями.

Radio(
      value: "Yes",
      groupValue: _radioValue,
      onChanged: (val) {
            setState(() {
                _radioValue = val;
                //here questionNum is int value you need to handle question no
                widget.updatePropertyHandler(questionNum, _radioValue);
            });
      },
         activeColor: Colors.green,
         focusColor: Colors.black,
     )
0 голосов
/ 10 июля 2020

Во-первых, отметьте приведенный выше ответ как правильный, так как я не смог бы заставить его работать без помощи @ Alpe sh.

Мне пришлось немного изменить ответ, чтобы обновить правильное свойство модели.

Это в моем родительском виджете:

            RadioQuestionWidget(
              question: 'Question 1',
              updatePropertyHandler: (String ans) => {
                setState(() {
                  _qc.speedForSpeedChaeckCompleted = ans;
                })
              },
            ),

, а это мой RadioQuestionWidget:

import 'package:flutter/material.dart';

class RadioQuestionWidget extends StatefulWidget {
  RadioQuestionWidget({Key key, this.question, this.updatePropertyHandler})
      : super(key: key);
  final String question;
  final Function updatePropertyHandler;

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

class _RadioQuestionWidgetState extends State<RadioQuestionWidget> {
  String question;
  var _groupValue;
  Function(String) onCountChange;

  @override
  void initState() {
    super.initState();
    question = widget.question;
    _groupValue = 'Not Applicable';
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          new Text(
            question,
            style: new TextStyle(
                fontSize: 16.0,
                color: Colors.black,
                fontWeight: FontWeight.bold),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              children: <Widget>[
                Radio(
                  value: "Yes",
                  groupValue: _groupValue,
                  onChanged: (val) {
                    setState(() {
                      _groupValue = val;
                      //here questionNum is int value you need to handle question no
                      widget.updatePropertyHandler(val);
                    });
                  },
                  activeColor: Colors.green,
                  focusColor: Colors.black,
                ),
                new Text(
                  'Yes',
                  style: new TextStyle(fontSize: 16.0, color: Colors.black),
                ),
                Radio(
                  value: "No",
                  groupValue: _groupValue,
                  onChanged: (val) {
                    setState(() {
                      _groupValue = val;
                      //here questionNum is int value you need to handle question no
                      widget.updatePropertyHandler(val);
                    });
                  },
                  activeColor: Colors.green,
                  focusColor: Colors.black,
                ),
                new Text(
                  'No',
                  style: new TextStyle(fontSize: 16.0, color: Colors.black),
                ),
                Radio(
                  value: "Not Applicable",
                  groupValue: _groupValue,
                  onChanged: (val) {
                    setState(() {
                      _groupValue = val;
                      //here questionNum is int value you need to handle question no
                      widget.updatePropertyHandler(val);
                    });
                  },
                  activeColor: Colors.red,
                  focusColor: Colors.black,
                ),
                new Text(
                  'Not applicable',
                  style: new TextStyle(fontSize: 16.0, color: Colors.black),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
...