The problem is very simple but I am unable to find a proper solution. I have a search screen and here is what I want to do.
- When screen is started for first time, I want to show a message in
Textwidget 'Your results will appear here'. - If user enters something in search box and press search, I want to show
CircularProgressIndicator. - And then, when API response is received, I want to either show a
ListVieworTextsaying 'Found nothing'. - If user searches something again, I want to show
CircularProgressIndicatoragain.
How can I achieve this behavior using Stream? Following is my code so far:
Widgets
StreamBuilder<List<Model>>(
stream: bloc.searchStream,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(
child: Text(
'Error occurred'
),
);
}
if (!snapshot.hasData) {
return Center(
child: Text(
'Your results will appear here'
),
);
}
if (snapshot.hasData && snapshot.data.length < 1) {
return Center(
child: Text(
'Found nothing'
),
);
}
// Where should I put my CircularProgressIndicator?
return ListView.separated(
itemCount: snapshot.data.length,
separatorBuilder: (context, index) => Divider(height: 1),
itemBuilder: (context, index) {
final item = snapshot.data[index];
return ItemWidget(item);
},
);
},
)
BLoC
final _searchStreamController = StreamController<List<Model>>();
Stream<List<Model>> get searchStream => _searchStreamController.stream;
void search(String searchTerm) async {
if (searchTerm.isEmpty) {
_searchStreamController.add(null);
return;
}
final client = HttpClient();
client.method = HttpMethod.POST;
client.endPoint = 'search';
client.addData('query', searchTerm);
try {
final responseStr = await client.execute();
final response = SearchResponse.fromJson(responseStr);
_searchStreamController.add(response.data);
} catch (e) {
_searchStreamController.addError(e);
}
}
I want to display CircularProgressIndicator every time search(String searchedTerm) function is called.
Thank you.
Here is what hack I had to do to achieve my requirements. If there is a better way to achieve this, please post an answer and I will mark it as correct.
Hack
And then use this
isProcessingproperty to check whether to showCircularProgressIndicatororListView. The rest of the code became:Widget
BLoC