0% found this document useful (0 votes)
15 views

Unit III - Chapter 6 - Using Common Widgets

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Unit III - Chapter 6 - Using Common Widgets

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Topics covered:

1. How to use basic widgets such as Scaffold, AppBar, SafeArea, Container,


Text, RichText, Column, and Row, as well as different types of buttons.

2. How to nest the Column and Row widgets together to create different UI
layouts.

3. Ways to include images, icons, and decorators

4. How to use text field widgets to retrieve, validate, and manipulate data

5. How to check your app’s orientation


What are the basic widgets?

1. Scaffold

The Scaffold widget in Flutter is used for creating a structured user


interface. It acts as the foundation for implementing Material Design
layouts in a Flutter app, providing a consistent framework to manage
various components like the AppBar, Drawer, BottomAppBar, and more.

Leading Icon

App Bar

App Bar Title

Body

Bottom Navigation
2. AppBar

An AppBar appears at the top of the screen in a Flutter app. It helps you
show information like the screen title, buttons for actions, and even a
navigation icon (like a back arrow).

Title:
The title is the text that we see in the center of the AppBar. It's a simple
Text widget. You can also replace it with other widgets, like a
DropdownButton if you need more interactive options.

Leading:
The leading property shows something on the left side, before the title.
It’s often an icon, like a back button or a menu button (like the three-line
"hamburger" icon for a navigation drawer). If you don’t define leading,
Flutter automatically shows a back arrow when there’s a previous
screen.

Actions:
The actions are a list of buttons or icons that appear beside the title.
These are usually interactive, such as search buttons, menu options, or
settings. You can have multiple icons or buttons here for different
actions.
FlexibleSpace:

FlexibleSpace in Flutter is a special area behind the AppBar that you can use to
add background elements, like images or other widgets, to enhance the visual
design of your app.

Think of it as a background layer for the AppBar, where you can place things
like:

 An image that stretches across the AppBar


 A gradient color
 Even other widgets, like icons or text
3. SafeArea

SafeArea in Flutter is a widget that ensures your app's content doesn't


get hidden behind things like notches, status bars, or rounded corners,
which are common on modern devices like the iPhone X or some
Android phones.

SafeArea automatically adds padding (extra space) around your app’s


content to make sure it stays visible and doesn't overlap with these
areas.

4. Container

A Container in Flutter is a flexible widget that you can use to customize


and style its content (child widget) or simply as an empty box to control
layout.

A Container acts like a box that can hold one child widget, and you can
change its appearance or position by applying various properties:

- Set it’s size (width and height)

- Add colors or backgrounds

- Add padding (space inside the container) or margin (space outside the
container).

- Align its content or even add borders and shadows.


5. Text Widget

The Text widget in Flutter is used to display a string of characters


(words, numbers, or symbols) on the screen. It is one of the most
frequently used to show some text, labels, titles, or messages.

6. RichText

The RichText widget in Flutter allows you to display text with multiple
styles in the same block of text. It’s useful when you want to apply
different formatting (like bold, color, size) to different parts of a
sentence or paragraph.

Normally, with the Text widget, we can only apply one style to the entire
text. But with RichText, we can apply different styles to different parts of
the text, all within a single widget. This is done using TextSpans (text
spans), which lets us break up the text and style each section
individually.
7. Column

A Column widget displays its children vertically. It takes a children


property con taining an array of List, meaning you can add multiple
widgets. The children align vertically without taking up the full height of
the screen. Each child widget can be embedded in an Expanded widget
to fill the available space. CrossAxisAlignment, MainAxisAlign ment, and
MainAxisSize can be used to align and size how much space is occupied
on the main axis.

8. Row

A Row widget displays its children horizontally. It takes a children


property containing an array of List. The same properties that the
Column contains are applied to the Row widget with the exception that
the alignment is horizontal, not vertical.
Nesting Row widgets inside a Column:
Nesting a Column widget inside a Row:
9. Buttons

There are a variety of buttons to choose from for different situations


such as RaisedButton, FloatingActionButton, FlatButton, IconButton,
PopupMenuButton, and ButtonBar.

RaisedButton:

Floating Action Button:


 Flat Button

Icon Button:

PopupMenu Button:

The PopupMenuButton is a Flutter widget that shows a menu (a list of


options) when the user taps it. It is commonly placed on the top-right
corner of an AppBar, where users can access additional actions or
filters.

How It Works:
 Displaying Menu Items:
o The menu items are created as a list of objects (like options with
text and icons).
o When the user taps the PopupMenuButton, the menu appears.
 Selecting an Item:
o When an item is selected, its value is passed to the onSelected
property to handle what happens next.
 Default Icon:
o If you don't specify an icon, it will show a default three-dot menu
icon.
ButtonBar:

The ButtonBar widget is a layout widget that arranges multiple buttons


horizontally in a row. It's often used to group buttons together in a horizontal
row within a dialog, card, or other widget. The ButtonBar ensures that the
buttons are properly aligned and spaced in a consistent manner.

Key Features:

 Alignment: Buttons can be aligned to the start, center, or end of the ButtonBar.
 Spacing: You can set the space between buttons using the buttonPadding property.

Properties:

1. children: A list of widgets (typically buttons) that will be displayed in the ButtonBar.
2. alignment: Controls the alignment of the buttons within the ButtonBar. It can be set to:
o MainAxisAlignment.start (left alignment)
o MainAxisAlignment.center (center alignment)
o MainAxisAlignment.end (right alignment)
o MainAxisAlignment.spaceEvenly, spaceBetween, spaceAround (to adjust
the spacing between buttons).
3. buttonPadding: Adds padding between each button to control the spacing between them.

Example Program:
import 'package:flutter/material.dart';

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('ButtonBar Example'),
),
body: Center(
child: ButtonBar(
alignment: MainAxisAlignment.center, // Align buttons at center
children: [
RaisedButton(
onPressed: () {
print('Button 1 clicked');
},
child: Text('Button 1'),
),
RaisedButton(
onPressed: () {
print('Button 2 clicked');
},
child: Text('Button 2'),
),
RaisedButton(
onPressed: () {
print('Button 3 clicked');
},
child: Text('Button 3'),
),
],
),
),
),
);
}
}

Designing of Basic App

1. Add an App Bar


a. Add leading icon button.
leading: IconButton(
icon: Icon(Icons.menu),
onPressed: () { },
),

b. Add a heading to an App Bar


i. Add title to an app bar
title: Text('Home')
ii. Remove title and Add FlexibleSpace

c. Add actions to an app bar. Actions property takes list of widgets


actions: [
IconButton( icon: Icon(Icons.search),
onPressed: () {},
),
IconButton( icon: Icon(Icons.more_vert),
onPressed: () {},
),
],

d. Add FlexibleSpace: without SafeArea


flexibleSpace: Icon(
Icons.photo_camera,
size: 75.0,
color: Colors.white70, ),

e. Add FlexibleSpace: with SafeArea


flexibleSpace: SafeArea(
child: Icon(
Icons.photo_camera,
size: 75.0,
color: Colors.white70, ),
),
f. Preferred Size:
What is PreferredSize?

PreferredSize is a widget in Flutter that allows you to set a specific


size (usually height or width) for a child widget that does not have
a defined size on its own. It’s most commonly used with widgets
like the AppBar or any other widget where Flutter doesn’t
automatically know the exact size you want it to be.

Why use PreferredSize?

Certain widgets in Flutter, like AppBar, have a default size. But if


you want to change their size (like making the app bar shorter or
taller), you use PreferredSize to tell Flutter the exact size you want
for that widget.
AssetBundle

AssetBundle is a class in Flutter that allows you to access and manage files that
are bundled with your app. These files can include images, fonts, JSON data, or
other assets that your app might need to work with.

In Flutter, assets are files that are bundled with the app and are included
during the build process. For example, you might include images that are used
within your app interface or configuration files like JSON that define app
settings.

How it Works:

 You declare your assets in the pubspec.yaml file of your Flutter project.
 The AssetBundle provides methods like load() to retrieve these assets
when needed.

Declaring Assets in pubspec.yaml:

Before using assets in your app, you need to declare them in the pubspec.yaml
file. This ensures that the assets are bundled with your app during the build
process.
Example:

Image Widget:

Display image from assets:


Display image from a URL:

Icon Widget:

The Icon widget in Flutter is used to display a graphical icon, usually as part of a
button, app bar, or within any UI component where you want to represent an
action or concept with a visual symbol.

Icons in Flutter come from the Material Design Icons library, and the Icon
widget is part of the flutter/material.dart package. You can use built-in icons or
customize the icon’s size, color, and style.
Decorators:

BoxDecoration is a class in Flutter that allows you to apply decoration to a


Container or a DecoratedBox widget. It is commonly used to style containers
with background colors, borders, shadows, gradients, and more. The
BoxDecoration provides flexibility to enhance the visual presentation of a
widget, making it a powerful tool for UI design.

Input Decoration:

InputDecoration is a class in Flutter used to customize the appearance of input


fields like TextField and TextFormField. It allows developers to style various
aspects of the input fields, such as labels, borders, hints, icons, and more. By
using InputDecoration, you can create visually appealing and user-friendly
forms.
Form Validation in Flutter

Form validation in Flutter is a process of checking the inputs provided by the


user to ensure they meet certain criteria before submission. For example,
validating that an email field has an "@" symbol or that a password meets a
minimum length. By validating form fields, you prevent users from submitting
incomplete or incorrect information, which is crucial for applications requiring
accurate data.

Using of formKey:

Helps us to keep track of the form's state and lets you control what happens
inside the form, such as checking if all fields are valid or saving the data.
What is a formKey?

The formKey is a unique identifier for a form in Flutter. It’s created using a
GlobalKey<FormState> object, which can be used to manage and control what
happens in the form.

Why is a formKey useful?

When you have a form with multiple fields, such as text fields for name, email,
or phone number, it’s important to know:

1. If all fields are filled out correctly (for example, the email field contains
a valid email).
2. When to save or submit the form after validation.

Using the formKey allows you to:

 Validate all the form fields at once.


 Access the state of the form from anywhere in the widget.

Usage:

1. Create the formKey using GlobalKey<FormState>. This will allow you to


access the form’s current state.

final GlobalKey<FormState> formKey = GlobalKey<FormState>();

Assign formKey to the Form widget: Inside the Form widget, set the key
property to this formKey.
Use formKey to validate or save: When the user clicks a submit button, we
can use the formKey to validate all fields and save the data.

why formKey is important:

1. Validation: The formKey allows us to validate the entire form at once.


With formKey.currentState.validate(), we can check if all fields meet
their validation criteria.

2. Saving Data: The formKey lets to save data from all fields in one go with
formKey.currentState.save(). This is particularly useful for complex
forms, allowing us to gather all input values and store them or process
them further.
3. Accessing Form State: The formKey gives access to the form’s internal
state (like knowing if a form is valid, or if data should be saved).

Device Orientation in Flutter

When creating a mobile app, adapting the layout based on the device’s
orientation, portrait (vertical) or landscape (horizontal), can improve usability.
There are two main ways in Flutter to detect and adapt to the orientation:

1. Using MediaQuery.of(context).orientation: This is the preferred


method. It directly provides the device's orientation, offering a reliable
result.

2. Using OrientationBuilder: This widget listens to changes in the available


space and gives an estimate of orientation, but it might not always
match the device's actual orientation unless placed as a parent widget in
the layout. OrientationBuilder can sometimes behave unpredictably if
it's inside other widgets that affect its available space.

Example: Changing UI Based on Orientation

In the following example, we’ll build a widget that displays different layouts
based on orientation:

 Portrait Mode: Displays a single icon.


 Landscape Mode: Displays two icons.

We will be using MediaQuery to detect orientation to demonstrate how it works


as a parent and child widget.

MediaQuery.

A Flutter tool that provides information about the device's display and its
current settings, such as screen size, pixel density, and—important for this
case—the orientation (portrait or landscape). Here’s how it works:
 MediaQuery: This is like a "context inspector" that tells us about the
device’s current layout information.

 MediaQuery.of(context).orientation: By using .orientation, we are


specifically asking for the current orientation of the device. This will
return either:

 Orientation.portrait when the device is held vertically.

 Orientation.landscape when the device is held horizontally.

In simple terms MediaQuery helps determine if the device is in portrait or


landscape mode, so we can use it to adjust the UI based on the orientation.

Orientation _orientation = MediaQuery.of(context).orientation;

 MediaQuery.of(context): This part accesses the MediaQuery object for


the given context. MediaQuery holds useful information about the
device and screen, like the screen size, pixel density, and, in this case,
orientation.

 .orientation: This property of MediaQuery gives us the device’s current


orientation, which will be either Orientation.portrait or
Orientation.landscape.

 Orientation _orientation: Here, we are defining a variable of type


Orientation and naming it _orientation. This variable will store the
current screen orientation value.

You might also like