4

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

usersina
  • 1,063
  • 11
  • 28

2 Answers2

1

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();
});
Mohammad Hammadi
  • 733
  • 2
  • 11
  • 34
0

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')),
        ],
      ),
    );
toyota Supra
  • 3,181
  • 4
  • 15
  • 19