Home > Net >  Flutter Stream-Builder returning blank screen at app launch only
Flutter Stream-Builder returning blank screen at app launch only

Time:02-19

I am learning Flutter and I am trying to create a sample todo application to practice what I have learnt so far.

I am experiencing a problem with StreamBuilder showing always snapshot.data null at (basically a blank page) but only at first boot of the application, meaning that as soon as I do any action, like opening the drawer, the data appears and is not null anymore. I have no idea on what I am doing wrong, so I am asking for some help so that I can understand what it is going on.

Here is a screenshot of the problem

here at boot: image of the app at boot with only loading but has data

here after just opening the drawer: opening the drawer you see the element appearing

Of course now I am done with blah blah and images and here is the code, if you need more, I can provide (it is also published on GitHub)

Widget _buildTodoList(BuildContext context) {
    return StreamBuilder<List<Todo>>(
      stream: Provider.of<ITodoRepository>(context, listen: true).watchTodos(),
      builder: (context, AsyncSnapshot<List<Todo>> snapshot) {
        if ((snapshot.connectionState == ConnectionState.active || snapshot.connectionState == ConnectionState.done) && snapshot.data != null) {
          debugPrint("SB Initialized");
          final todos = snapshot.data ?? [];
          return ListView.builder(
            itemCount: todos.length,
            itemBuilder: (BuildContext context, int index) {
              final todo = todos[index];
              return Padding(
                padding: const EdgeInsets.only(right: 16.0, left: 16.0),
                child: SizedBox(
                  height: 70,
                  child: _buildSlidable(context, todo),
                ),
              );
            },
          );
        } else {
          return const Center(child: CircularProgressIndicator(),);
        }
      },
    );
  }

Here the repository:

@override
  Stream<List<Todo>> watchTodos() {
    return db.watchTodos().map((event) => event.map((e) => e.asTodoModel).toList());
  }

and here the Drift database code:

Stream<List<DriftTodo>> watchTodos() {
    return select(driftTodos).watch();
  }

Is there something I am doing wrong? I thank you a ton in advance

CodePudding user response:

it is good practice to return an error in else if then return progress indicator()

 if (snapshot.hasData) {
                return Text(snapshot.data!.title);
              } else if (snapshot.hasError) {
                return Text('${snapshot.error}');
              }

              // By default, show a loading spinner.
              return const CircularProgressIndicator();
            },
          ),
  • Related