Search code examples
flutterdartstream-builder

Flutter streamBuilder initalData not working as expected


I need to have a search function in page A. Once the search icon is pressed, it will retrieve the items from server and store to sink, then use stream to populate in listView.

But now it keeps stuck at ConnectionState.waiting when I not pressing search icon. How to make it display No item initally ? When the search icon is clicked, only it shows the output?

Container(
              child: StreamBuilder<List<ABC>>(
              initialData: null,
              stream: _bloc.displayStream,
              builder: (context, snapshot) {
                switch (snapshot.connectionState) {
                  case ConnectionState.active:
                    if (snapshot.data.isEmpty) {
                      return Center(
                          child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                            Icon(
                              Icons.format_list_bulleted,
                              size: 80,
                              color: Colors.orange,
                            ),
                            SizedBox(
                              height: 20,
                            ),
                            Text(
                              'No item',
                              style: TextStyle(fontSize: 18),
                            )
                          ]));
                    } else {
                      return Stack(
                        children: <Widget>[
                          _showListView(snapshot),
                        ],
                      );
                    }

                    break;

                  case ConnectionState.waiting:
                    return Center(
                      child: Image.asset(
                        'assets/loading.gif',
                        width: 200.0,
                        height: 200.0,
                      ),
                    );
                    break;

                  default:
                    return Text("Error");
                }
              },
            ))

Solution

  • add if (!snapshot.hasData) return LinearProgressIndicator(); in builder: (context, snapshot) {

    Reference firebase flutter codelab