Home > Net >  Flutter / Dart - ToggleButtons adding a changeable number and transposing the choice
Flutter / Dart - ToggleButtons adding a changeable number and transposing the choice

Time:12-09

After some great help, ToggleButtons are now in my app. However, is it possible to add input text boxes (with default numbers already inside - Breakfast 1.0, Lunch 0.6 and Tea 0.55) (allowing numbers only and decimals) into those ToggleButtons and whichever one is picked the number gets transposed into the numR3C2controller ('Meal Carbs') box to be used in the calculation?

How my app needs to look :

enter image description here

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    const appTitle = 'Help with diabetic dosage for a meal!';
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: const Text(appTitle),
          backgroundColor: Colors.grey,
          foregroundColor: Colors.black,
        ),
        body: const AddTwoNumbers(),
      ),
    );
  }
}

class AddTwoNumbers extends StatefulWidget {
  const AddTwoNumbers({super.key});

  @override
  // ignore: library_private_types_in_public_api
  _AddTwoNumbersState createState() => _AddTwoNumbersState();
}

class _AddTwoNumbersState extends State<AddTwoNumbers> {
  Color _fillColor = Colors.white;
  TextEditingController numR1C1controller =
      TextEditingController(); //Changed name of the texteditingcontroller as Row as R and Column as C
  TextEditingController numR1C2controller = TextEditingController();
  TextEditingController numR1C3controller = TextEditingController();
  TextEditingController numR2C1controller = TextEditingController();
  TextEditingController numR2C2controller = TextEditingController();
  TextEditingController numR2C3controller = TextEditingController();
  TextEditingController numR3C1controller = TextEditingController();
  TextEditingController numR3C2controller = TextEditingController();
  TextEditingController numR3C3controller = TextEditingController();
  String result = "0";
  String result2 = "0";
  String result3 = "0";

  // MAKE LIST OF MAP TO KEEP TRACK OF EACH BUTTONS
  List<Map> buttons = [
    {"name": "BreakFast", "active": false},
    {"name": "Lunch", "active": false},
    {"name": "Tea", "active": false},
  ];

  // YOU CAN SET VARIABLE TO CURRENT MEAL NAME AND CAN CHECK WHETHER IT'S (breakFast) OR NOT
  String? currentMealType;

  // TOGGLE BUTTON FUNCTION
  toggleButtons(String name) {
    for (var i in buttons) {
      if (i['name'] == name) {
        i['active'] = !i['active'];
      } else {
        i['active'] = false;
      }
    }

    setState(() {});
  }

  _calculateR1() {
    if (numR1C1controller.text.isNotEmpty &&
        numR1C2controller.text.isNotEmpty) {
      double sum = double.parse(numR1C1controller.text) -
          double.parse(numR1C2controller.text);
      numR1C3controller.text = sum.toStringAsFixed(1);
      result = sum.toStringAsFixed(1);
    }

    if (numR1C2controller.text.isNotEmpty) {
      setState(() {
        _fillColor = double.parse(numR1C2controller.text) < 5
            ? Colors.red
            : double.parse(numR1C2controller.text) > 9.1
                ? Colors.orange
                : Colors.green;
      });
    } else {
      setState(() {
        _fillColor = Colors.white;
      });
    }
  }

  _calculateR2() {
    if (numR2C1controller.text.isNotEmpty &&
        numR2C2controller.text.isNotEmpty) {
      setState(() {
        double sum = double.parse(numR2C1controller.text) /
            double.parse(numR2C2controller.text);
        numR2C3controller.text = sum.toStringAsFixed(1);
        result2 = sum.toStringAsFixed(1);
      });
    }
  }

  _calculateR3() {
    if (numR3C1controller.text.isNotEmpty &&
        numR3C2controller.text.isNotEmpty) {
      setState(() {
        double sum = double.parse(numR3C1controller.text) *
            double.parse(numR3C2controller.text);
        numR3C3controller.text = sum.toStringAsFixed(1);
        result3 = sum.toStringAsFixed(1);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Container(
          padding: const EdgeInsets.all(10.0),
          child: Column(
            children: [
              const Padding(
                padding: EdgeInsets.all(6.0),
                child: Text('Meal Ratio'),
              ),

              // HERER IS THE VIEW FOR BUTTONS
              //******************************

              Row(
                children: buttons
                    .map((btn) => Expanded(
                          child: GestureDetector(
                            onTap: () {
                              toggleButtons(btn['name']);
                            },
                            child: Container(
                              padding: const EdgeInsets.all(20.0),
                              margin:
                                  const EdgeInsets.only(bottom: 10, right: 10),
                              decoration: BoxDecoration(
                                  color:
                                      btn['active'] ? Colors.red : Colors.white,
                                  border: Border.all(color: Colors.grey[300]!)),
                              child: Text(btn['name'],
                                  style: TextStyle(
                                      color: btn['active']
                                          ? Colors.white
                                          : Colors.black)),
                            ),
                          ),
                        ))
                    .toList(),
              ),

              //******************************

              Row(
                children: <Widget>[
                  Expanded(
                    child: TextField(
                      textAlign: TextAlign.center,
                      style: const TextStyle(fontSize: 20.0),
                      controller: numR1C1controller,
                      onChanged: (value) => _calculateR1(),
                      keyboardType:
                          const TextInputType.numberWithOptions(decimal: true),
                      inputFormatters: <TextInputFormatter>[
                        FilteringTextInputFormatter.allow(
                            RegExp(r'^(\d )?\.?\d{0,1}'))
                      ],
                      decoration: InputDecoration(
                          border: const OutlineInputBorder(),
                          labelText: 'Target Level',
                          hintText: 'Enter First Number',
                          fillColor: _fillColor,
                          filled: false),
                    ),
                  ),
                  const SizedBox(
                    width: 8,
                  ),
                  Expanded(
                    child: TextField(
                      textAlign: TextAlign.center,
                      style: const TextStyle(fontSize: 20.0),
                      onChanged: (value) => _calculateR1(),
                      keyboardType:
                          const TextInputType.numberWithOptions(decimal: true),
                      controller: numR1C2controller,
                      inputFormatters: <TextInputFormatter>[
                        FilteringTextInputFormatter.allow(
                            RegExp(r'^(\d )?\.?\d{0,1}'))
                      ],
                      decoration: InputDecoration(
                          border: const OutlineInputBorder(),
                          filled: true,
                          labelText: 'Current Level',
                          hintText: 'Enter Second Number',
                          fillColor: _fillColor),
                    ),
                  ),
                  const SizedBox(
                    width: 8,
                  ),
                  Expanded(
                    child: TextField(
                      textAlign: TextAlign.center,
                      style: const TextStyle(fontSize: 20.0),
                      onChanged: (value) => _calculateR1(),
                      keyboardType:
                          const TextInputType.numberWithOptions(decimal: true),
                      controller: numR1C3controller,
                      inputFormatters: <TextInputFormatter>[
                        FilteringTextInputFormatter.digitsOnly
                      ],
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Result',
                        hintText: '',
                      ),
                    ),
                  ),
                  const SizedBox(
                    width: 8,
                  ),
                ],
              ),
              const SizedBox(
                height: 8,
              ),
              const Padding(
                padding: EdgeInsets.all(6.0),
                child: Text('Calculations'),
              ),
              Row(
                children: [
                  Expanded(
                    child: TextField(
                      onChanged: (value) => _calculateR2(),
                      keyboardType:
                          const TextInputType.numberWithOptions(decimal: true),
                      controller: numR2C1controller,
                      inputFormatters: <TextInputFormatter>[
                        FilteringTextInputFormatter.allow(
                            RegExp(r'^(\d )?\.?\d{0,2}'))
                      ],
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'One Unit',
                        hintText: 'Enter Third Number',
                      ),
                    ),
                  ),
                  const SizedBox(
                    width: 8,
                  ),
                  Expanded(
                    child: TextField(
                      onChanged: (value) => _calculateR2(),
                      keyboardType:
                          const TextInputType.numberWithOptions(decimal: true),
                      controller: numR2C2controller,
                      inputFormatters: <TextInputFormatter>[
                        FilteringTextInputFormatter.allow(
                            RegExp(r'^(\d )?\.?\d{0,2}'))
                      ],
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Drop by mmol?',
                        hintText: 'Enter Fourth Number',
                      ),
                    ),
                  ),
                  const SizedBox(
                    width: 8,
                  ),
                  Expanded(
                    child: TextField(
                      textAlign: TextAlign.center,
                      style: const TextStyle(fontSize: 20.0),
                      onChanged: (value) => _calculateR3(),
                      keyboardType:
                          const TextInputType.numberWithOptions(decimal: true),
                      controller: numR2C3controller,
                      inputFormatters: <TextInputFormatter>[
                        FilteringTextInputFormatter.digitsOnly
                      ],
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Result',
                        hintText: '',
                      ),
                    ),
                  ),
                  const SizedBox(
                    width: 8,
                  ),
                ],
              ),
              const SizedBox(
                height: 8,
              ),
              Row(
                children: [
                  Expanded(
                    child: TextField(
                      onChanged: (value) => _calculateR3(),
                      keyboardType:
                          const TextInputType.numberWithOptions(decimal: true),
                      controller: numR3C1controller,
                      inputFormatters: <TextInputFormatter>[
                        FilteringTextInputFormatter.allow(
                            RegExp(r'^(\d )?\.?\d{0,2}'))
                      ],
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Meal Carbs',
                        hintText: 'Enter Fifth Number',
                      ),
                    ),
                  ),
                  const SizedBox(
                    width: 8,
                  ),
                  Expanded(
                    child: TextField(
                      onChanged: (value) => _calculateR3(),
                      keyboardType:
                          const TextInputType.numberWithOptions(decimal: true),
                      controller: numR3C2controller,
                      inputFormatters: <TextInputFormatter>[
                        FilteringTextInputFormatter.allow(
                            RegExp(r'^(\d )?\.?\d{0,2}'))
                      ],
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Meal Ratio',
                        hintText: 'Enter Sixth Number',
                      ),
                    ),
                  ),
                  const SizedBox(
                    width: 8,
                  ),
                  Expanded(
                    child: TextField(
                      textAlign: TextAlign.center,
                      style: const TextStyle(fontSize: 20.0),
                      onChanged: (value) => _calculateR3(),
                      keyboardType:
                          const TextInputType.numberWithOptions(decimal: true),
                      controller: numR3C3controller,
                      inputFormatters: <TextInputFormatter>[
                        FilteringTextInputFormatter.digitsOnly
                      ],
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Result',
                        hintText: '',
                      ),
                    ),
                  ),
                  const SizedBox(
                    width: 8,
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

CodePudding user response:

I've done some changes in the UI and toggleButton(String) method following is the complete code:

  import 'package:flutter/material.dart';
  import 'package:flutter/services.dart';

  void main() => runApp(const MyApp());

  class MyApp extends StatelessWidget {
    const MyApp({super.key});

    @override
    Widget build(BuildContext context) {
      const appTitle = 'Help with diabetic dosage for a meal!';
      return MaterialApp(
        title: appTitle,
        home: Scaffold(
          appBar: AppBar(
            title: const Text(appTitle),
            backgroundColor: Colors.grey,
            foregroundColor: Colors.black,
          ),
          body: const AddTwoNumbers(),
        ),
      );
    }
  }

  class AddTwoNumbers extends StatefulWidget {
    const AddTwoNumbers({super.key});

    @override
    // ignore: library_private_types_in_public_api
    _AddTwoNumbersState createState() => _AddTwoNumbersState();
  }

  class _AddTwoNumbersState extends State<AddTwoNumbers> {
    Color _fillColor = Colors.white;

    TextEditingController numR1C1controller =
        TextEditingController(); //Changed name of the texteditingcontroller as Row as R and Column as C
    TextEditingController numR1C2controller = TextEditingController();
    TextEditingController numR1C3controller = TextEditingController();
    TextEditingController numR2C1controller = TextEditingController();
    TextEditingController numR2C2controller = TextEditingController();
    TextEditingController numR2C3controller = TextEditingController();
    TextEditingController numR3C1controller = TextEditingController();
    TextEditingController numR3C2controller = TextEditingController();
    TextEditingController numR3C3controller = TextEditingController();

    String result = "0";
    String result2 = "0";
    String result3 = "0";

    // MAKE LIST OF MAP TO KEEP TRACK OF EACH BUTTONS
    List<Map> buttons = [
      {"name": "BreakFast", "active": false, "value": 1.0},
      {"name": "Lunch", "active": false, "value": 0.6},
      {"name": "Tea", "active": false, "value": 0.55},
    ];

    // YOU CAN SET VARIABLE TO CURRENT MEAL NAME AND CAN CHECK WHETHER IT'S (breakFast) OR NOT
    String? currentMealType;

    // TOGGLE BUTTON FUNCTION
    toggleButtons(Map obj) {
      for (var i in buttons) {
        if (i['name'] == obj['name']) {
          i['active'] = !i['active'];
          numR3C2controller.text = obj['value'].toString();
          _calculateR3();
        } else {
          i['active'] = false;
        }
      }

      setState(() {});
    }

    _calculateR1() {
      if (numR1C1controller.text.isNotEmpty &&
          numR1C2controller.text.isNotEmpty) {
        double sum = double.parse(numR1C1controller.text) -
            double.parse(numR1C2controller.text);
        numR1C3controller.text = sum.toStringAsFixed(1);
        result = sum.toStringAsFixed(1);
      }

      if (numR1C2controller.text.isNotEmpty) {
        setState(() {
          _fillColor = double.parse(numR1C2controller.text) < 5
              ? Colors.red
              : double.parse(numR1C2controller.text) > 9.1
                  ? Colors.orange
                  : Colors.green;
        });
      } else {
        setState(() {
          _fillColor = Colors.white;
        });
      }
    }

    _calculateR2() {
      if (numR2C1controller.text.isNotEmpty &&
          numR2C2controller.text.isNotEmpty) {
        setState(() {
          double sum = double.parse(numR2C1controller.text) /
              double.parse(numR2C2controller.text);
          numR2C3controller.text = sum.toStringAsFixed(1);
          result2 = sum.toStringAsFixed(1);
        });
      }
    }

    _calculateR3() {
      if (numR3C1controller.text.isNotEmpty &&
          numR3C2controller.text.isNotEmpty) {
        setState(() {
          double sum = double.parse(numR3C1controller.text) *
              double.parse(numR3C2controller.text);
          numR3C3controller.text = sum.toStringAsFixed(1);
          result3 = sum.toStringAsFixed(1);
        });
      }
    }

    @override
    Widget build(BuildContext context) {
      return Container(
        padding: const EdgeInsets.all(10.0),
        child: Column(
          children: [
            const Padding(
              padding: EdgeInsets.all(6.0),
              child: Text('Meal Ratio'),
            ),

            // HERE IS THE VIEW FOR BUTTONS
            //******************************

            Row(
              children: buttons
                  .map(
                    (btn) => Expanded(
                      child: GestureDetector(
                        onTap: () => toggleButtons(btn),
                        child: Container(
                          padding: const EdgeInsets.all(20.0),
                          margin: const EdgeInsets.only(bottom: 10, right: 10),
                          decoration: BoxDecoration(
                              color: btn['active'] ? Colors.red : Colors.white,
                              border: Border.all(color: Colors.grey[300]!)),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(btn['name'],
                                  style: TextStyle(
                                      color: btn['active']
                                          ? Colors.white
                                          : Colors.black)),
                              Text(btn['value'].toString(),
                                  style: TextStyle(
                                      color: btn['active']
                                          ? Colors.white
                                          : Colors.black))
                            ],
                          ),
                        ),
                      ),
                    ),
                  )
                  .toList(),
            ),

            //******************************

            Row(
              children: <Widget>[
                Expanded(
                  child: TextField(
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 20.0),
                    controller: numR1C1controller,
                    onChanged: (value) => _calculateR1(),
                    keyboardType:
                        const TextInputType.numberWithOptions(decimal: true),
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.allow(
                          RegExp(r'^(\d )?\.?\d{0,1}'))
                    ],
                    decoration: InputDecoration(
                        border: const OutlineInputBorder(),
                        labelText: 'Target Level',
                        hintText: 'Enter First Number',
                        fillColor: _fillColor,
                        filled: false),
                  ),
                ),
                const SizedBox(
                  width: 8,
                ),
                Expanded(
                  child: TextField(
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 20.0),
                    onChanged: (value) => _calculateR1(),
                    keyboardType:
                        const TextInputType.numberWithOptions(decimal: true),
                    controller: numR1C2controller,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.allow(
                          RegExp(r'^(\d )?\.?\d{0,1}'))
                    ],
                    decoration: InputDecoration(
                        border: const OutlineInputBorder(),
                        filled: true,
                        labelText: 'Current Level',
                        hintText: 'Enter Second Number',
                        fillColor: _fillColor),
                  ),
                ),
                const SizedBox(
                  width: 8,
                ),
                Expanded(
                  child: TextField(
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 20.0),
                    onChanged: (value) => _calculateR1(),
                    keyboardType:
                        const TextInputType.numberWithOptions(decimal: true),
                    controller: numR1C3controller,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.digitsOnly
                    ],
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Result',
                      hintText: '',
                    ),
                  ),
                ),
                const SizedBox(
                  width: 8,
                ),
              ],
            ),
            const SizedBox(
              height: 8,
            ),
            const Padding(
              padding: EdgeInsets.all(6.0),
              child: Text('Calculations'),
            ),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    onChanged: (value) => _calculateR2(),
                    keyboardType:
                        const TextInputType.numberWithOptions(decimal: true),
                    controller: numR2C1controller,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.allow(
                          RegExp(r'^(\d )?\.?\d{0,2}'))
                    ],
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'One Unit',
                      hintText: 'Enter Third Number',
                    ),
                  ),
                ),
                const SizedBox(
                  width: 8,
                ),
                Expanded(
                  child: TextField(
                    onChanged: (value) => _calculateR2(),
                    keyboardType:
                        const TextInputType.numberWithOptions(decimal: true),
                    controller: numR2C2controller,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.allow(
                          RegExp(r'^(\d )?\.?\d{0,2}'))
                    ],
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Drop by mmol?',
                      hintText: 'Enter Fourth Number',
                    ),
                  ),
                ),
                const SizedBox(
                  width: 8,
                ),
                Expanded(
                  child: TextField(
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 20.0),
                    onChanged: (value) => _calculateR3(),
                    keyboardType:
                        const TextInputType.numberWithOptions(decimal: true),
                    controller: numR2C3controller,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.digitsOnly
                    ],
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Result',
                      hintText: '',
                    ),
                  ),
                ),
                const SizedBox(
                  width: 8,
                ),
              ],
            ),
            const SizedBox(
              height: 8,
            ),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    onChanged: (value) => _calculateR3(),
                    keyboardType:
                        const TextInputType.numberWithOptions(decimal: true),
                    controller: numR3C1controller,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.allow(
                          RegExp(r'^(\d )?\.?\d{0,2}'))
                    ],
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Meal Carbs',
                      hintText: 'Enter Fifth Number',
                    ),
                  ),
                ),
                const SizedBox(
                  width: 8,
                ),
                Expanded(
                  child: TextField(
                    onChanged: (value) => _calculateR3(),
                    keyboardType:
                        const TextInputType.numberWithOptions(decimal: true),
                    controller: numR3C2controller,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.allow(
                          RegExp(r'^(\d )?\.?\d{0,2}'))
                    ],
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Meal Ratio',
                      hintText: 'Enter Sixth Number',
                    ),
                  ),
                ),
                const SizedBox(
                  width: 8,
                ),
                Expanded(
                  child: TextField(
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 20.0),
                    onChanged: (value) => _calculateR3(),
                    keyboardType:
                        const TextInputType.numberWithOptions(decimal: true),
                    controller: numR3C3controller,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.digitsOnly
                    ],
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Result',
                      hintText: '',
                    ),
                  ),
                ),
                const SizedBox(
                  width: 8,
                ),
              ],
            ),
          ],
        ),
      );
    }
  }
  • Related