Flutter Course (21 Blogs) Become a Certified Professional

Flutter Widgets – Streamline Your Mobile App Development Process

Last updated on Jan 10,2024 1.3K Views


Flutter is a popular open-source framework for mobile app development that enables developers to create high-performance, visually appealing, and responsive apps for Android and iOS platforms. One of the key features of Flutter is its use of widgets. In this blog, we will explore Flutter widgets in detail.

Content:

flutter widgets intro

What are Flutter Widgets?

Flutter widgets are the building blocks of a Flutter app’s user interface. They are the basic visual elements developers use to create user interfaces and define the app’s functionality.

A Flutter widget can be defined as a self-contained, reusable piece of code that describes how part of the user interface should be displayed. Widgets can be thought of as Lego blocks, which can be combined and arranged in many different ways to create complex user interfaces.

Difference Between Stateful and Stateless Widget

In the context of widget-based user interfaces frameworks like React, Flutter, and Angular, widgets can be categorized into two main types: stateful and stateless.

Stateless widgets do not have any internal state that can change over time. They are purely based on their input parameters, also called props or properties, and render their output based on those input parameters alone. Stateless widgets are easy to reason because they are deterministic and their output is predictable based on their input. Examples of stateless widgets include buttons, labels, and icons.

On the other hand, stateful widgets have an internal state that can change over time. These widgets have a state object that stores data that can be modified by the widget or external events such as user interactions. The output of a stateful widget can change based on both its input parameters and its internal state. Examples of stateful widgets include forms, lists, and sliders.

Stateful widgets can be more complex to reason about compared to stateless widgets because their output can change over time, and their behaviour can depend on multiple factors, including their input parameters and internal state. However, stateful widgets are necessary for creating dynamic and interactive user interfaces that respond to user interactions and external events

Here’s an example of a stateful and stateless widget:

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Stateless vs Stateful Widget Example',
home: Scaffold(
appBar: AppBar(
title: Text('Stateless vs Stateful Widget Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
MyStatelessWidget(),
SizedBox(height: 16),
MyStatefulWidget(),
],
),
),
),
);
}
}
class MyStatelessWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(16),
color: Colors.green,
child: Text(
'I am a stateless widget',
style: TextStyle(fontSize: 24, color: Colors.white),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
@override
 _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool _isPressed = false;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
setState(() {
_isPressed = !_isPressed;
}
);
},
child: Text(_isPressed ? 'Welcome to Edureka' : 'Sign In'),
);
}
}

stateful and stateless

Importance of widgets in Flutter

Widgets are a fundamental building block of Flutter’s user interface framework, and they play a crucial role in creating beautiful, responsive, and dynamic mobile apps. Here are some key reasons why widgets are important in Flutter:

  1. Reusability: Widgets in Flutter are highly reusable. Once you create a widget, you can use it in multiple places throughout your app. This saves time and effort and makes it easy to maintain your code.
  2. Customizability: Widgets can be easily customized to meet specific design requirements. You can modify a widget’s properties to change its appearance, or you can create custom widgets that meet unique design needs.
  3. Composability: Widgets can be combined to create more complex and dynamic user interfaces. You can nest widgets inside other widgets, allowing you to build complex layouts and interactions.
  4. Performance: Flutter’s widget-based architecture is highly performant. Because widgets are immutable, Flutter can optimize the rendering process by reusing existing widgets and minimizing unnecessary redraws.
  5. Separation of concerns: Flutter’s widget-based architecture allows you to separate the user interface from the business logic of your app. This makes it easier to maintain and update your codebase.

Widget tree and how it works in Flutter

The Widget tree is a hierarchical structure of widgets in Flutter, which defines the user interface of a Flutter app. Widgets are arranged in a tree-like structure, where each widget represents a particular component of the user interface.

flutter widget tree

In Flutter, widgets are either stateful or stateless. When a widget needs to update its user interface, it rebuilds itself and its child widgets. This process is called a “rebuild” or a “rerender”. The rebuild process can occur due to changes in the widget’s state, changes in its parent widget, or due to changes in the app’s data.

The widget tree starts with a single root widget, which is usually a MaterialApp or a CupertinoApp. The root widget can have child widgets, which can have their own child widgets, and so on. The Widget tree can be deep or shallow, depending on the complexity of the app’s user interface.

Each widget has a build method, which returns a widget that defines its user interface. The build method can create child widgets, which can have their own build methods and child widgets. This creates a hierarchy of widgets, with the root widget at the top and the leaf widgets at the bottom.

The Widget tree is important because it determines the layout and appearance of the user interface. Each widget can have its own set of properties, such as color, size, position, and behaviour. These properties are inherited by the child widgets, which can override them if needed.

So let’s see some of the Commonly Used Flutter Widgets:

Text Widget

widget is a graphical user interface (GUI) element that allows you to display text on a window or a web page. It is a standard UI element in most programming frameworks and libraries.

The Text widget typically provides a way to set the content of the text and display it on the screen. You can use it to display any type of text, including titles, subtitles, paragraphs, and lists.

In addition to displaying plain text, the Text widget also supports basic formatting options, such as changing the font size, colour, and style. This allows you to make the text more visually appealing and easier to read.

Some programming frameworks and libraries also provide advanced formatting options for the Text widget, such as adding hyperlinks, images, and tables.

Overall, the Text widget is a versatile and essential UI element that allows you to display text in a visually appealing and customisable way.

Here is an example of the Text Widget

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Text Widget Example')),
body: const Center(
child: Text(
'Welcome to edureka!',
style: TextStyle(fontSize: 24),
),
),
),
);
}
}

Flutter widgets text

Container Widget

In Flutter, the Container widget is used to create a rectangular visual element on the screen. The Container widget can be customized in many ways to achieve a desired look and feel. Here are some of the properties that can be used to customize the Container widget:

  1. Padding: This property can be used to add space around the content inside the container. Padding can be specified for all sides of the container or for specific sides.
  2. Margin: This property can be used to add space around the container itself. Margin can be specified for all sides of the container or for specific sides.
  3. Decoration: This property can be used to add a background color, border, or other visual effects to the container. Decoration can be specified using a BoxDecoration object.
  4. Alignment: This property can be used to specify how the content inside the container should be aligned. For example, the content can be aligned to the top, center, or bottom of the container.
  5. Width and Height: These properties can be used to specify the size of the container. The width and height can be specified in pixels, or as a percentage of the screen size.

By using these properties, you can create a container that looks exactly how you want it to. The Container widget is a versatile widget that can be used in many different ways, from creating a simple rectangular box to creating more complex layouts.

Let’s see an example here

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Container Widget Example'),
),
body: Center(
child: Container(
width: 200,
height: 200,
decoration: BoxDecoration(
color: Colors.blue
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(0, 3),
),
],
),
child: Center(
child: Text(
'edureka!',
style: TextStyle(
color: Colors.white,
fontSize: 150,
fontWeight: FontWeight.bold,
),
),
),
),
),
),
);
}
}

Flutter widgets cont

Image Widget

The Image widget is a graphical user interface (GUI) element that is used to display an image in a graphical application or a web page. The Image widget is commonly used in various types of software applications such as image editors, multimedia players, web browsers, and more.

The Image widget is typically a rectangular area in the UI where the image is displayed. It can be used to display images of various formats such as JPEG, PNG, GIF, BMP, and more. The widget can be configured to display images from a file, a URL, or an in-memory buffer.

In addition to displaying images, the Image widget can be configured to perform various other tasks such as scaling, cropping, rotating, and applying filters to the image. It can also be used to create animations by displaying a sequence of images in a loop.

The Image widget is widely used in web development and is a standard HTML element. In HTML, the Image widget is created using the <img> tag and can be configured with various attributes such as the source URL, the width and height of the image, and more.

In summary, the Image widget is a useful GUI element that can be used to display images in a software application or a web page. It can be configured to perform various tasks and is widely used in web development.

Here is an example of an Image Widget

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Image.network(
'https://d1jnx9ba8s6j9r.cloudfront.net/imgver.1680603302/img/site/edureka_1362740598.png',
fit: BoxFit.cover,
),
),
),
);
}
}

Flutter widget image

ListView Widget

A ListView widget is a common widget used in mobile and web applications to display a scrollable list of items. It is a powerful and flexible tool for showing data in a structured and organized way.

In Flutter, a ListView widget can display a list of widgets of any type, such as Text, Image, Icon, or even custom widgets. The ListView widget automatically scrolls the list of items when it is longer than the available screen space, making it easy for users to navigate through a large number of items.

There are two main types of ListView widgets in Flutter:

  1. ListView.builder: This is used when you have a large or infinite list of items. It dynamically creates widgets as they are scrolled into view, allowing for efficient memory usage.
  2. ListView.separated: This is similar to ListView.builder, but adds a separator widget between each item in the list.

Both ListView widgets can be customized to fit your app’s specific needs, including changing the scrolling direction, adding padding or margins, and customizing the appearance of individual items in the list.

Overall, ListView is a versatile and powerful widget that can help you create an intuitive and engaging user interface in your Flutter app.

Let’s see an example here

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final List<String> items = ['Flutter', 'Android', 'Python', 'Data Science', 'Cloud Computing'];
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primaryColor: Colors.blue,
accentColor: Colors.blueAccent,
),
home: Scaffold(
appBar: AppBar(
title: Text('ListView Widget Example'),
),
body: ListView.separated(
separatorBuilder: (context, index) => Divider(),
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
child: Text('${index + 1}'),
),
title: Text(
items[index],
style: TextStyle(fontSize: 18.0),
),
trailing: Icon(Icons.arrow_forward),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => DetailScreen(item: items[index])),
);
},
);
},
),
),
);
}
}
class DetailScreen extends StatelessWidget {
final String item;
DetailScreen({Key? key, required this.item}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Detail Screen'),
),
body: Center(
child: Text(item, style: TextStyle(fontSize: 24.0)),
),
);
}
}

Flutter Widgets list

Find out our Flutter Course in Top Cities

IndiaOther Countries
Flutter Training in Chennai Flutter Course in Australia
Flutter Course in BangaloreFlutter Course in Canada
Flutter Training in HyderabadFlutter Course in London

TextField Widget

In the context of user interface development, a widget is a graphical element that can be interacted with by the user. The TextField widget is a type of widget that allows the user to enter text input via a keyboard or other input device.

In most user interface toolkits, a TextField widget will typically consist of a rectangular box with a cursor indicating the current position of the text input. The user can click or tap on the widget to give it focus and start entering text.

Some common features of TextField widgets include the ability to select, copy, cut, and paste text, as well as support for various input methods such as typing, voice input, and handwriting recognition.

In addition to these basic features, TextField widgets can often be customized with various options such as placeholder text (i.e., text that appears in the widget before the user starts typing), input validation (i.e., ensuring that the input meets certain criteria such as length or format), and autocomplete (i.e., suggesting possible completions for the input based on previously entered text or another context).

Overall, TextField widgets are a fundamental tool for creating user-friendly input forms and other interactive elements in modern user interfaces.

Here is the example for the TextField Widget

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My App',
home: Scaffold(
appBar: AppBar(
title: Text('My TextField Example'),
),
body: Center(
child: Padding(
padding: EdgeInsets.all(16.0),
child: MyTextField(),
),
),
),
);
}
}
class MyTextField extends StatefulWidget {
const MyTextField({Key? key}) : super(key: key);
@override
_MyTextFieldState createState() => _MyTextFieldState();
}
class _MyTextFieldState extends State<MyTextField> {
final TextEditingController _controller = TextEditingController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(
controller: _controller,
decoration: InputDecoration(
labelText: 'Enter your name',
hintText: 'e.g John Doe',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
onChanged: (value) {
// Do something with the user input
print('User input: $value');
},
);
}
}

jflutter widget textfield
Conclusion

Flutter widgets are an essential part of building Flutter apps. They are reusable building blocks that enable developers to create high-performance, visually appealing, and responsive apps. In this blog, we explored the two types of Flutter widgets: Stateless widgets and Stateful widgets, along with some commonly used widgets in Flutter. By using these widgets effectively, developers can create beautiful and functional apps with ease.

This brings us to the end of this blog on Flutter Widget. Hope I was able to explain Flutter Widget and why you should use it clearly. 

If you want to get trained in Flutter and wish to develop interesting UI’s on your own, then check out the best Flutter Course offered by Edureka, Our Flutter Application Development Certification Course Syllabus, curated by industry experts that will help you to master all its concepts.

Got a question for us? Please mention it in the comments section and we will get back to you.

Comments
0 Comments

Join the discussion

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.