Flutter Widgets
Flutter is Google’s UI toolkit for crafting beautiful, natively compiled iOS and Android apps from a
single code base. To build any application we start with widgets – The building block of flutter
applications. Widgets describe what their view should look like given their current configuration and
state. It includes a text widget, row widget, column widget, container widget, and many more.
Widgets: Each element on a screen of the Flutter app is a widget. The view of the screen completely
depends upon the choice and sequence of the widgets used to build the apps. And the structure of
the code of an apps is a tree of widgets.
• Flutter is a widget.
• Widgets are nested with each other to build the app. It means the
root of your app is itself a widget, and all the way down is a widget
also. For example, a widget can display something, can define design,
can handle interaction, etc.
We can create the Flutter widget like this:
Class ImageWidget extends StatelessWidget {
// Class Stuff
}
Types of Widget
• In Flutter, widgets can be grouped into multiple categories based on their
features, as listed below −
• Platform specific widgets
• Platform independent / basic widgets
• Layout widgets
• State maintenance widgets: Stateless Widget and Stateful Widget
• We can split the Flutter widget into two categories:
• Visible (Output and Input)
• Invisible (Layout and Control)
Platform specific widgets
• Flutter has widgets specific to a particular platform - Android or iOS.
• Android specific widgets are designed in accordance with Material
design guideline by Android OS. Android specific widgets are called
as Material widgets.
• iOS specific widgets are designed in accordance with Human Interface
Guidelines by Apple and they are called as Cupertino widgets.
• Some of the most used material widgets are as follows − • Some of the most used Cupertino widgets are as follows −
• Scaffold • CupertinoButton
• AppBar • CupertinoPicker
• BottomNavigationBar • CupertinoDatePicker
• TabBar • CupertinoTimerPicker
• TabBarView • CupertinoNavigationBar
• ListTile • CupertinoTabBar
• RaisedButton • CupertinoTabScaffold
• FloatingActionButton • CupertinoTabView
• FlatButton • CupertinoTextField
• IconButton • CupertinoDialog
• DropdownButton • CupertinoDialogAction
• PopupMenuButton • CupertinoFullscreenDialogTransition
• ButtonBar • CupertinoPageScaffold
• TextField • CupertinoPageTransition
• Checkbox • CupertinoActionSheet
• Radio • CupertinoActivityIndicator
• Switch • CupertinoAlertDialog
• Slider • CupertinoPopupSurface
• Date & Time Pickers • CupertinoSlider
• SimpleDialog
• AlertDialog
Layout widgets
• In Flutter, a widget can be created by composing one or more widgets. To
compose multiple widgets into a single widget, Flutter provides large
number of widgets with layout feature. For example, the child widget can
be centered using Center widget.
• Some of the popular layout widgets are as follows −
• Container − A rectangular box decorated using BoxDecoration widgets with
background, border and shadow.
• Center − Center its child widget.
• Row − Arrange its children in the horizontal direction.
• Column − Arrange its children in the vertical direction.
• Stack − Arrange one above the another.
Platform independent / basic widgets
Visible widget
• The visible widgets are related to the user input and output data.
• 1. Text
• 2. Button
• 3. Image
• 4. Icon
Text
• A Text widget holds some text to display on the screen. We can align
the text widget by using textAlign property, and style property allow
the customization of Text that includes font, font weight, font style,
letter spacing, color, and many more. We can use it as like below code
snippets.
• new Text(
• 'Hello, Javatpoint!',
• textAlign: TextAlign.center,
• style: new TextStyle(fontWeight: FontWeight.bold),
•)
• The most important properties of the Text widget are as follows −
• maxLines, int − Maximum number of lines to show
• overflow, TextOverFlow − Specify how visual overflow is handled
using TextOverFlow class
• style, TextStyle − Specify the style of the string using TextStyle class
• textAlign, TextAlign − Alignment of the text like right, left, justify, etc.,
using TextAlign class
• textDirection, TextDirection − Direction of text to flow, either left-to-
right or right-to-left
Text widget has a special constructor, Text.rich, which accepts the child of type TextSpan to specify
the string with different style.
widget is recursive in nature and it accepts TextSpan as its children. The sample code for this
purpose is as follows −
Text.rich( TextSpan( children: <TextSpanText widget has a special constructor, Text.rich, which
accepts the child of type TextSpan to specify the string with different style.
TextSpan widget is recursive in nature and it accepts TextSpan as its children. The sample code for
this purpose is as follows −
Text.rich(
TextSpan(
children: <TextSpan>[
TextSpan(text: "Hello ", style:
TextStyle(fontStyle: FontStyle.italic)),
TextSpan(text: "World", style:
TextStyle(fontWeight: FontWeight.bold)),
],
),
)>[ TextSpan(text: "Hello ", style: TextStyle(fontStyle: FontStyle.italic)),
TextSpan(text: "World", style: TextStyle(fontWeight: FontWeight.bold)), ], ), )
Button
• This widget allows you to perform some action on
click. Flutter does not allow you to use the Button 1.
widget directly; instead, it uses a type of buttons 2.//RaisedButton Example
like a FlatButton and a RaisedButton. We can use it 3.new RaisedButton(
as like below code snippets. 4. child: Text("Click here"),
• //FlatButton Example 5. elevation: 5.0,
• new FlatButton( 6. onPressed: () {
• child: Text("Click here"), 7. // Do something here
8. },
• onPressed: () {
9.),
• // Do something here In the above example, the onPressed property
• }, allows us to perform an action when you click
• ), the button, and elevation property is used to
change how much it stands out.
•
Image
• This widget holds the image which can fetch it from multiple sources like from the asset folder or directly from the URL. It provides
many constructors for loading image, which are given below:
• Image: It is a generic image loader, which is used by ImageProvider.
• asset: It load image from your project asset folder.
• file: It loads images from the system folder.
• memory: It load image from memory.
• network: It loads images from the network.
To add an image in the project, you need first to create an assets folder where you keep your images and then add the below l ine
in pubspec.yaml file.
• assets:
• - assets/
Now, add the following line in the dart file.
• Image.asset('assets/computer.png')
• A basic pubspec is generated when you create a new Flutter project. It's located at the top of the project tree and contains
metadata about the project that the Dart and Flutter tooling needs to know.
The easiest option to load and display an image in Flutter is by including the image as assets of the application and
load it into the widget on demand.
•Create a folder, assets inThe easiest option to load and display an image in Flutter is by
• including the image as assets of the application and load it into the widget on demand.
•Create a folder, assets in the project folder and place the necessary images.
•Specify the assets in the pubspec.yaml as shown below −
•flutter:
• assets:
• - assets/smiley.png
•Now, load and display the image in the application.
•Image.asset('assets/smiley.png') the project folder and place the necessary images.
•Specify the assets in the pubspec.yaml as shown below −
flutter: assets: - assets/smiley.png
•Now, load and display the image in the application.
Image.asset('assets/smiley.png')
The complete source code for adding an image is
shown below in the hello world example.
• class MyHomePage extends StatelessWidget {
• MyHomePage({Key key, this.title}) : super(key: key);
• // This widget is the home page of your application.
• final String title;
• @override
• Widget build(BuildContext context) {
• return Scaffold(
• appBar: AppBar(
• title: Text(this.title),
• ),
• body: Center( child: Image.asset('assets/computer.png'), ),
• );
• }
• }
• The most important properties of the Image widget are as follows −
• image, ImageProvider − Actual image to load
• width, double − Width of the image
• height, double − Height of the image
• alignment, AlignmentGeometry − How to align the image within its
bounds
Icon
Icon widget is used to display a glyph ("the specific shape, design, or representation of a
character") from a font described in IconData class. The code to load a simple email
icon is as follows −
Icon(Icons.email)
• This widget acts as a container for storing the Icon in the Flutter. The
following code explains it more clearly.
• new Icon(
• Icons.add,
• size: 34.0,
•)
The complete source code to apply it in hello
world application is as follows −
class MyHomePage extends StatelessWidget
{ MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override Widget build(BuildContext context)
{ return Scaffold(
appBar: AppBar(title: Text(this.title),),
body: Center( child: Icon(Icons.email)), ); } }
Invisible widget
• The invisible widgets are related to the layout and control of widgets.
It provides controlling how the widgets actually behave and how they
will look onto the screen.
•Align, which lets you arbitrarily position a child within itself, rather than just
centering it.
•Row, a widget that displays its children in a horizontal array.
•Column, a widget that displays its children in a vertical array.
•Container, a convenience widget that combines common painting, positioning, and
sizing widgets.
Some of the important types of these widgets are:
Column
• A column widget is a type of widget that arranges all its children's widgets in a vertical alignment. It provides spacing bet ween the
widgets by using the mainAxisAlignment and crossAxisAlignment properties. In these properties, the main axis is the vertical axis,
and the cross axis is the horizontal axis.
• Example
• The below code snippets construct two widget elements vertically.
• new Column(
• mainAxisAlignment: MainAxisAlignment.center,
• children: <Widget>[
• new Text(
• "VegElement",
• ),
• new Text(
• "Non-vegElement"
• ),
• ],
• ),
Row
• The row widget is similar to the column widget, but it constructs a widget horizontally rather than vertically. Here, the mai n axis is
the horizontal axis, and the cross axis is the vertical axis.
Example
• The below code snippets construct two widget elements horizontally.
• new Row(
• mainAxisAlignment: MainAxisAlignment.spaceEvenly,
• children: <Widget>[
• new Text(
• "VegElement",
• ),
• new Text(
• "Non-vegElement"
• ),
• ],
• ),
Center
This widget is used to center the child widget, which comes inside it. All the previous examples
contain inside the center widget.
• Example
• Center(
• child: new column(
• mainAxisAlignment: MainAxisAlignment.spaceEvenly,
• children: <Widget>[
• new Text( "VegElement", ),
• new Text( "Non-vegElement" ),
• ],
• ),
• ),
Padding
• This widget wraps other widgets to give them padding in specified
directions. You can also provide padding in all directions. We can
understand it from the below example that gives the text widget padding
of 6.0 in all directions.
• Example
• Padding(
• padding: const EdgeInsets.all(6.0),
• child: new Text(
• "Element 1",
• ),
• ),
Scaffold
• This widget provides a framework that allows you to add common
material design elements like AppBar, Floating Action Buttons,
Drawers, etc.
Stack
• It is an essential widget, which is mainly used for overlapping a
widget, such as a button on a background gradient.
State Management Widget
• In Flutter, there are mainly two types of widget:
• StatelessWidget
• StatefulWidget
StatefulWidget
• A StatefulWidget has state information. It contains mainly two
classes: the state object and the widget. It is dynamic because it can
change the inner data during the widget lifetime. This widget does
not have a build() method. It has createState() method, which
returns a class that extends the Flutters State Class. The examples of
the StatefulWidget are Checkbox, Radio, Slider, InkWell, Form, and
TextField.
• The InkWell class is a rectangular area of a Material widget that
responds to touch events by displaying a clipped splash. The
Material widget is responsible for the ink effects that are displayed
when a touch event occurs. The Material refers to the area where the
ink reactions are painted.
• Example
• class Car extends StatefulWidget {
• const Car({ Key key, this.title }) : super(key: key);
•
• @override
• _CarState createState() => _CarState();
• }
•
• class _CarState extends State<Car> {
• @override
• Widget build(BuildContext context) {
• return Container(
• color: const Color(0xFEEFE),
• child: Container(
• child: Container( //child: Container() )
• )
• );
• }
• }
StatelessWidget
• The StatelessWidget does not have any state information. It remains static
throughout its lifecycle. The examples of the StatelessWidget are Text, Row,
Column, Container, etc.
• Example
• class MyStatelessCarWidget extends StatelessWidget {
• const MyStatelessCarWidget ({ Key key }) : super(key: key);
•
• @override
• Widget build(BuildContext context) {
• return Container(color: const Color(0x0xFEEFE));
• }
•}
Example: The Layout Tree of basic app screen
using Stateless Widgets:
import 'package:flutter/material.dart';
// function to trigger build process
void main() => runApp(const GeeksforGeeks());
class GeeksforGeeks extends StatelessWidget {
const GeeksforGeeks({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.lightGreen,
appBar: AppBar(
backgroundColor: Colors.green,
title: const Text("GeeksforGeeks"),
), // AppBar
body: Container(
child: const Center(
child: Text("Hello Geeks!!"),
), // Center
), // Container
), // Scaffold
); // MaterialApp
}
}
Example: The Layout Tree of basic app screen using Stateful widgets.
This also produces the same results as the above code.
mport 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
// ignore: library_private_types_in_public_api
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.lightGreen,
appBar: AppBar(
backgroundColor: Colors.green,
title: const Text("GeeksforGeeks"),
), // AppBar
body: const Center(
child: Text("Hello Geeks!!"),
), // Container
), // Scaffold
);// MaterialApp
}
Description of the widgets used are as follows:
•
Scaffold – Implements the basic material design visual layout
structure.
App-Bar – To create a bar at the top of the screen.
Text To write anything on the screen.
Container – To contain any widget.
Center – To provide center alignment to other widgets.
Output:
The below image is a simple visual representation of the widget tree.
• import 'package:flutter/material.dart';
• class MyHomePage extends StatelessWidget
• {
• MyHomePage({Key key, this.title}) : super(key: key);
• final String title;
• @override
• Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(this.title), ),
body: Center( child: Text('Hello World‘), ),
); }
•}
• Here, we have created a new widget by extending StatelessWidget.
• Note that the StatelessWidget only requires a single method build to be implemented in its
derived class. The build method gets the context environment necessary to build the widgets
through BuildContext parameter and returns the widget it builds.
• In the code, we have used title as one of the constructor argument and also used Key as another
argument. The title is used to display the title and Key is used to identify the widget in the build
environment.
• Here, the build method calls the build method of Scaffold, which in turn calls the build method of
AppBar and Center to build its user interface.
• Finally, Center build method calls Text build method.
For a better understanding, the visual
representation of the same is given below −