0

Am i trying to get the second screen double value in first screen when i click the device back button but i can't get it.I don't know how to do it. I'm a beginner for flutter.Help me to solve it.

My task is first screen get two double value using text field and pass it to second screen. second screen have text field to enter the operator and click device back button it will check the operator and make the equal operations like(addition,subtraction,multiplication and division) then the answer will be display in the first screen.

How can i get the second screen double variable(value) in first screen. How to pass a double value to another class

This is my code.


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


class User {
  final double a, b,c;
   User(
    {
    this.a,
    this.b,
    this.c,
    }
  );
}


void main() {
  runApp(MaterialApp(
    title: 'Navigation Basics',
    home: App(),
  ));
}

class App extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primaryColor: Color(0xFFFB415B),
        fontFamily: "Ubuntu"
      ),
      home: LoginPage(),
    );
  }
}

class LoginPage extends StatefulWidget{
  final User value;

  LoginPage ({Key key, this.value}) : super(key: key);
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage>{
double c1;
 /*callback(double c2) {
   print("$c2");
    setState(() {
    c1 = c2;
    });
}*/

  bool _isHidden = true;

  var _acontroller= new TextEditingController();
  var _bcontroller= new TextEditingController();
  void _toggleVisibility(){
    setState(() {
      _isHidden = !_isHidden;
    });
  }
  Future<bool> _onWillPop() {
    return showDialog(
      context: context,
      builder: (context) => new AlertDialog(
        title: new Text('Are you sure?'),
        content: new Text('Do you want to exit an App'),
        actions: <Widget>[
          new FlatButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: new Text('No'),
          ),
          new FlatButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: new Text('Yes'),
          ),
        ],
      ),
    ) ?? false;
  }

  @override
  Widget build(BuildContext context){


         return WillPopScope(
      onWillPop:_onWillPop,
                child: Scaffold(
                  appBar: AppBar(
                    title: Text("First Page"),
                  ),
                  resizeToAvoidBottomPadding: false,
                  body: Container(
                    padding: EdgeInsets.only(top: 100.0, right: 20.0, left: 20.0, bottom: 20.0),
                    child: Column(
                       mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          'Hello',
                          style: TextStyle(
                            fontSize: 50.0,
                            fontWeight: FontWeight.bold,
                            fontFamily: "Pacifico"
                          ),
                        ),

                        TextFormField(

                           keyboardType: TextInputType.number,
                            inputFormatters: <TextInputFormatter>[
                                WhitelistingTextInputFormatter.digitsOnly
                            ],
                          controller: _acontroller,
                           decoration: InputDecoration(
                            border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(20.0),
                                ),
                                 hintText: 'Enter A value',
                              hintStyle: TextStyle(color: Colors.grey),
                            contentPadding: EdgeInsets.all(10)
                        )
                        ),

                        TextFormField(
                           keyboardType: TextInputType.number,
                            inputFormatters: <TextInputFormatter>[
                                WhitelistingTextInputFormatter.digitsOnly
                            ],
                          controller: _bcontroller,
                           decoration: InputDecoration(
                            border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(20.0),
                                ),
                                 hintText: 'Enter B value',
                              hintStyle: TextStyle(color: Colors.grey),
                            contentPadding: EdgeInsets.all(5)
                        )
                        ),
                         RaisedButton(
                          child: Text(" OK "),
                           color: Colors.red,
                          textColor: Colors.white,
                          splashColor: Colors.grey,
                          padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                          onPressed: () async {

                            if(_acontroller.text == "" && _bcontroller.text == "")
                            {
                               await showDialog(
                  context: context,
                  builder: (context) => new AlertDialog(
                    title: new Text('Please Enter The value'),
                  ),
                    );
                            }

                            else if(_acontroller.text == "")
                            {
                               await showDialog(
                  context: context,
                  builder: (context) => new AlertDialog(
                    title: new Text('Please Enter The A value'),
                  ),
                    );
                            }
                             else if(_bcontroller.text == "")
                            {
                               await showDialog(
                  context: context,
                  builder: (context) => new AlertDialog(
                    title: new Text('Please Enter The B value'),
                  ),
                    );
                            }

                            else
                            {
                           //a = emailController.text;
               var route = new MaterialPageRoute(
                                builder: (BuildContext context) =>
                                    new SecondScreen(
                                      value: User(
                                              a:double.parse(_acontroller.text) ,
                                              b:double.parse(_bcontroller.text) ,

                                              )
                                              ),
                              );
                              Navigator.of(context).push(route);
                          }
                          }
                           ),


              Text('Answers : $c1',//+ {widget.value.c}.toString(),//${widget.value.c}
            style: TextStyle(
              fontSize: 35.0,
              fontWeight: FontWeight.bold,
              fontFamily: "Pacifico"
            ),
            ),

          ]

    )
      )
    ));

  }



}

class SecondScreen extends StatefulWidget {
   final User value;
double c1;
double c2;
//Function(double) callback;

  SecondScreen ({Key key, this.value}) : super(key: key);
  @override
  _SecondScreenState createState() => _SecondScreenState();
}

class _SecondScreenState extends State<SecondScreen> {

 var _ccontroller= new TextEditingController();
  Future<bool> _onWillPop() async {

      if(_ccontroller.text == ""){
        await showDialog(
      context: context,
      builder: (context) => new AlertDialog(
        title: new Text('Please Enter The Operator'),
      ),
        );
      }
    else if(_ccontroller.text == "+"){
       double a1=  widget.value.a;
       double b1= widget.value.b;


      //  c1 = a1+b1;
        setState(() {
              widget.c1 = a1+b1;
            });
              //widget.callback = (c) as Function(double);



        Navigator.pop(context);
     }
    else if(_ccontroller.text == "-"){
       double a1=  widget.value.a;
       double b1= widget.value.b;

       setState(() {
              widget.c1 = a1-b1;
            });


        Navigator.pop(context, '$widget.c1');
     }
     else if(_ccontroller.text == "*" || _ccontroller.text =="×" ){
       double a1=  widget.value.a;
       double b1= widget.value.b;

       setState(() {
              widget.c1 = a1*b1;
            });


          Navigator.pop(context, '$widget.c1');
     }
     else if(_ccontroller.text == "/"){
       double a1=  widget.value.a;
       double b1= widget.value.b;

        setState(() {
              widget.c1 = a1/b1;
            });


         Navigator.pop(context, '$widget.c1');
     }
     else{
       await showDialog(
      context: context,
      builder: (context) => new AlertDialog(
        title: new Text('Wrong Operator'),
      ),
        );
     }

  }

 @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop:_onWillPop,

          child: Scaffold(
        appBar: AppBar(
          title: Text('Operation'),
         backgroundColor: new Color(0xFF81C784),
        ),
        body: Center(
          child: Wrap(
            children: <Widget>[
                TextFormField(
                    controller: _ccontroller,
  decoration: new InputDecoration.collapsed(
       border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10.0),
          ),
      hintText: 'Enter Operator'
  ),

),


            ],


        ),
        )

      ),  
    );

  }
}




2 Answers2

1

You can await the result from your Navigator.of(context).push(...) and use it in your first screen to display the result from the second screen. Also, when you pop your second screen, you need to do it by calling Navigator.of(context).pop(yourValue) for it to work.

Check out this article from Flutter.dev: Return Data from a Screen for a detailed, step-by-step explanation on the topic.

drogel
  • 2,567
  • 2
  • 13
  • 22
  • However this will not work in case user uses back button of android device or pull from left to go back to previous screen in iOS App.. So think before what you are planning – Dev Mar 04 '20 at 10:52
  • 1
    It still works, you need to implement WillPopScope to override the device back button – Federick Jonathan Mar 04 '20 at 11:05
  • I try it but it pass a string value but i want to pass a double variable to first screen – Rock Durai Mar 05 '20 at 05:45
0

Check cookbook at

https://flutter.dev/docs/cookbook/navigation/returning-data

Basically

 Navigator.pop(context, 'Nope.');
Dev
  • 6,628
  • 2
  • 25
  • 34
  • However this will not work in case user uses back button of android device or pull from left to go back to previous screen in iOS App.. So think before what you are planning – Dev Mar 04 '20 at 10:54