ListView and Builder Methods

Right now you just have a card for your dog. It would be more useful to render all of them as a list.

One of the most important concepts in Flutter UI is rendering UI lists, which is often done in builder methods.

Builder methods essentially create a widget once for each piece of data in a Dart List.

First, create a new file called dog_list.dart.

1. DogList Class

  1. // dog_list.dart
  2. import 'package:flutter/material.dart';
  3. import 'dog_card.dart';
  4. import 'dog_model.dart';
  5. class DogList extends StatelessWidget {
  6. // Builder methods rely on a set of data, such as a list.
  7. final List<Dog> doggos;
  8. DogList(this.doggos);
  9. // First, make your build method like normal.
  10. // Instead of returning Widgets, return a method that returns widgets.
  11. // Don't forget to pass in the context!
  12. @override
  13. Widget build(BuildContext context) {
  14. return _buildList(context);
  15. }
  16. // A builder method almost always returns a ListView.
  17. // A ListView is a widget similar to Column or Row.
  18. // It knows whether it needs to be scrollable or not.
  19. // It has a constructor called builder, which it knows will
  20. // work with a List.
  21. ListView _buildList(context) {
  22. return ListView.builder(
  23. // Must have an item count equal to the number of items!
  24. itemCount: doggos.length,
  25. // A callback that will return a widget.
  26. itemBuilder: (context, int) {
  27. // In our case, a DogCard for each doggo.
  28. return DogCard(doggos[int]);
  29. },
  30. );
  31. }
  32. }

The only thing left to do is to actually use the DogList. Replace the DogCard in main with the DogList of Dog Cards.

First, import DogList to main.dart. Note that the dog_card.dart import is no longer needed.

  1. // main.dart
  2. import 'package:flutter/material.dart';
  3. import 'dog_list.dart';
  4. import 'dog_model.dart';

Then modify the build method in _MyHomePageState:

  1. // main.dart
  2. @override
  3. Widget build(BuildContext context) {
  4. return Scaffold(
  5. appBar: AppBar(
  6. title: Text(widget.title),
  7. backgroundColor: Colors.black87,
  8. ),
  9. body: Container(
  10. // Remove the DogCard Widget.
  11. // Instead, use your new DogList Class,
  12. // Pass in the mock data from the list above.
  13. child: Center( // Changed code
  14. child: DogList(initialDoggos), // Changed code
  15. ),
  16. ),
  17. );
  18. }

This is your app at this point with random doggos photos:

sample app