0% found this document useful (0 votes)
36 views28 pages

Widgets in Flutter

The document provides an overview of widgets in Flutter, explaining that each screen element is a widget and categorizing them into 14 functional groups. It distinguishes between two main types of widgets: Stateless and Stateful, detailing their characteristics and providing examples. Additionally, it includes implementation examples and guidance on creating custom widgets for enhanced code reusability and maintainability.

Uploaded by

leelarani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views28 pages

Widgets in Flutter

The document provides an overview of widgets in Flutter, explaining that each screen element is a widget and categorizing them into 14 functional groups. It distinguishes between two main types of widgets: Stateless and Stateful, detailing their characteristics and providing examples. Additionally, it includes implementation examples and guidance on creating custom widgets for enhanced code reusability and maintainability.

Uploaded by

leelarani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Widgets in Flutter

What are Widgets?

Each element on the 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
apps is a tree of widgets.

Category of Widgets

There are mainly 14 categories into which the flutter widgets are
divided. They are mainly segregated on the basis of the functionality
they provide in a flutter application.

Widgets Description

These are the set of widgets that make a Flutter app


Accessibility more easily accessible.

Animation and
These widgets add animation to other widgets.
Motion

Assets, Images, These widgets take charge of assets such as display


and Icons images and show icons.

These provide async functionality in the Flutter


Async application.

These are the bundle of widgets that are absolutely


Basics necessary for the development of any Flutter application.

Cupertino These are the iOS-designed widgets.


Widgets Description

This set of widgets provides input functionality in a


Input Flutter application.

Interaction These widgets are here to manage touch events and route
Models users to different views in the application.

This bundle of widgets helps in placing the other


Layout widgets on the screen as needed.

Material This is a set of widgets that mainly follow material


Components design by Google.

This is the set of widgets that apply visual changes to


Painting and their child widgets without changing their layout or
effects shape.

This provides scrollability of to a set of other widgets


Scrolling that are not scrollable by default.

This deals with the theme, responsiveness, and sizing of


Styling the app.

Text This displays text.


Types of Widgets

There are broadly two types of widgets in the flutter:

1. Stateless Widget
2. Stateful Widget

1. Stateless Widget:
Stateless Widget is a type of widget which once built , then it’s
properties and state can’t be changed. These widgets are immutable,
once created can’t be modified.
Note: These are used for static content or UI content that don’t need a
change after time.
Key Characterstics of Stateless Widgets are:
Immutable , No State and Lightweight.

Examples: Display Text , Icons, Images, etc.

2. Stateful Widget
Stateful Widgets is a type of widget that can change state. It can
maintain and update the appearance in the response to change in state.
Note: These are used for dynamic change in the properties and
appearance over the time.
Key Characterstics of Stateful Widgets are: Mutable State , State
Lifecycle and Dynamic Updates.

Examples: Buttons, Sliders, Text Fields, etc.


Implementation of Stateful and Stateless Widgets

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.
Example: The Layout Tree of basic app screen using Stateless Widgets
and Stateful Widgets

import 'package:flutter/[Link]';
void main() => runApp(const MyApp());
// MyApp is the root widget of the application
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: HomePage(),
);
}
}

// HomePage is the main screen of the app


class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);

@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {


@override
Widget build(BuildContext context) {
return Scaffold(
// Set the background color of the scaffold
backgroundColor: [Link],
appBar: AppBar(
// Set the background color of the app bar
backgroundColor: [Link],
// Set the title of the app bar
title: const Text("WELCOME"),
),
// The main body of the scaffold
body: const Center(
// Display a centered text widget
child: Text(
"Hello CSE!!",
// Apply text styling
style: TextStyle(
fontSize: 24, // Set font size
fontWeight: [Link], // Set font weight
),
),
),
);
}}
Output:
Flutter Widget types

In general Flutter widgets are classified into two categories,

1. Stateless Widget
2. Stateful Widget
However, you can find more classes in the hierarchy of Flutter sources.

 StatelessWidget: The widget does not require a mutable state.


 StatefulWidget: The widget has a mutable state i.e state information can be
read synchronously when it is built and it may change during the widget's
lifetime. Therefore it's essential to ensure that the state is promptly notified
when the change occurs using setState.
 ProxyWidget: The Widget has a child widget provided to it, instead of
building a new widget. It is useful as a base class for other widgets
like InheritedWidget and ParentDataWidget.
 RenderObjectWidget: It provides the configuration for
the RenderObjectElements, which wrap RenderObjects, that provide the
actual rendering of the application.
 InheritedWidget: It is a base class for widgets that efficiently propagates
information down the tree. To obtain the near instance of a particular type of
inherited widget from a build context,
use [Link].
 When referenced in this way, it causes the consumer to rebuild when the
inherited widget itself changes state.
 ParentDataWidget: It is a base class for a widget that
hooks ParentData information to children of RenderObjectWidgets. It is
used to provide a per-child configuration for RenderObjectWidgets with
more than one child.
 LeafRenderObjectWidget: It is a superclass for RenderObjectWidgets that
configure RenderObject subclasses that have no children.
 SingleChildRenderObjectWidget: It is a superclass
for RenderObjectWidgets that configure RenderObject subclasses that have a
single child slot.
 MultiChildRenderObjetWidget: It is a superclass
for RenderObjectWidgets that configure RenderObject subclasses that have a
single list of children.
 _NullWidget: Zero cost widget. Use it when you need a placeholder.

Most commonly used Flutter Widgets with the example

1. Appbar

A Material Design app bar. An app bar consists of a toolbar and potentially other
widgets, such as a TabBar and a FlexibleSpaceBar.

Example:

import 'package:flutter/[Link]';

void main() {

runApp(gfgApp()); //MaterialApp
}

5 MaterialApp gfgApp() {

6 return MaterialApp(

7 home: Scaffold(

8 appBar: AppBar(

9 title: const Text('My demo app'),

10 ), //AppBar

11 body: const Center(

12 child: Text(

13 'Hello Geeks',

14 style: TextStyle(fontSize: 24),

15 ), //Text

16 ), // center

17 ), //Scaffold

18 debugShowCheckedModeBanner: false, //Removing Debug Banner

19 );

20 }

Output:

2. Column

Layout a list of child widgets in the vertical direction.

Example:

1 import 'package:flutter/[Link]';

4 //function to trigger build

5 void main() {

6 runApp(const MyApp());

7 }
10 class MyApp extends StatelessWidget {

11 const MyApp({Key? key}) : super(key: key);

14 @override

15 Widget build(BuildContext context) {

16 return MaterialApp(

17 title: 'My Demo App',

18 theme: ThemeData(

19 primarySwatch: [Link],

20 ), // ThemeData

21 home: const MyHomePage(),

22 debugShowCheckedModeBanner: false,

23 ); // MaterialApp

24 }

25 }

28 class MyHomePage extends StatefulWidget {

29 const MyHomePage({Key? key}) : super(key: key);

32 @override

33 // ignore: library_private_types_in_public_api

34 _MyHomePageState createState() => _MyHomePageState();

35 }

38 class _MyHomePageState extends State

Output:

3. Container

A convenience widget that combines common painting, positioning, and sizing


widgets.

Example:

1 import 'package:flutter/[Link]';

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

5 class MyApp extends StatelessWidget {

6 const MyApp({Key? key}) : super(key: key);

8 @override

9 Widget build(BuildContext context) {

10 return MaterialApp(

11 home: Scaffold(

12 appBar: AppBar(

13 title: const Text("Container example"),


14 ),

15 body: Container(

16 child:const Text("Hello! i am inside a container!",

17 style: TextStyle(fontSize: 20)),

18 ),

19 ),

20 );

21 }

22 }

Output:

4. ElevatedButton

A Material Design elevated button. A filled button whose material elevates when
pressed.

Example:
1 ElevatedButton(

2 child: Text('Elevated Button'),

3 style: [Link](

4 primary: [Link],

5 ),

6 onPressed: () {},

7 ),

5. FlutterLogo

The Flutter logo, in the widget form. This widget respects the IconTheme.

Example:

1 import 'package:flutter/[Link]'

3 //Material design library

4 void main() {

5 runApp(

6 //widget tree starts here

7 MaterialApp(

8 home: Scaffold(

9 appBar: AppBar(

10 leading: Container(

11 color: [Link],

12 padding: [Link](3),

13 /** FlutterLogo Widget **/


14 child: FlutterLogo(

15 size: 10,

16 ), //FlutterLogo

17 ), //Container

18 title: Text('Hello Dev'),

19 backgroundColor: [Link][400],

20 centerTitle: true,

21 ), //AppBar

22 body: Center(

23 child: Container(

24 /** FlutterLogo Widget **/

25 child: FlutterLogo(

26 size: 300,

27 textColor: [Link],

28 style: [Link],

29 ), //FlutterLogo

30 ), //Container

31 ), //Center

32 ), //Scaffold

33 ), //MaterialApp

34 );

35 }


6. Icon

A Material Design icon.

Example:

1 import 'package:flutter/[Link]';

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

5 /// main application widget

6 class MyApp extends StatelessWidget {

7 const MyApp({Key? key}) : super(key: key);

9 static const String _title = 'Flutter Application';

10

11 @override

12 Widget build(BuildContext context) {

13 return MaterialApp(

14 title: _title,

15 home: Scaffold(

16 appBar: AppBar(title: const Text(_title)),

17 body: const MyStatelessWidget(),

18 ),

19 );

20 }
21 }

22

23 /// stateless widget that the main application instantiates

24 class MyStatelessWidget extends StatelessWidget {

25 const MyStatelessWidget({Key? key}) : super(key: key);

26

27 @override

28 Widget build(BuildContext context) {

29 return Column(

30 crossAxisAlignment: [Link],

31 children: const

Output:

7. Image
A widget that displays an image.

Example:

1 import 'package:flutter/[Link]';

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

5 class MyApp extends StatelessWidget {

6 @override

7 Widget build(BuildContext context) {

8 return MaterialApp(

9 home: Scaffold(

10 appBar: AppBar(

11 title: Text('Flutter Image Demo'),

12 ),

13 body: Center(

14 child: Column(

15 children:

8. Placeholder

A widget that draws a box that represents where other widgets will one day be
added.

Example:

1 SizedBox(height: 10),
2 Container(

3 height: 100,

4 child: Placeholder(color: RED),

5 ),

Output:

9. Row

Layout a list of child widgets in the horizontal direction.

Example:

1 import 'package:flutter/[Link]';

4 //function to trigger build


5 void main() {

6 runApp(const MyApp());

7 }

10 class MyApp extends StatelessWidget {

11 const MyApp({Key? key}) : super(key: key);

12

13

14 @override

15 Widget build(BuildContext context) {

16 return MaterialApp(

17 title: 'My Demo App',

18 theme: ThemeData(

19 primarySwatch: [Link],

20 ), // ThemeData

21 home: const MyHomePage(),

22 debugShowCheckedModeBanner: false,

23 ); // MaterialApp

24 }

25 }

26

27
28 class MyHomePage extends StatefulWidget {

29 const MyHomePage({Key? key}) : super(key: key);

30

31

32 @override

33 // ignore: library_private_types_in_public_api

34 _MyHomePageState createState() => _MyHomePageState();

35 }

36

37

38 class _MyHomePageState extends State

Output:

‍10. Text
A run of text with a single style.

Example:

1 import 'package:flutter/[Link]';

2 import 'package:flutter/[Link]';

3 import 'package:flutter/[Link]';

5 void main() {

6 runApp(MyApp());

7 }

9 class MyApp extends StatelessWidget {

10 @override

11 Widget build(BuildContext context) {

12 return MaterialApp(

13 home: Scaffold(

14 appBar: AppBar(

15 title: Text("Flutter Text Widget"),

16 ),

17 body: Text("This is text"),

18 ),

19 );

20 }

21 }
22

23

Output:
Flutter – Custom Widgets
What is a Custom Widget?
In Flutter, a custom widget refers to a user-defined widget that
encapsulates a specific set of functionalities or visual representations.

Custom widgets are the building blocks of a Flutter application. They


allow developers to create reusable UI components that can be used
throughout the application.

Why Use Custom Widgets?


1. Code Reusability
2. Maintainability
3. Consistent UI
4. Abstraction

Creating a custom widget in Flutter allows you to encapsulate reusable UI components and
enhance code maintainability. Below is an example of how to create a custom widget in Flutter.

Steps to Create a Custom Widget:

1. Create a new Dart file (e.g., custom_button.dart).


2. Define a Stateless or Stateful Widget inside that file.
3. Customize its appearance and behavior.
4. Use the custom widget in the main app.

Example: Custom Button Widget

Step 1: Create the Custom Widget (custom_button.dart)


import 'package:flutter/[Link]';

class CustomButton extends StatelessWidget {


final String text;
final VoidCallback onPressed;
final Color color;
const CustomButton({
Key? key,
required [Link],
required [Link],
[Link] = [Link],
}) : super(key: key);

@override
Widget build(BuildContext context) {
return ElevatedButton(
style: [Link](
backgroundColor: color,
padding: const [Link](horizontal: 20, vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: [Link](10),
),
),
onPressed: onPressed,
child: Text(
text,
style: const TextStyle(color: [Link], fontSize: 16),
),
);
}
}

Step 2: Use the Custom Widget in [Link]


import 'package:flutter/[Link]';
import 'custom_button.dart'; // Import the custom widget

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {


const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(title: const Text('Custom Widget Example')),
body: Center(
child: CustomButton(
text: "Click Me",
color: [Link],
onPressed: () {
print("Button Pressed!");
},
),
),
),
);
}
}

Output:
Key Takeaways

 Encapsulation: Makes your code modular and reusable.


 Customization: Allows dynamic styling and functionality.
 Reusability: Use the same widget multiple times in different parts of your app.

You might also like