irongirl
irongirl

Reputation: 935

Execute two functions for a button in flutter

So i want to be able to save the text from the textcontroller that user have keyed in into shared preferences However, i want to go to the next page too at the same time.

So:

  1. Save the text in a shared preference
  2. Go to next page

    final _text = TextEditingController();
    
    _nameSaver() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString('my_string_key', _text.text);
      }
    
    FooterRaisedButton(
                      "Next",
                      () => (_text.text.isEmpty)
                          ? null
                          : Navigator.pushNamed(context, '/onboardMarket'),
                      "#0087a8")
    

I dont know how to call out the function that saves the name at the same time the button pressed will go to the next page

Upvotes: 1

Views: 1937

Answers (2)

CopsOnRoad
CopsOnRoad

Reputation: 267444

Remove fat arrow (=>), and implement it like this:

FooterRaisedButton(
  "Next",
   () async {
    if (_text.text.isEmpty)
      return; // return if it is empty
    await nameSaver(); // else save it here
    Navigator.pushNamed(context, '/onboardMarket'); // once done, navigate
  }
);

Just to give you a basic idea,

// only one statement can be executed using fat notation
RaisedButton(onPressed: () => _calculate(1));

// here you can perform as many as you need.
RaisedButton(onPressed: () {
  _calculate(1);
  _printScreen();
});

Upvotes: 5

Yash Jain
Yash Jain

Reputation: 415

Try this code it should work :

Code:

final _text = TextEditingController();

  _nameSaver() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('my_string_key', _text.text);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RaisedButton(
        child: Text("Next"),
        onPressed: (){
          if(_text.text.isEmpty){
            print("Cannot use empty text");
          }
          else {
            _nameSaver();
            Navigator.pushNamed(context, '/onboardMarket');
          }

        },
      ),
    );
  }

Upvotes: 0

Related Questions