How to show an error message in the UI in Flutter

Suragch
4 min readJan 25, 2023

A minimal example for a dialog or snackbar message

My friend asked me today how to show an error message in the UI when making an HTTP request. It was kind of hard to explain in a chat message, so this article is for him…and for you if you have the same question.

I won’t cover how to make the HTTP request, since I’ve written about that before in the article How to make HTTP requests in Flutter.

There are a few ways to show a message in the UI based on an HTTP response. In this article, I’ll use a callback function to get the job done. I’m assuming you have your UI code and your app logic in separate files. If you don’t, you should. I like to use the minimalist approach using Flutter’s own listeners and builder widgets.

Note: I’m not as familiar with how other state management solutions handle showing error messages. I believe the approach described here would work with Provider and Cubit, but I’m not sure if Bloc and Riverpod have their own custom solutions. Feel free to add a comment below if you know.

Create a callback variable

In your state management file, add a nullable callback function variable at the top of the class:

class HomeScreenManager {

// nullable callback function…

--

--