User Feedback: Toasts / Snackbars

Good UX is all about being explicit about what's going on the in app when something updates. So the app should give users feedback in two places:

  • When you try to add a new dog but the form is wrong.
  • When you try to update a dog's rating but the form is wrong.

1. Feedback when Adding a New Dog

show snackbar on error screenshot

Only the submitPup function needs to be updated in your new_dog_form page.

First, some explanation that I glossed over in an earlier lesson:

In the build method on this page, the RaisedButton is wrapped in a Builder.

A builder creates a new scaffold under the hood. It's a new page, a new BuildContext, etc.

This new scaffold is necessary to show Snackbars (aka toasts on the web) because they are an element that is on another page, waiting to be called like any page would be.

The better way to do this would be to make a whole new stateless widget that's just a RaisedButton that shows a Snackbar on pressed.

Anyway, update your submitPup method:

  1. // new_dog_form.dart
  2. void submitPup(context) {
  3. if (nameController.text.isEmpty) {
  4. Scaffold.of(context).showSnackBar(
  5. SnackBar(
  6. backgroundColor: Colors.redAccent,
  7. content: Text('Pups neeed names!'),
  8. ),
  9. );
  10. } else {
  11. var newDog = Dog(nameController.text, locationController.text,
  12. descriptionController.text);
  13. Navigator.of(context).pop(newDog);
  14. }
  15. }

Now, try to submit a dog without a name.

2. Dialog Feedback when the Rating Form is wrong

This time, you'll implement a Dialog, which on mobile is just a modal.

Dialogs in Flutter give you access to actions so you can do things like ask user questions, get ratings, etc.

We're going to use what's called an AlertDialog, which alerts the users of something.

This goes in your _DogDetailPageState.

  1. // dog_detail_page.dart
  2. // Just like a route, this needs to be async, because it can return
  3. // information when the user interacts.
  4. Future<Null> _ratingErrorDialog() async {
  5. // showDialog is a built-in Flutter method.
  6. return showDialog(
  7. context: context,
  8. builder: (BuildContext context) {
  9. return AlertDialog(
  10. title: Text('Error!'),
  11. content: Text("They're good dogs, Brant."),
  12. // This action uses the Navigator to dismiss the dialog.
  13. // This is where you could return information if you wanted to.
  14. actions: [
  15. FlatButton(
  16. child: Text('Try Again'),
  17. onPressed: () => Navigator.of(context).pop(),
  18. )
  19. ],
  20. );
  21. },
  22. );
  23. }

Finally, update your updateRating method to handle that error:

  1. void updateRating() {
  2. if (_sliderValue < 10) {
  3. _ratingErrorDialog();
  4. } else {
  5. setState(() => widget.dog.rating = _sliderValue.toInt());
  6. }
  7. }

Now, when someone tries to give a dog a low rating, we'll stop them.

After all, they're good dogs.