Return value 0 or 1 with checkbox (Dart)

Asked

Viewed 163 times

0

(I’m new to language)

I have a checkbox to inform if the customer wants to receive (1) the push or not (0).

My idea is to create a Dynamic variable (to receive all types) and then convert true=1 and false=0 as in the example below, but I get the following error:

type 'int' is not a subtype of type 'bool'

Could someone help me or tell me what I’m doing wrong?

Example class

class _TesteState extends State<Teste> {

dynamic _ativado = false;

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text("Teste"),
  ),
  body: Center(
    child: Row(
      children: [
        Text("Enviar para o histórico?"),
        Checkbox(onChanged: (dynamic e) {
          setState(() {
            _ativado = e;
            if(_ativado = true){
              _ativado = 1;
            } 
            else {
              _ativado = 0;
            }
          });
        },
        value: _ativado,
        ),
      ],
    ),
  ),
);

} }

Note: I have tried to convert the _enabled variable to toInt before assigning 1 and 0 to it, but neither will it

1 answer

0


You didn’t put the error line (it’s important to put when you ask a question here), but it’s probably the following:

value: _ativado,

The error occurs because Property value expects a value of the type bool. This can be checked in documentation:

@required bool value,

When she’s worth it 1 or 0, this property does not know how to interpret, she is waiting true or false and receives an integer that can represent many values.

You can fix it by making a ternary operator, for example:

value: _ativado==1?true:false,

Opening a parenthesis:

  • Will you need so many dynamics in your code like this?
  • What a gain do you get by swapping between false/true and 0/1 in the variable _ativado?
  • You need to use her as 1/0 somewhere else it wasn’t included in the question?
  • If so, couldn’t you instead check if _enabled is true or false?

The dynamic type is to be used very cautiously, and is not very recommended for beginners. When you delimit the correct type of variables, the compiler can warn you of many errors that you haven’t noticed. This one of your question for example. You help him help you. This is so much for the variable _ativado as to the e.

  • 1

    Perfect, thanks!! As for the parénteses... Yes, I am a empres task and the API expects the values 0 and 1, so necessarily I have to return the same...

  • 1

    I will study better possibilities to replace Dynamic, thanks for the guidelines

Browser other questions tagged

You are not signed in. Login or sign up in order to post.