Understanding Widget

widget

Widget Architecture | image source from Flutter Dev

Widget is a basic building block on flutter code. For example, button is one of widget component within apps. So widget can create "structural element","stylistic element(font / color)", and "layout" etc.

Let's say you build app screen. App screen have lots of UI element such as card,button and tab etc. These are all widgets. It become Tree of Widget just like above diagram.

import 'package:flutter/material.dart';

void main() {
  runApp(
    Center(
      child: Text(
        'Hello, world!',
        textDirection: TextDirection.ltr,
        style: TextStyle(
          fontSize: 32,
          color: Colors.black87,
        ),
      ),
    ),
  );
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Let's take a part of code with line by line. runApp() is root of widget tree. This widget tree consists of two widget, one is Center() the other is Text()

"A widget’s main job is to implement a build function, which describes the widget in terms of other, lower-level widgets." [cited from flutter dev site]

widget_component

Types of Widget

  1. StatelessWidget StatelessWidget is immutable once it is built.

  2. StatefulWidget StatefulWidget is changed dynamically and can be redrawn within life cycle

Element of Widget

Flutter provide basic element of widget.

  • Text
  • Row, Column
  • Stack
  • Container

Text is widget that create styled text element in the screen.

Row, Column is widget that generate flexible layout for Row(horizontal) and Column(vertical) element in the screen.

Stack is widget that stack widget on the top of each.

Container is widget that create rectangular visual element. Container can be decorated with "BoxDecoration" such as a background, a border, or a shadow.