Как отменить выбор радиокнопки в флаттере? - PullRequest
0 голосов
/ 08 ноября 2019

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

Текстовое поле может быть стерто:

RaisedButton(onPressed: () { _controllerTextField.clear();},
                  child: Text('Clear',style:Theme.of(context).textTheme.body2.merge(TextStyle(color: Colors.white)),),)

Но я неЯ не понимаю, как стереть мой текст и поставить радио по умолчанию в невыбранное состояние.

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

У вас есть представление о способе использования?

Спасибо

Ответы [ 3 ]

0 голосов
/ 08 ноября 2019

Если вы можете выбрать только один вариант;Укажите groupValue для переключателей

Пример:

const TYPE_DOG = 1
const TYPE_CAT = 2

                      Radio(
                        value: TYPE_DOG,
                        groupValue: type,
                        onChanged: (value) => setState(() => type = value),
                      ),
                      Radio(
                        value: TYPE_CAT,
                        groupValue: type,
                        onChanged: (value) => setState(() => type = value),
                      ),

, затем в onPressed установите это значение на 0;

0 голосов
/ 15 ноября 2019

Спасибо, Карим, за ваше предложение.

Извините, я был занят другими делами. Наконец я сделал это:

onPressed: () {
    _controller.clear();
    setState(() {
    radioSelectionne = 3;
     nombreTextField = null;
     Resultat = null;});
     },

И для цвета радио: В моем главном файле -> ThemeData -> unselectedWidgetColor

Все как я хотел.

Спасибо за вашу помощь.

0 голосов
/ 08 ноября 2019
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

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

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

class _TestState extends State<Test> {

  final TextEditingController _controllerTextField =  TextEditingController();


  double nombreTextField;
  int radioSelectionne;
  int resultat;

  Map coefMultipicateur = {
    0: 'x 2',
    1: 'x 5',
    2: 'x 10',
  };


  @override
  Widget build(BuildContext context) {
    return  GestureDetector(
      onTap: (() => FocusScope.of(context).requestFocus(FocusNode())),
      child: Scaffold(
        appBar: AppBar(
          title: Text('Test'),
        ),
        body: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.only(left:10.0, right: 10.0),
            child: Column(
              children: <Widget>[
                Container(
                    margin: EdgeInsets.only(top: 10.0, bottom: 50.0),
                    child:
                    Row(
                      children: <Widget>[
                        Expanded(
                            flex:6,
                            child: Text('entrer nombre :',
                              style:Theme.of(context).textTheme.body2.merge(
                                  TextStyle(
                                      fontSize: 16)),
                            )
                        ),
                        Expanded(
                          flex: 4,
                          child: TextField(
                            controller: _controllerTextField,
                            keyboardType: TextInputType.number,
                            onChanged: (String string) {
                              setState(() {
                                nombreTextField = double.tryParse(string);
                              });
                            },
                            decoration: InputDecoration(
                              labelText: 'entrer nombre',
                            ),
                          ),
                        )
                      ],
                    )
                ),
                Container(
                  margin: EdgeInsets.only(top: 10.0, bottom: 20.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 3,
                        child: Container(
                          color: Colors.blue,

                          child:columnRadio(),
                        ),
                      ),
                      Expanded(
                          flex: 7,
                          child: Center(
                              child: Column(
                                children: <Widget>[
                                  Text('resultat\n= ',
                                    textAlign: TextAlign.center,
                                    style:Theme.of(context).textTheme.title.merge(TextStyle(color: Colors.blueGrey)),),
                                  Container(
                                    margin: EdgeInsets.only(bottom: 10.0),
                                    child: Text(nombreTextField == null || radioSelectionne == null ? '' : '$resultat',
                                      style:Theme.of(context).textTheme.title.merge(TextStyle(color: Colors.green)),),
                                  ),
                                ],
                              )
                          )
                      )
                    ],
                  ),
                ),
                Container(
                    margin: EdgeInsets.only(top: 50.0),
                    child: RaisedButton(
                      onPressed: () {
                        _controllerTextField.clear();
                      },
                      color: Colors.blue,
                      child: Text('Clear',
                        style:Theme.of(context).textTheme.body2.merge(TextStyle(color: Colors.white)),
                      ),
                    )
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  Column columnRadio() {
    List<Widget> pourcentages = [];
    coefMultipicateur.forEach((key, value) {
      Row listePourcentages = Row(
        children: <Widget>[
          Radio(
              activeColor: Colors.white,
              value: key,
              groupValue: radioSelectionne,
              onChanged: (Object i) {
                setState(() {
                  radioSelectionne = i;
                  if (nombreTextField != null) {
                    switch (radioSelectionne) {
                      case 0:
                        resultat = (nombreTextField * 2).toInt();
                        break;
                      case 1:
                        resultat = (nombreTextField * 5).toInt();
                        break;
                      case 2:
                        resultat = (nombreTextField *  10).toInt();
                        break;
                    }
                  }
                });
              }),
          Text(value,
              style: TextStyle(
                  color: (radioSelectionne == key) ? Colors.white : Colors.blue[200],
                  fontWeight: FontWeight.bold)),
        ],
      );
      pourcentages.add(listePourcentages);
    });
    return Column(
      children: pourcentages,
    );
  }
}
...