Flutter Widgets

In flutter everything is a widget. Widget is a user interface. Application is the top level widget and UI is built using multiple child widgets. Each widget nests inside its parent and can receive context from the parent. Flutter has platform specific design widgets, MaterialApp for Android and CupertinoApp for iOS. You can understand the widget hierarchy from the diagram below.

Widget state

The framework introduces two types of widgets:

  1. Stateless widget
  2. Stateful widget

1) Stateless widget

The widgets whose properties do not change over time are called stateless widgets. Stateless widgets remain static throughout its lifecycle. The examples of stateless widgets are Text, Container, Row, Column etc..

Example:

class MyStatelessWidget extends StatelessWidget {     
  @override     
  Widget build(BuildContext context) {       
   return Container();     
  }   
 }   

2) Stateful widget

If the property of the widget changes based on user interaction or other factors then that widget is stateful widget. If the user clicks on a button whose label is date and it opens a calendar widget, after changing date from the calendar, the label of that button needs to be updated with a new date value. The value of date is the state for that button. When the date changes, the button needs to be rebuilt using setState() method.

Example:

class MyStatefulWidget extends StatefulWidget {   
  @override   
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();   
}    
  
class _MyStatefulWidgetState extends State<MyStatefulWidget> {   
  @override   
  Widget build(BuildContext context) {   
   return Container();   
  }   
}   

Stateful widget has two classes: State object and Widget. This widget does not have a build() method. It has createState() method, which returns a class that extends the Flutters State Class. Examples of stateful widgets are TextField, TextFormField, RaisedButton, InkWell, Checkbox etc..