Food Delivery App 11 - ListView with StreamBuilder API


Rendering a ListView with StreamBuilder

final Stream<List<int>> _posts = Stream<List<int>>.fromIterable(
  <List<int>>[
    List<int>.generate(10, (int i) => i),
  ],
);

That List of 10 items is used as the first value in a new Stream. From the subscription side of the Stream, there will be a single event with data that is a List of 10 items. I'm going with this pattern because Firestore will have snapshots with multiple documents.

The PostsList build method needs to be updated to consume the Stream and use a StreamBuilder:

@override
Widget build(BuildContext context) {
  return StreamBuilder<List<int>>(
    stream: posts,
    builder: (BuildContext context, AsyncSnapshot<List<int>> snapshot) {
      if (snapshot.hasError) {
        return Text('Error: ${snapshot.error}');
      }
       switch (snapshot.connectionState) {
        case ConnectionState.waiting:
          return const Text('Loading...');
        default:
          if (snapshot.data.isEmpty) {
            return const NoContent();
          }
          return _itemList(snapshot.data);
      }
    },
  );
}

The StreamBuilder takes a Stream and will then call the builder with an AsyncSnapshot. There are a couple of different states on this snapshot that need to be handled:

  • The first is checking to see if there has been an error. If there has been, render some error text.
  • Second, if the connection is waiting, show a loader while waiting for data to arrive.
  • Third, if there is no data, render the NoContent widget.
  • Finally if none of the previous cases are met, render the actual data.

Looking at the tests for PostList, all four of those scenarios are tested by creating different kinds of mock streams with the _postsStream helper.

Stream<List<int>> _postsStream(int count) {
  return Stream<List<int>>.fromIterable(
    <List<int>>[
      List<int>.generate(count, (int i) => i),
    ],
  );
}

Then I can test that the loading text is shown, followed a test that all the mocked items are rendered.

testWidgets('renders list of PostItems', (WidgetTester tester) async {
  // Build our app and trigger a frame.
  await tester.pumpWidget(MaterialApp(
    home: PostsList(_postsStream(5)),
  ));

  expect(find.text('Loading...'), findsOneWidget);

  await tester.pump(Duration.zero);

  expect(find.byType(PostItem), findsNWidgets(5));
});

To simulate the error case, I can throw an error on a Future and convert that to a stream.

testWidgets('renders NoContent widget', (WidgetTester tester) async {
  // Build our app and trigger a frame.
  await tester.pumpWidget(MaterialApp(
    home: PostsList(Future<List<int>>.error('Bad Connection').asStream()),
  ));

  await tester.pump(Duration.zero);
   expect(find.text('Error: Bad Connection'), findsOneWidget);
}); 

Comments

Popular posts from this blog

Flutter : Introduction

Flutter: State Management-2