Search code examples
flutterdartsetstate

Button that change units of measure dynamically flutter


I am trying to create a button that, when pressed, will cycle back and fourth between units of measure (i.e. cm and inches) in flutter. I am able to go from cm to inches but can not figure out how to make the text dynamically change back to cm if the button is pressed and displays inches. I know I need to move my if statement out of my setState but cant seem to get it to work without an error. Any tips?

import 'package:flutter/material.dart';

enum Units { cm, inches }

class InputRow extends StatefulWidget {
  InputRow({
    this.inputParameter,
  });
  final String inputParameter;

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

class _InputRowState extends State<InputRow> {
  String Unit = 'cm';
  Units selectedUnit;

  @override
  Widget build(BuildContext context) {
    return Center(
        child: Column(
      children: <Widget>[
        SizedBox(
          height: 100,
        ),
        Container(
          constraints: BoxConstraints(maxWidth: 350),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Text(widget.inputParameter),
              Flexible(
                child: TextField(),
              ),
              Text(Unit),
              RaisedButton(
                shape: new RoundedRectangleBorder(
                    borderRadius: new BorderRadius.circular(18.0),
                    side: BorderSide(color: Colors.red)),
                color: Colors.deepPurple,
                textColor: Colors.black,
                onPressed: () {
                  setState(() {
                    selectedUnit == Units.inches ? Units.cm : Units.inches;
                    if (selectedUnit == Units.cm) {
                      Unit = 'cm';
                    } else {
                      Unit = 'inches';
                    }
                  });
                },
              ),
            ],
          ),
        )
      ],
    ));
  }
}


Solution

  • change your setState method to

    setState(() {
                        selectedUnit =
                            selectedUnit == Units.inches ? Units.cm : Units.inches;
    
                        if (selectedUnit == Units.cm) {
                          unit = 'cm';
                        } else {
                          unit = 'inches';
                        }
                      });