6

I have an appBar with a search button, which when pressed returns a custom DataSearch class that extends SearchDelegate.

When I close the search page (from the device's go back button or from the widget), I need to execute a certain function first. However the function is only executed from the below widget and not when the device's "BACK" button is pressed.

(Image below)

Here's my code:

class DataSearch extends SearchDelegate<String> {
  @override
  List<Widget> buildActions(BuildContext context) {
    // ...
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.arrow_back),
      onPressed: () {
        function_I_need_to_execute();
        close(context, null);
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    // ...
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    // ...
  }
}

I've tried this, but no changes:

@override
  void close(BuildContext context, String result) {
    super.close(context, result);
    function_I_need_to_execute();
  }

I'm considering using the WillPopScope widget but I'm not sure where it fits in the delegate.

Image:

enter image description here

2
  • hey, did you solve this? Commented Aug 6, 2021 at 15:33
  • Nope, no luck. It looks like it's a bug in the flutter sdk itself. Commented Aug 6, 2021 at 22:16

2 Answers 2

4

Seems this is not possible using the close method.

However you can do this using the .then method on showSearch since showSearch is a Future.

The then method registers callbacks to be called when this future completes.

showSearch(context: context, delegate: SearchDelegate()).then((value) async {
  await doSomething();
});
Sign up to request clarification or add additional context in comments.

Comments

1

Modify the below method in search delegate add willpop in build suggestion both back operations was working fine

 @override
  Widget buildSuggestions(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        // Handle back button press here within the search screen
        // You can execute custom logic and return true to allow popping, or false to prevent it
        bool shouldPop = await showConfirmationDialog(context);
        return shouldPop;
      },
      child: ListView(
        children: [
          ListTile(title: Text('Suggestion 1')),
          ListTile(title: Text('Suggestion 2')),
        ],
      ),
    );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.