I have Search Modal popup where the user can search and get results based on their search. However, since the class extends ModalRoute and not a StatefulWidget, calling setState does not re-render the build and the search results do no appear on the screen. Is there a way to update the state or re-render the screen without having to convert the class to a StatefulWidfet?
class JobSerachModal extends ModalRoute {
List<dynamic>? searchResults;
@override
Duration get transitionDuration => const Duration(milliseconds: 250);
@override
bool get opaque => false;
@override
bool get barrierDismissible => false;
@override
Color get barrierColor => Colors.black;
@override
String? get barrierLabel => null;
@override
bool get maintainState => true;
getSearch(String query) async {
var result = await SearchService().getAllPaged(query: query);
setState(() {
searchResults = result;
});
}
_onSearchChanged(String query) {
getSearch(query);
}
@override
Widget buildPage(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: TextField(
onChanged: _onSearchChanged,
autofocus: true,
),
),
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'))
],
),
const SizedBox(
height: 20,
),
...searchResults.map(
(search) {
return ListTile(
title: Text(search.title),
);
},
)
],
),
),
),
);
}
}
2
Answers
Use StatefulBuilder
Example:
Flutters
setState()
method is only available within aStatefulWidget
to rebuild the widgets when there is a state change. You can not callsetState()
method fromModalRoute
since it doesn’t exist there.You could use
ValueNotifier
andValueListenableBuilder
to achieve your goal.The Code: