DEV Community

Beatriz Herculano
Beatriz Herculano

Posted on

Flutter and the basics on Widgets

What is Flutter?

Flutter is a SDK, created by Google, to build cross platform mobile apps and web applications.
Flutter é um SDK para desenvolvimento de aplicativos multiplataforma e aplicações web criada pela Google.

I started studding flutter without ever programing with components, because of that a lot of concepts were strange to me, mainly the concept and usage of Widgets

If you read the documentation for Flutter you will find the following definition for widgets:

Widgets describe what their view should look like given their current configuration and state. When a widget’s state changes, the widget rebuilds its description, which the framework diffs against the previous description in order to determine the minimal changes needed in the underlying render tree to transition from one state to the next.

This "explains" the concept of widget but not their usage. How it is used to build a flutter app?

Render Tree

The first thing to learn is that every visual component in a Flutter App is a widget or a Widget inside another:
If I want a centered text, I use a Text Widget inside a Center Widget. Actually, your entire app will be a Widget with others inside it.

When, for whatever reason, a widget have to load again, it will reload its children and itself. If you are worried about performance thinking about how you could rebuild your entire app, flutter was built thinking about it and there ar several guidelines and best practices to avoid a "render hell".

State and behavior

Ok, another thing about components, they can have behavior and a state.
The behavior can be simply described as what your widget do. If you are building a button that changes colors when you click it, there you have a method to do it, a behavior!

The state is what the behavior can change.

One very important concept is that you widget is in function of you state.

Going back to my button that changes color, the color can be represented as a variable in the state, if I click it the state changes and the appearance of the widget should change too.

The state is like a save file for a game, but for your widget.

You can bring this concept to any of the component style frameworks like React, Vue, SwiftUI and others.

How does state and behavior work in Flutter?

So the state can change, but is not necessary. Flutter separates widgets that changes and the ones that do not. They can be Stateless and Stateful.

This something that can be good or bad. This makes clear from the beginning how your widget will behave, if will be able to rebuild the render tree bellow it or if will be only modified if its parent do, but it can create verbose code and it will force you to adapt some code sometimes because suddenly you want behavior in that widget.

Another thing that this difference do is to block the "render hell", and can help you to use stateful widgets only when necessary.

Stateless Widgets

A Widget that is built once and cannot rebuild itself, only their parent can do it for them. A good example is the Text Widget:

Text( 'This is a immutable text',);
Enter fullscreen mode Exit fullscreen mode

This widget is once created and it has not more behavior than this.
I could stack stateless widgets to build my own for example.

Container(
    color: Colors.red,
    child: Center(
        child: Text( 'This is a immutable text',)
    ));
Enter fullscreen mode Exit fullscreen mode

This does not have a state or a behavior.

Stateful Widgets

This widget can change after is built and rebuild itself. A example is the raised button Widget, when the button is idle, it have the "raised" effect, during the click the effect is removed and if you let the click out the effect returns.

Another example is the following:

class Counter extends StatefulWidget {
  @override
  _CounterState createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
            FloatingActionButton(
              onPressed: _incrementCounter,
              tooltip: 'Increment',
              child: Icon(Icons.add),
            )
          ],
        ),
      ),
      color: Colors.white,
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

We have a widget that is visually composed by a Column, a Center, a Text and a FloatingActionButton, but it also has a state, that is a integer named counter that starts with 0.

When you press the FloatActionButton the _incrementCounter is called, this private method uses the setState and inside it changes the counter value, incrementing one to this number.

Now, in flutter, if you are inside a Stateful widget and you use the setState, you will rebuild the widget, because you are telling that you are changing the state, since your visual is a representation of the state it has to render again.

Finishing this up

I used React, Flutter and SwiftUI, learning the basics teach me that they are far more similar that you expect. You still is confused with this concept and you think flutter is making things worse I recommend you learn a little about SwiftUI, i used the (100 days of SwiftUI)[https://www.hackingwithswift.com/100/swiftui] to learn it.

Hope this can help if you want to learn Flutter and you can ping me for help.

Top comments (0)