0

I need help solving a problem. I am trying to retrieve a value which is the result of adding several values ​​of textfields in order to be able to use it in another screen, (either via the sharedpreferencies or sqlite) ... I can't seem to get this value ('totalvalues' in my example). Anyone have a method for me?

import 'package:flutter/material.dart';

class Screen1 extends StatefulWidget {
  Screen1({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _Screen1State createState() => _Screen1State();
}

class _Screen1State extends State<Screen1> {

  final myController1 = TextEditingController();
  final myController2 = TextEditingController();


  @override
  void dispose() {
    myController1.dispose();
    myController2.dispose();
    super.dispose();
  }
  double value1;
  double value2;
  //double totalvalues = value1 + value2;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Screen 1'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: myController1,
                    keyboardType: TextInputType.number,
                    onChanged: (val) {
                      setState(() {
                        value1 = double.parse(myController1.text) * 10;
                      });
                    },
                    decoration: InputDecoration(
                        hintText: '0'
                    ),
                  ),
                ),
                Expanded(
                    child: Center(
                        child: value1 != null
                            ? Text(value1.toStringAsFixed(0))
                            : Text('0')
                    )
                ),
              ],
            ),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: myController2,
                    keyboardType: TextInputType.number,
                    onChanged: (val) {
                      setState(() {
                        value2 = double.parse(myController2.text) * 5;
                      });
                    },
                    decoration: InputDecoration(
                        hintText: '0'
                    ),
                  ),
                ),
                Expanded(
                    child: Center(
                        child: value2 != null
                            ? Text(value2.toStringAsFixed(0))
                            : Text('0')
                    )
                ),
              ],
            ),
            Center(
              child: Text('totalvalues = value1 + value2'),
            ),
            Center(
                child: ElevatedButton(
                    onPressed: () {
                      print('$value1');
                      print('$value2');
                      myController1.clear();
                      myController2.clear();

                    },
                    child: Text('Next screen >')
                )
            )
          ],
        ),
      ),
    );
  }
}
mbrd
  • 335
  • 1
  • 4
  • 14
  • Use shared_pref or sqflite only if you need that data for future sessions too. Else you can simply create a class named data and add a static variable in it. Say the variable is named "additionData", then whenever you want to set or edit the data you can call : Data.additionData = 1; then you can get the data in same way : print(Data.additionData). You can use this static variable anywhere in your code. – Sarvesh Dalvi Mar 23 '21 at 08:30

2 Answers2

0

The problem here is that you have to recalculate totalvalue everytime a value changes.

First declare the variable without initializing it:

double totalvalues;

Second, on each onChanged function, recalculate the value:

For value1:

onChanged: (val) {
    setState(() {
        value1 = double.parse(myController1.text) * 10;
        totalvalues = value1 + value2;
    });
},

For value2:

onChanged: (val) {
    setState(() {
        value2 = double.parse(myController2.text) * 10;
        totalvalues = value1 + value2;
    });
},

Then you'll have totalvalue updated everytime you change an input and show it in your Text like this:

Text('$value1 + $value2 = $totalvalues')

If you expect to have more than two values or the way of calculationg totalvalue can change, I recomend you moving the recalculation to a function.

Brugui
  • 574
  • 6
  • 20
0

For you case, you even don't TextEditingController

class _Screen1State extends State<Screen1> {

 // final myController1 = TextEditingController();
 // final myController2 = TextEditingController();


  @override
  void dispose() {
   // myController1.dispose();
   // myController2.dispose();
    super.dispose();
  }
  double value1;
  double value2;
  //double totalvalues = value1 + value2;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Screen 1'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Row(
              children: [
                Expanded(
                  child: TextField(
                    // controller: myController1,
                    keyboardType: TextInputType.number,
                    onChanged: (val) {
                      setState(() {
                        //value1 = double.parse(myController1.text) * 10;
                        value1 = double.parse(val) * 10;
                      });
                    },
                    decoration: InputDecoration(
                        hintText: '0'
                    ),
                  ),
                ),
                Expanded(
                    child: Center(
                        child: value1 != null
                            ? Text(value1.toStringAsFixed(0))
                            : Text('0')
                    )
                ),
              ],
            ),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    // controller: myController2,
                    keyboardType: TextInputType.number,
                    onChanged: (val) {
                      setState(() {
                        // value2 = double.parse(myController2.text) * 5;
                        value2 = double.parse(val) * 5;

                      });
                    },
                    decoration: InputDecoration(
                        hintText: '0'
                    ),
                  ),
                ),
                Expanded(
                    child: Center(
                        child: value2 != null
                            ? Text(value2.toStringAsFixed(0))
                            : Text('0')
                    )
                ),
              ],
            ),
            Center(
              child: Text('totalvalues = ${value1 + value2}'),
            ),
            Center(
                child: ElevatedButton(
                    onPressed: () {
                      print('$value1');
                      print('$value2');
                      // myController1.clear();
                      // myController2.clear();
                      value1=0;
                      value2=0;
                    },
                    child: Text('Next screen >')
                )
            )
          ],
        ),
      ),
    );
  }
}
Sam Chan
  • 1,665
  • 4
  • 14
  • Thank you for your attention. Sam Chan: this code is a trial version, I am using the TextEditingController to give me the option to do a controller.clean () in the final version. – mbrd Mar 23 '21 at 11:53
  • Brugui: your method works, it seems astonishing to me to have to do this calculation on each TextField because for my final version, there will be up to 8 TextFields and I only want to 'store' the result to display it on a last screen before saving in a SQFLite database ... but it works. – mbrd Mar 23 '21 at 11:53
  • Sarvech Dalvi: I asked myself the question of making a backup in a sharedpreferencies to display this result on my last screen before saving in a sqflite database. I also looked at provider and BLoc but it is beyond my skills for the moment. I am going to look into your method to gain control of it. Thank you to you for your valuable advice and your experience. – mbrd Mar 23 '21 at 11:53
  • I replaced the code totalvalues ​​= value1 + value2; by the method: void totalScreen1 () { totalvalues ​​= value1 + value2; } in my StatefulWidget (looks better to me?) and I just have to store the result to use it on my last screen ... – mbrd Mar 23 '21 at 12:57