Flutter Widgets

Learn how to use Flutter widgets

Flutter Widgets

Flutter widgets are the basic building blocks of the Flutter UI. They provide a way to describe the part of the user interface in the current configuration. There are many widgets in Flutter, each having its own functionality and purpose.

What are Flutter Widgets?

Widgets are the primary elements of a Flutter app's user interface. Each widget is an immutable declaration of part of the user interface and can include other widgets (which are also called "children"). Widgets are used for both layout and UI elements.

Types of Flutter Widgets

There are two types of widgets in Flutter: Stateless and Stateful.

Stateless Widgets

A stateless widget describes part of the user interface which can depend on configuration information in the widget itself and in the widget’s parent but does not depend on any runtime state.

Stateful Widgets

A stateful widget is dynamic. The user can interact with a stateful widget (by typing into a form, or moving a slider, for example), or it changes over time (perhaps a data feed causes the UI to update).

Flutter Widget Tree

Every Flutter app starts with a top-level widget that gets inflated into the window, which in turn can inflate additional sub-widgets. This creates a tree of widgets, also known as the widget tree.

Using Flutter Widgets

A Flutter app is itself a widget, and most widgets have a build() method. When called, it returns a Tree of widgets. You can visualize it as a widget tree. Flutter builds the UI by traversing this tree and drawing each widget.

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Welcome to Flutter'),
        ),
        body: Center(
          child: Text('Hello World'),
        ),
      ),
    );
  }
}

In this example, the MyApp widget is the root of your app. Inside MyApp, the MaterialApp widget is used. This is a widget that provides many features like navigation and theming. The Scaffold widget, which provides a default app bar, title, and body property which is populated with a Center widget. The Center widget then contains a Text child widget.

The widgets that you use in your apps are usually composed of many small, reusable widgets. This helps you maximize the reusability of code.

Conclusion

Widgets are the core concept of Flutter's UI framework. They allow you to create complex and custom designs with a small amount of code. Understanding how to use widgets effectively will be a critical part of becoming a proficient Flutter developer.