Flutter Widgets
In this section, we are going through the concept of a widget, the different kinds of widgets available, creating widgets, and their different types available. As we know everything is a widget in flutter.
Whenever you start coding in flutter you will be writing within a widget, using widgets and creating new widgets. The main purpose is to build an app with widgets.This will describe how your app looks and feels with their current configuration and state. When you make any changes in code, the widget rebuilds itself by calculating the difference between the previous and current widget to determine the minimal changes to be rendered in the UI.
Widgets are nested in the main widget to build the app. It means the root itself is a widget, and everything under it is a widget. For example, a sub widget or a list of widgets can display something, can define design, can handle interaction, etc.
The image below is a visual representation of the widget tree.
It works with the core concepts of programming languages like classes, interfaces and functions. Dart language does not support arrays but you can use lists instead. It supports collection, which is used to replicate the data structure such as List,Maps, generics, and optional typing.
The following example shows simple Dart programming.
Flutter widget Syntax looks like this:5>
Class ImageWidget extends StatelessWidget {
// Class Assets
}
Hello World Example
import 'package:flutter/material.dart';
class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This will be the homepage of the application.
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(this.title),
),
body: Center(
child: Text('Hello World'),
),
);
}
}
Types of Widget
Class ImageWidget extends StatelessWidget { // Class Assets }
import 'package:flutter/material.dart'; class MyHomePage extends StatelessWidget { MyHomePage({Key key, this.title}) : super(key: key); // This will be the homepage of the application. final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(this.title), ), body: Center( child: Text('Hello World'), ), ); } }
There are two categories of widgets:
- Visible (Output and Input)
- Invisible (Layout and Control)
Visible widget
The visible widgets are widgets which the user interacts with like input and output data. Some of the most used widgets are:
Text
The Text widget is used to display the text on the screen. We can align the text using textAlign property, and style property allows customization of the Text that includes font,font size, font weight, font style, letter spacing, color, and many more. We can use it like below code snippets.
Text( 'Hello, World!', textAlign: TextAlign.center, style: new TextStyle(fontWeight: FontWeight.bold), )
Button
This is the button widget that allows you to perform some action on pressing it. Flutter has different types of buttons like a FlatButton and a RaisedButton. It can be used like code snippets.
//FlatButton Example FlatButton( child: Text("Click here"), onPressed: () { // Do something here }, ), //RaisedButton Example RaisedButton( child: Text("Click here"), elevation: 6.0, onPressed: () { // Do something here }, ),
In the above example, the onPressed is the property/method which performs some action when the button is pressed, and elevation property is used to define how much it stands out.
Image
This widget is used for adding the images which can be fetched from multiple sources like from the asset folder. It provide constructors for adding image, which are given below:
- Image: This is the generic image loader, used by ImageProvider.
- asset: It loads images from your project directed folders.
- file: It loads images from the system.
- memory: It loads images from memory.
- network: It loads images from the network.
We can add images in the project by creating an assets folder, add an images folder where you keep your images and then add the below line in pubspec.yaml file.
assets: - assets/images/
Now, add the following line in the homepage widget.
Image.asset('assets/images/computer.png')
The source code for adding an image using the assets folder.
class MyHomePage extends StatelessWidget { MyHomePage({Key key, this.title}) : super(key: key); // Stateless Widget used as the home page final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(this.title), ), body: Center( child: Image.asset('assets/images/computer.png'), ), ); } }
Output
Icon
This widget is used for showing an icon in the Flutter. Check the example code that explains it more clearly.
Icon( Icons.add_circle_outline, size: 40.0, )
Invisible widget
These are widgets which are used for layout and control of UI. These widgets help control behavior and look on the screen of the widget. Some important widgets are:
Column
A column widget is used to set the layout in a vertical alignment. We can use mainAxisAlignment(Vertical Axis) and crossAxisAlignment(Horizontal Axis) properties to set the direction and spacing of the underline widgets.
Example
This code will demonstrate how we can set elements as a column.
Column( mainAxisAlignment: MainAxisAlignment.center, children:[ Text( "First Element", ), Text( "Second Element" ), RaisedButton( onPressed:()=>action(), child:Text(“Button), ), ], ),
Row
This widget is similar to column widget, but it sets the widgets horizontally instead of vertically.
Example
This code will demonstrate how we can set elements as a column.
Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children:[ new Text( "First", ), new Text( "Second" ), ], ),
Center
This widget centers its child widget.
Example
Center( child: new column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children:[ Center(child: Text( "Centered", ),), Text( "notCentered" ), ], ), ),
Padding
This widget adds padding to other widgets in specific directions or you can add padding to all the directions at once. To understand it check out the example below that gives the text widget padding of 10.0 in all directions.
Example
Padding( padding: const EdgeInsets.all(10.0), child: new Text( "TextWidget", ), ),
Scaffold
This widget provides a framework that allows you to add elements like AppBar, Floating Action Buttons, Drawers, Floating button,bottomNavBar etc.
Stack
Widget, which can be used for overlapping a widget over a different widget, such as a add a close icon on top of an image.
State Management Widget
There are two types of widgets in flutter:
- StatelessWidget
- StatefulWidget
StatefulWidget
A StatefulWidget has state information. It contains two classes: the state object which is the parent class and the widget. We can change the data in this class. This widget does not have a build() method. createState() method is used to return a class which extends the Flutters State Class. Examples of already defined Stateful Widgets are Checkbox,TextFields etc.
Example
class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State{ int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), ); } }
StatelessWidget
The StatelessWidget does not manage any state information so data is static. Some StatelessWidget examples are Text, Row, Column, Container, etc.
Example
class MyHomeWidget extends StatelessWidget { const MyHomeWidget ({ Key key }) : super(key: key); @override Widget build(BuildContext context) { return Container(color: const Color(0x0xFEEFE), child:Text(“Stateless widgets ”),); } }