Home > Net >  How to autofill values in other boxes in flutter?
How to autofill values in other boxes in flutter?

Time:12-05

I want to autofill the other boxes with calculated values when one of the box is filled with a value. For example:Box Fields

When I fill the 'meter' value, the value in 'feet', and 'centimeter' should get auto-filled with respective values. And same for the other values. I couldn't come up with any idea or code (In Flutter) . Please give some help with code, plugins or extensions.

CodePudding user response:

This is just a quick example on how to achieve what you want, just using plain TextFormField widgets with its own TextEditingController's.

The enum UnitType will help you out figuring which field was actually modified and update the others accordingly.

enter image description here

enum UnitType {
  meter,
  cm,
  feet,
}

class ConvertWidget extends StatelessWidget {
  ConvertWidget({Key? key}) : super(key: key);

  final TextEditingController _feetController = TextEditingController(text: '0');
  final TextEditingController _cmController = TextEditingController(text: '0');
  final TextEditingController _meterController = TextEditingController(text: '0');

  void _convertUnit(UnitType type) {
    double? ft = double.tryParse(_feetController.value.text) ?? 0;
    double? cm = double.tryParse(_cmController.value.text) ?? 0;
    double? meter = double.tryParse(_meterController.value.text) ?? 0;

    switch (type) {
      case UnitType.feet:
        _meterController.text = (ft * 0.3048).toString();
        _cmController.text = (ft * 100).toString();
        break;

      case UnitType.cm:
        _meterController.text = (cm / 100).toString();
        _feetController.text = (cm * 0.03048).toString();
        break;

      case UnitType.meter:
        _cmController.text = (meter * 100).toString();
        _feetController.text = (meter * 0.3048).toString();
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextFormField(
              controller: _feetController,
              keyboardType: TextInputType.number,
              onChanged: (_) => _convertUnit(UnitType.feet),
              decoration: const InputDecoration(labelText: 'Feet'),
            ),
            TextFormField(
              controller: _cmController,
              keyboardType: TextInputType.number,
              onChanged: (_) => _convertUnit(UnitType.cm),
              decoration: const InputDecoration(labelText: 'CM'),
            ),
            TextFormField(
              controller: _meterController,
              keyboardType: TextInputType.number,
              onChanged: (_) => _convertUnit(UnitType.meter),
              decoration: const InputDecoration(labelText: 'Meter'),
            ),
          ],
        ),
      ),
    );
  }
}
  • Related