Writing Better Flutter Widgets: How to Choose Between Classes and Functions

Jordan Goulet
8 min readApr 28, 2023

Widgets serve as the foundation of the user interface in Flutter and can be created using classes or functions. Deciding which one to use has its advantages and disadvantages, but classes are recommended by Flutter. Why is that? Let’s explore this further and provide some examples.

Class Widget VS Function Widget
Class Widget VS Function Widget

Class-Based Widget Coding

When coding a widget in a class in Flutter, you create a new class that extends the base widget class, such as StatelessWidget or StatefulWidget. This new class represents your custom widget, and you define its properties and behavior within the class definition.

Let’s say you want to make a list of buttons that can be clicked or unclicked. To keep track of which buttons were clicked, you need to give each button an ID. To achieve this, you can define a class called “ClassButton” that contains a Container with an OutlinedButton. This class has two variables that you will want to access later: _isClicked and id. When a button is clicked, the _isClicked variable changes its value. To retrieve the current value of this variable, you need to create a getter function. The id variable is final, which means you can access it without using a getter function.

class ClassButton extends StatefulWidget {
bool _isClicked = false;
final int id…

--

--

Jordan Goulet

Passionate software dev & Flutter enthusiast. Reach me at Twitter @jordan_goulet or @UbermenschDevel or visit https://ubermenschdeveloper.com!