Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views54 pages

bim30603labavtivity5

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 54

BIM30603 Lab Activity #5

BIM30603 – MOBILE APPLICATION DEVELOPMENT


Semester 1 Session 2024/2025
Lab Activity #5
Title : Flutter Basics
Outcomes : At the end of the lab session, students should be able to:
• Understand and implement widgets in Flutter.
• Practice creating and using widgets.
Week : 7
Duration : 2-Hours
Submission : No submission needed.

INSTRUCTIONS

1. This is an individual Lab Activity.


2. Complete all following task.

Implementation of Stateful and Stateless Widgets


Below is the Image with showing the Layout Tree:

1
BIM30603 Lab Activity #5

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:
import 'package:flutter/material.dart';

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: Colors.lightGreen,
appBar: AppBar(
// Set the background color of the app bar
backgroundColor: Colors.green,
// Set the title of the app bar
title: const Text("BIM30603"),
),
// The main body of the scaffold
body: const Center(
// Display a centered text widget
child: Text(
"Hello Semua!!",
// Apply text styling
style: TextStyle(
fontSize: 24, // Set font size

2
BIM30603 Lab Activity #5

fontWeight: FontWeight.bold, // Set font weight


),
),
),
);
}
}

Example: The Layout Tree of basic app screen using Stateful Widgets. This also produces the same
results as the above code.
import '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("BIM30603"),
), // AppBar
body: const Center(
child: Text("Hello Semua!!"),
), // Container
), // Scaffold
);// MaterialApp
}
}

3
BIM30603 Lab Activity #5

Output:

4
BIM30603 Lab Activity #5

Container class in Flutter


Container class in flutter is a convenience widget that combines common painting, positioning, and sizing
of widgets. A Container class can be used to store one or more widgets and position them on the screen
according to our convenience. Basically, a container is like a box to store contents. A basic container
element that stores a widget has a margin, which separates the present container from other contents.
The total container can be given a border of different shapes, for example, rounded rectangles, etc. A
container surrounds its child with padding and then applies additional constraints to the padded extent
(incorporating the width and height as constraints, if either is non-null).

Constructor of Container Class

Syntax:
Container({Key key,
AlignmentGeometry alignment,
EdgeInsetsGeometry padding,
Color color,
Decoration decoration,
Decoration foregroundDecoration,
double width,
double height,
BoxConstraints constraints,
EdgeInsetsGeometry margin,
Matrix4 transform,
Widget child,
Clip clipBehavior: Clip.none});

5
BIM30603 Lab Activity #5

Properties of Container Class:

1. child: Container widget has a property ‘child:’ which stores its children. The child class can be any
widget. Let us take an example, taking a text widget as a child.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Container example"),
),
body: Container(
child:const Text("Hello! i am inside a container!",
style: TextStyle(fontSize: 20)),
),
),
);
}
}

Output:

6
BIM30603 Lab Activity #5

2. color: The color property sets the background color of the entire container. Now we can visualize the
position of the container using a background color.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Container example"),
),
body: Container(
color: Colors.purple,
child: const Text("Hello! i am inside a container!",
style: TextStyle(fontSize: 20)),
),
),
);
}
}

Output:

7
BIM30603 Lab Activity #5

3. height and width: By default, a container class takes the space that is required by the child. We can
also specify the height and width of the container based on our requirements.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Container example"),
),
body: Container(
height: 200,
width: double.infinity,
color: Colors.purple,
child: const Text("Hello! i am inside a container!",
style: TextStyle(fontSize: 20)),
),
),
);
}
}

Output:

8
BIM30603 Lab Activity #5

4. margin: The margin is used to create an empty space around the container. Observe the white space
around the container. Here EdgeInsets.geometry is used to set the margin .all() indicates that the margin
is present in all four directions equally.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Container example"),
),
body: Container(
height: 200,
width: double.infinity,
color: Colors.purple,
margin: const EdgeInsets.all(20),
child: const Text("Hello! i am inside a container!",
style: TextStyle(fontSize: 20)),
),
),
);
}
}

Output:

9
BIM30603 Lab Activity #5

5. padding: The padding is used to give space from the border of the container from its children.
Observe the space between the border and the text.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Container example"),
),
body: Container(
height: 200,
width: double.infinity,
color: Colors.purple,
margin: const EdgeInsets.all(20),
padding: const EdgeInsets.all(30),
child: const Text("Hello! i am inside a container!",
style: TextStyle(fontSize: 20)),
),
),
);
}
}

Output:

10
BIM30603 Lab Activity #5

6. alignment: The alignment is used to position the child within the container. We can align in different
ways: bottom, bottom center, left, right, etc. here the child is aligned to the bottom center.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Container example"),
),
body: Container(
height: 200,
width: double.infinity,
color: Colors.purple,
alignment: Alignment.bottomCenter,
margin: const EdgeInsets.all(20),
padding: const EdgeInsets.all(30),
child: const Text("Hello! i am inside a container!",
style: TextStyle(fontSize: 20)),
),
),
);
}
}

Output:

11
BIM30603 Lab Activity #5

7. Decoration: The decoration property is used to decorate the box(e.g. give a border). This paints
behind the child. Whereas foreground Decoration paints in front of a child. Let us give a border to the
container. But, both color and border color cannot be given.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Container example"),
),
body: Container(
height: 200,
width: double.infinity,
//color: Colors.purple,
alignment: Alignment.center,
margin: const EdgeInsets.all(20),
padding: const EdgeInsets.all(30),
decoration: BoxDecoration(
border: Border.all(color: Colors.black, width: 3),
),
child: const Text("Hello! i am inside a container!",
style: TextStyle(fontSize: 20)),
),
),
);
}
}

Output:

12
BIM30603 Lab Activity #5

8. Transform: This property of the container helps us to rotate the container. We can rotate the
container in any axis, here we are rotating in the z-axis.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Container example"),
),
body: Container(
height: 200,
width: double.infinity,
color: Colors.purple,
alignment: Alignment.center,
margin: const EdgeInsets.all(20),
padding: const EdgeInsets.all(30),
transform: Matrix4.rotationZ(0.1),
child: const Text("Hello! i am inside a container!",
style: TextStyle(fontSize: 20)),
),
),
);
}
}

Output:

13
BIM30603 Lab Activity #5

9. Constraints: When we want to give additional constraints to the child, we can use this property.

10. ClipBehaviour: This property takes in Clip Enum as the object. This decides whether the content
inside the container will be clipped or not.

11. Foreground Decoration: This parameter holds Decoration class as the object. It controls the
decoration in front of the Container widget.

Note: There can be many more operations that can be performed to container class. Moreover, the
container class is used often while developing flutter applications. This is just basics to get started with.
Find more properties and attributes in the given link which is the official flutter documentation.

14
BIM30603 Lab Activity #5

Scaffold class in Flutter with Examples

Scaffold is a class in flutter which provides many widgets or we can say APIs like Drawer, Snack-Bar,
Bottom-Navigation-Bar, Floating-Action-Button, App-Bar, etc. Scaffold will expand or occupy the whole
device screen. It will occupy the available space. The Scaffold will provide a framework for implementing
the basic material design layout of the application.

The class Hierarchy is as follows:

Object

↳ Diagnosticable

↳ Diagnosticable Tree

↳ Widget

↳ StateFul Widget

↳ Scaffold

The constructor of the Scaffold class:


const Scaffold({
Key key,
this.appBar,
this.body,
this.floatingActionButton,
this.floatingActionButtonLocation,
this.floatingActionButtonAnimator,
this.persistentFooterButtons,
this.drawer,
this.endDrawer,
this.bottomNavigationBar,
this.bottomSheet,
this.backgroundColor,
this.resizeToAvoidBottomPadding,
this.resizeToAvoidBottomInset,
this.primary = true,
this.drawerDragStartBehavior = DragStartBehavior.start,
this.extendBody = false,
this.drawerScrimColor,
})

15
BIM30603 Lab Activity #5

Properties of Scaffold Class


Description
app-Bar It displays a horizontal bar which mainly placed at the top of
the Scaffold. appBar uses the widget AppBar which has its own
properties like elevation, title, brightness, etc.
body It will display the main or primary content in the Scaffold. It is
below the appBar and under the floatingActionButton. The widgets
inside the body are at the left-corner by default.
floatingActionButton FloatingActionButton is a button that is placed at the right bottom
corner by default. FloatingActionButton is an icon button that floats
over the content of the screen at a fixed place. If we scroll the page
its position won’t change, it will be fixed.
drawer drawer is a slider menu or a panel which is displayed at the side of
the Scaffold. The user has to swipe left to right or right to left
according to the action defined to access the drawer menu. In the
Appbar, an appropriate icon for the drawer is set automatically at a
particular position. The gesture to open the drawer is also set
automatically. It is handled by the Scaffold.
bottomNavigationBar bottomNavigationBar is like a menu at the bottom of the Scaffold.
We have seen this navigationbar in most of the applications. We
can add multiple icons or texts or both in the bar as items.
backgroundColor used to set the color of the whole Scaffold widget.
floatingActionButtonAnimator used to provide animation to move floatingActionButton.
primary to tell whether the Scaffold will be displayed or not.
drawerScrimColor used to define the color for the primary content while a drawer is
open.
bottomSheet This property takes in a widget (final) as the object to display it at
the bottom of the screen.
drawerDragStartBehaviour This property holds DragStartBehavior enum as the object to
determine the drag behaviour of the drawer.
drawerEdgeDragWidth This determines the area under which a swipe or a drag will result
in the opening of the drawer. And it takes in a double as the object.
drawerEnableOpenGesture This property holds in a boolean value as the object to determine
the drag gesture will open the drawer or not, by default it is set to
true.
endDrawer The endDrawer property takes in a widget as the parameter. It is
similar to the Drawer, except the fact it opens in the opposite
direction.
endDrawerEnableOpenGesture Again this property takes in a boolean value as the object to
determine whether the drag gesture will open the endDrawer or
not.
extendBody The extendBody property takes in a boolean as the object. By
default, this property is always false but it must not be null. If it is
set to true in the presence of
a bottomNavigationBar or persistentFooterButtons, then the height

16
BIM30603 Lab Activity #5

of these is added to the body and they are shifted beneath the
body.
extendBodyBehindAppBar This property also takes in a boolean as the object. By default, this
property is always false but it must not be null. If it is set to true
the app-Bar instead of being on the body is extended above it and
its height is added to the body. This property is used when the
color of the app-Bar is not fully opaque.
floating Action Button Location This property is responsible for the location of the floating Action
Button.
persistent Footer Button This property takes in a list of widgets. Which are usually buttons
that are displayed underneath the scaffold.
resize To Avoid Bottom Insets This property takes in a Boolean value as the object. If set to true
then the floating widgets on the scaffold resize themselves to avoid
getting in the way of the on-screen keyboard.

Example of Scaffold Class in Flutter

1. app-Bar

Below is the example of app-Bar:


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("BIM30603"),
),
),
);
}

Output:

17
BIM30603 Lab Activity #5

2. body

Below is the example of body:


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("BIM30603"),
),
body: const Center(
child: Text(
"Welcome to FSKTM!!!",
style: TextStyle(
color: Colors.black,
fontSize: 40.0,
),
),
),
),
);
}

In this example, we have displayed the text Welcome to FSKTM!!! in the body. We have displayed the
text in the center of the page using Center widget. For styling the text, we have used TextStyle widget.

Output:

18
BIM30603 Lab Activity #5

3. floatingActionButton

Below is the implementation of floatingActionButton:


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("BIM30603"),
),
body: const Center(
child: Text(
"Welcome to FSKTM!!!",
style: TextStyle(
color: Colors.black,
fontSize: 40.0,
),
),
),
floatingActionButton: FloatingActionButton(
elevation: 10.0,
child: const Icon(Icons.add),
onPressed: () {
// action on button press
},
),
),
);
}
}

Here the elevation property is used to give a shadow effect to the button. Icon is used to put the icon of
the button using some preloaded icons in flutter SDK. The onPressed() is a function that will be called
when the button is pressed and the statements inside the function will be executed.

Output:

19
BIM30603 Lab Activity #5

4. drawer

Below is the Example of drawer:


drawer: Drawer(
child: ListView(
children: const <Widget>[
DrawerHeader(
decoration: BoxDecoration(
color: Colors.green,
),
child: Text(
'BIM30603',
style: TextStyle(
color: Colors.black,
fontSize: 24,
),
),
),
ListTile(
title: Text('Item 1'),
),

20
BIM30603 Lab Activity #5

ListTile(
title: Text('Item 2'),
),
],
),
),

As a parent widget we took ListView and inside it, we divided the panel into two parts, Header and
Menu.DrawerHeader is used to modify the header of the panel. In header we can display icon or details
of user according to the application. We have used ListTile to add the items to the menu.

Output:

21
BIM30603 Lab Activity #5

5. bottomNavigationBar

Below is the implementation of bottomNavigationBar:


bottomNavigationBar: BottomNavigationBar(
currentIndex: 0,
fixedColor: Colors.green,
items: const [
BottomNavigationBarItem(
label: "Home",
icon: Icon(Icons.home),
),
BottomNavigationBarItem(
label: "Search",
icon: Icon(Icons.search),
),
BottomNavigationBarItem(
label: "Profile",
icon: Icon(Icons.account_circle),
),
],
onTap: (int indexOfItem) {}),

We use BottomNavigationBar widget to display the bar. For the color of active icon, we use
the fixedColor property. To add items in the bar we use BottomNavigationBarItems widget, inside which
we give text and icon. For the action performed on the tapping on the items, we have onTap(int
indexOfItem) function which works according to the index position of the item.

Output:

22
BIM30603 Lab Activity #5

23
BIM30603 Lab Activity #5

MaterialApp class in Flutter


MaterialApp Class: MaterialApp is a predefined class or widget in a flutter. It is likely the main or core
component of a flutter app. The MaterialApp widget provides a wrapper around other Material Widgets.
We can access all the other components and widgets provided by Flutter SDK. Text widget,
DropdownButton widget, AppBar widget, Scaffold widget, ListView widget, StatelessWidget,
StatefulWidget, IconButton widget, TextField widget, Padding widget, ThemeData widget, etc. are the
widgets that can be accessed using MaterialApp class. There are many more widgets that are accessed
using MaterialApp class. Using this widget, we can make an attractive app that follows the Material Design
guidelines.

Constructor of MaterialApp class


const MaterialApp(
{
Key key,
GlobalKey<NavigatorState> navigatorKey,
Widget home,
Map<String, WidgetBuilder> routes: const <String, WidgetBuilder>{},
String initialRoute,
RouteFactory onGenerateRoute,
InitialRouteListFactory onGenerateInitialRoutes,
RouteFactory onUnknownRoute,
List<NavigatorObserver> navigatorObservers: const
<NavigatorObserver>[],
TransitionBuilder builder,
String title: '',
GenerateAppTitle onGenerateTitle,
Color color,
ThemeData theme,
ThemeData darkTheme,
ThemeData highContrastTheme,
ThemeData highContrastDarkTheme,
ThemeMode themeMode: ThemeMode.system,
Locale locale,
Iterable<LocalizationsDelegate> localizationsDelegates,
LocaleListResolutionCallback localeListResolutionCallback,
LocaleResolutionCallback localeResolutionCallback,
Iterable<Locale> supportedLocales: const <Locale>[Locale('en',
'US')],
bool debugShowMaterialGrid: false,
bool showPerformanceOverlay: false,
bool checkerboardRasterCacheImages: false,
bool checkerboardOffscreenLayers: false,
bool showSemanticsDebugger: false,
bool debugShowCheckedModeBanner: true,
Map<LogicalKeySet, Intent> shortcuts,
Map<Type, Action<Intent>> actions}
)

24
BIM30603 Lab Activity #5

Properties of MaterialApp widget:


Property Description
action This property takes in Map<Type,
Action<Intent>> as the object. It controls intent
keys.
backButtonDispatcher It decided how to handle the back button.
checkerboardRasterCacheImage This property takes in a boolean as the object. If
set to true it turns on the checkerboarding of
raster cache images.
color It controls the primary color used in the
application.
darkTheme It provided theme data for the dark theme for
the application.
debugShowCheckedModeBanner This property takes in a boolean as the object to
decide whether to show the debug banner or
not.
debugShowMaterialGird This property takes a boolean as the object. If
set to true it paints a baseline grid material app.
highContrastDarkTheme It provided the theme data to use for the high
contrast theme.
home This property takes in widget as the object to
show on the default route of the app.
initialRoute This property takes in a string as the object to
give the name of the first route in which the
navigator is built.
locale It provides a locale for the MaterialApp.
localizationsDelegate This provides a delegate for the locales.
navigatorObserver It takes in GlobalKey<NavigatorState> as the
object to generate a key when building a
navigator.
navigatorObserver This property holds List<NavigatorObserver> as
the object to create a list of observers for the
navigator.
onGenerateInitialRoutes This property takes in InitialRouteListFactory
typedef as the object to generate initial routes.
onGeneratRoute The onGenerateRoute takes in a RouteFactory as
the object. It is used when the app is navigated
to a named route.
onGenerateTitle This property takes in RouteFactory typedef as
the object to generate a title string for the
application if provided.

25
BIM30603 Lab Activity #5

onUnknownRoute The onUnknownRoute takes in RouteFactory


typedef as the object to provide a route in case
of failure in other method.
routeInformationParse This property
holds RouteInformationParser<T> as the object
to the routing information from the
routeInformationProvider into a generic data
type.
routeInformationProvider This property takes
in RouteInformationProvider class as the object.
It is responsible for providing routing
information.
routeDelegate This property takes in RouterDelegate<T> as the
object to configure a given widget.
routes The routes property takes in LogicalKeySet class
as the object to control the app’s topmost level
routing.
shortcuts This property takes in LogicalKeySet class as the
object to decide the keyboard shortcut for the
application.
showPerformanceOverlay The showPerformanceOverlay takes in
a boolean value as the object to turn on or off
performance overlay.
showSemantisDebugger This property takes in a boolean as the object. If
set to true, it shows some accessible
information.
supportedLocales The supportedLocales property keeps hold of the
locals used in the app by taking
in Iterable<E> class as the object.
theme This property takes in ThemeData class as the
object to describe the theme for the
MaterialApp.
themeMode This property holds ThemeMode enum as the
object to decide the theme for the material app.
title The title property takes in a string as the object
to decide the one-line description of the app for
the device.

26
BIM30603 Lab Activity #5

Simple Material App Example:


Here is very simple code in dart language to make a screen that has an AppBar title as BIM30603.
import 'package:flutter/material.dart';

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

class GFGapp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'BIM30603',
theme: ThemeData(primarySwatch: Colors.green),
darkTheme: ThemeData(primarySwatch: Colors.grey),
color: Colors.amberAccent,
supportedLocales: {const Locale('en', ' ')},
debugShowCheckedModeBanner: false,

home: Scaffold(
appBar: AppBar(
title: const Text('BIM30603'),
backgroundColor: Colors.green
),
),
);
}
}

Output:

27
BIM30603 Lab Activity #5

• Here we can see that the text defined in the title of the AppBar is displayed at the top.

• The default theme color is green as we defined.

• runApp() calls the widget GFGapp that returns the MaterialApp widget which specifies theme,
localization, title, home widget and more.

Output explanation:

• import statement: The import statement is used to import the libraries that are provided by the
flutter SDK. Here we have imported the ‘material.dart’ file. We can use all the flutter widgets
that implement the material design by importing this file.

• main() function: Like many other programming languages, we also have a main function in
which we have to write the statements that are to be executed when the app starts. The return
type of the main function is ‘void’.

• runApp(Widget widget) function: The void runApp(Widget widget) takes a widget as an


argument and sets it on a screen. It gives the constraints to the widget to fit into the screen. It
makes the given widget the root widget of the app and other widgets as the child of it. Here we
have used the MaterialApp as a root widget in which we have defined the other widgets.

28
BIM30603 Lab Activity #5

• MaterialApp() widget: We have discussed MaterialApp in the beginning. Let us have a look at
the different properties of the MaterialApp widget.

• title: This property is used to provide a short description of the application to the user. When
the user presses the recent apps button on mobile the text proceeded in titlthe e is displayed.

• theme: This property is used to provide the default theme to the application like the theme
color of the application.
For this, we use the inbuilt class/widget named ThemeData(). In Themedata() widget we have to
write the different properties related to the theme. Here we have used
the primarySwatch which is used to define the default themecolor of the application. To choose
the color we used Colors class from the material library. In ThemeData() we can also define
some other properties like TextTheme, Brightness(Can enable dark theme by this),
AppBarTheme, and many more.

• home: It is used for the default route of the app means the widget defined in it is displayed
when the application starts normally. Here we have defined the Scaffold widget inside the home
property. Inside the Scaffold we define various properties like appBar, body,
floatingActionButton, backgroundColor, etc.
For example, in the appBar property we have used the AppBar() widget which
accepts ‘GeeksforGeeks’ as the title, this will be displayed at the top of the application in appbar.

• The other properties in MaterialApp() are debugShowCheckedModeBanner (used to remove the


debug tag at the top corner), darkTheme (To request dark mode in application), color (For the
primary color of application), routes (For routing table of application), ThemeMode (To
determine which theme to be used) and supportedLocales contains a list of languages the app
supports, etc.

29
BIM30603 Lab Activity #5

Drawer Widget in Flutter


Drawer widget is used to provide access to different destinations and functionalities provided in your
application. It is represented by three horizontal parallel lines on the upper end of the scaffold. It has a
horizontal movement from the edge of the Scaffold that navigates the link to different routes in the flutter
app.

In order to use the app drawer you need to import the material component package that is ” package:
flutter/material.dart.”
The Navigating AppDrawer is divided into three sections namely header, body, and footer. The idea is
about having a navigator with a couple of items as the drawer’s child that will be navigated to different
destinations on getting tapped. All children of a Drawer widget are usually in ListView and initially, only
the DrawerHeader is present in the UI which when tapped extends horizontally.

Constructors:
Drawer({Key key, double elevation: 16.0, Widget child, String
semanticLabel})

Properties:
• child: The widgets below this widget in the tree.
• hashCode: The hash code for this object.
• key: Controls how one widget replaces another widget in the tree.
• runtimeType: A representation of the runtime type of the object.
• elevation: The z-coordinate at which to place this drawer relative to its parent.
• semanticLabel: The semantic label of the dialogue used by accessibility frameworks to
announce screen transitions when the drawer is opened and closed.
Important Function:
• build(BuildContext context) → Widget: This method specifies the part of the UI
rendered by the widget. This method is called when the Drawer widget is inserted into
the tree in a given BuildContext and when the dependencies of the Drawer widget
change.
Implementation:
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterialLocalizations(context));
String? label = semanticLabel;
switch (Theme.of(context).platform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
break;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:

30
BIM30603 Lab Activity #5

label = semanticLabel ??
MaterialLocalizations.of(context).drawerLabel;
}
return Semantics(
scopesRoute: true,
namesRoute: true,
explicitChildNodes: true,
label: label,
child: ConstrainedBox(
constraints: const BoxConstraints.expand(width: _kWidth),
child: Material(
elevation: elevation,
child: child,
),
),
);
}

Why Drawers?
Drawers are very easy to implement as well as handy to balance different functionalities of your mobile
application at the same time. Creating a drawer makes visiting different destinations in your app quite
easy and manageable to a large extent, especially in the case of a complex application with many screens.
You can easily switch between different screens and perform tasks.

Steps to Create a Drawer:


A drawer can be set using 4 simple steps:

1. Create a flutter project: Open the terminal and navigate to the desired location in which you want to
create your project. Using the “flutter create project_name” command creates your flutter project.
flutter create file_name

2. Create a scaffold widget: Inside the MyApp Class of your stateless/stateful widget return a scaffold
widget. A Scaffold Widget provides a framework for implementing the basic visual layout structure of
the flutter app.
Scaffold(
drawer:
);

3. Add Drawer inside the scaffold: Set the scaffold’s drawer property to Drawer with ListView as its child
or you can add a Container with a ListView as its child as well. Various ListViews contain desired items
that needed to be displayed inside the drawer.
Scaffold(
drawer: Drawer(
//...
),);

31
BIM30603 Lab Activity #5

4. Add a closing functionality: Navigator is used for implementing closing functionality on the drawer
when the user wants to close it after tapping on some item. This can be done using a Navigator State.
Navigator.of(context).pop();

Types of Navigation Drawer:

An app drawer is divided into three categories:


1. Standard Navigation Drawer: They provide user interaction with the screen content and drawer at the
same time.
2. Modal Navigation Drawer: These drawers block the user interaction with the rest of the screen and
allow only the user to interact with the drawer only.
3. Bottom Navigation Drawer: These are similar to modal navigation drawers except the orientation of
the drawer is towards the bottom section of the screen.

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

// function to trigger app build


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

class MyApp extends StatelessWidget {


final appTitle = 'Flutter Drawer Demo';

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

@override
Widget build(BuildContext context) {
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
); // MaterialApp
}
}

class MyHomePage extends StatelessWidget {


final String title;

const MyHomePage({Key? key, required this.title}) : super(key: key);

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
backgroundColor: Colors.green,
),
body: const Center(
child: Text(
'A drawer is an invisible side screen.',
style: TextStyle(fontSize: 20.0),
)),
drawer: Drawer(

32
BIM30603 Lab Activity #5

child: ListView(
padding: const EdgeInsets.all(0),
children: [
const DrawerHeader(
decoration: BoxDecoration(
color: Colors.green,
), //BoxDecoration
child: UserAccountsDrawerHeader(
decoration: BoxDecoration(color: Colors.green),
accountName: Text(
"Abhishek Mishra",
style: TextStyle(fontSize: 18),
),
accountEmail: Text("abhishekm977@gmail.com"),
currentAccountPictureSize: Size.square(50),
currentAccountPicture: CircleAvatar(
backgroundColor: Color.fromARGB(255, 165, 255,
137),
child: Text(
"A",
style: TextStyle(fontSize: 30.0, color:
Colors.blue),
), //Text
), //circleAvatar
), //UserAccountDrawerHeader
), //DrawerHeader
ListTile(
leading: const Icon(Icons.person),
title: const Text(' My Profile '),
onTap: () {
Navigator.pop(context);
},
),
ListTile(
leading: const Icon(Icons.book),
title: const Text(' My Course '),
onTap: () {
Navigator.pop(context);
},
),
ListTile(
leading: const Icon(Icons.workspace_premium),
title: const Text(' Go Premium '),
onTap: () {
Navigator.pop(context);
},
),
ListTile(
leading: const Icon(Icons.video_label),
title: const Text(' Saved Videos '),
onTap: () {
Navigator.pop(context);
},
),
ListTile(
leading: const Icon(Icons.edit),
title: const Text(' Edit Profile '),

33
BIM30603 Lab Activity #5

onTap: () {
Navigator.pop(context);
},
),
ListTile(
leading: const Icon(Icons.logout),
title: const Text('LogOut'),
onTap: () {
Navigator.pop(context);
},
),
],
),
), //Drawer
);
}
}

Output:

34
BIM30603 Lab Activity #5

BottomNavigationBar Widget in Flutter


The BottonNavigationBar widget is used to show the bottom of an app. It can consist of multiple items
such as icons, text, or both that leads to a different route depending upon the design of the application.
It is meant to help the user navigate to different sections of the application in general.

Constructors:
BottomNavigationBar(
{
Key key,
@required List<BottomNavigationBarItem> items,
ValueChanged<int> onTap,
int currentIndex: 0,
double elevation,
BottomNavigationBarType type,
Color fixedColor,
Color backgroundColor,
double iconSize: 24.0,
Color selectedItemColor,
Color unselectedItemColor,
IconThemeData selectedIconTheme,
IconThemeData unselectedIconTheme,
double selectedFontSize: 14.0,
double unselectedFontSize: 12.0,
TextStyle selectedLabelStyle,
TextStyle unselectedLabelStyle,
bool showSelectedLabels: true,
bool showUnselectedLabels,
MouseCursor mouseCursor
}
)ol showUnselectedLabels,
MouseCursor mouseCursor

})

Properties:
Properties Description
hashCode The hash code for this object.
key Controls how one widget replaces another widget in the tree.
runtimeType A representation of the runtime type of the object.
backgrounColor The color of the BottomNavigationBar itself.
elevation The z-coordinate of this BottomNavigationBar.
fixedColor The z-coordinate of this BottomNavigationBar.
items Defines the appearance of the button items that are arrayed within
the bottom navigation bar.
onTap Called when one of the items is tapped.
currentIndex This property takes an int value as the object to assign index t the
items.

35
BIM30603 Lab Activity #5

fixedColor This property takes in Color class as the object to assign a fixed value
to the SelectedItemColor.
iconSize It takes a double value as the object to determine the size of all the
icons in the BottomNavigationBar.
mouseCursor The mouseCursor property takes MouseCursor class as the object. It
determines the type of cursor this widget will have.
selectedFontSize This property controls the font size in the BottomNavigationBar when
the items are selected. It takes a double value as the object.
selectedIcontheme This property holds IconThemeData class as the object to controls the
appearance of the icons this widget when it is selected.
selectedIconColor This property determines the color of the icons inside this widget will
hold when they are selected. This property takes Color class as the
property.
selectedLabelStyle TextStyle class is the object assigned to this property which controls
the text style at the instance of selection.
showSelectedLabele This property takes a boolean value as the object to determine
whether or not the labels for the unselected item will be shown.
showUnselectedLabels This property also takes in a boolean value as the object to determine
whether or not the labels for selected items will be shown.
type The type property controls the behaviour and the layout of the
BottomNavigationBar. It takes BottomNavigationBarType enum as the
object.
unselectedFontSize This property also takes a double value as e object to determine the
size of font when the item is not selected.
unselectedIconTheme This property also holds IconThemeData class as the object to controls
the appearance of the icons this widget when it is unselected or not
selected.
unselectedItemColor This property determines the color the icons inside this widget will
hold when they are unselected. This property takes Color class as the
property.
unselectedLabelStyle TextStyle class is the object assigned to this property which controls
the text style when the item is unselected.

Example of BottomNavigationBar Widget in Flutter


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


static const String _title = 'Flutter Code Sample';

const MyApp({super.key});

@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),

36
BIM30603 Lab Activity #5

);
}
}

class MyStatefulWidget extends StatefulWidget {


const MyStatefulWidget({super.key});

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

class _MyStatefulWidgetState extends State<MyStatefulWidget> {


int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'HOME PAGE',
style: optionStyle,
),
Text(
'COURSE PAGE',
style: optionStyle,
),
Text(
'CONTACT',
style: optionStyle,
),
];

void _onItemTapped(int index) {


setState(() {
_selectedIndex = index;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(BIM30603),
backgroundColor: Colors.green,
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: ('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.bookmark),
label: ('Courses'),
),
BottomNavigationBarItem(

37
BIM30603 Lab Activity #5

icon: Icon(Icons.contact_mail),
label: ('Mail'),
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}

Output:

Explanation of the above Program:


1. First, create the stateless main widget.
2. Second use the widget builder to create an appbar inside the scaffold.
3. Third use the ButtomNavigationBar widget in the body of the main app
4. Do not forget to set the navbar at the bottom of the app using the style property.

38
BIM30603 Lab Activity #5

AppBar Widget
AppBar is usually the topmost component of the app (or sometimes the bottom-most), it contains the
toolbar and some other common action buttons. As all the components in a Flutter application are a
widget or a combination of widgets. So AppBar is also a built-in class or widget in Flutter which gives the
functionality of the AppBar out of the box. The AppBar widget is based on Material Design and much of
the information is already provided by other classes like MediaQuery, and Scaffold as to where the
content of the AppBar should be placed. Though the AppBar class is very flexible and can be easily
customized, we can also use the SliverAppBar widget which gives scrollable functionality to the app bar.
Or we can create our own custom app bar from scratch.

Constructor Of AppBar Class:


AppBar(
{
Key key,
Widget leading,
bool automaticallyImplyLeading: true,
Widget title,
List<Widget> actions,
double elevation,
Color shadowColor,
ShapeBorder shape,
Color backgroundColor,
Brightness brightness,
IconThemeData iconTheme,
IconThemeData actionsIconTheme,
TextTheme textTheme,
...}
)

Properties of Appbar Widget:


• actions: This property takes in a list of widgets as a parameter to be displayed after the title if
the AppBar is a row.
• title: This property usually takes in the main widget as a parameter to be displayed in the
AppBar.
• backgroundColor: This property is used to add colors to the background of the Appbar.
• elevation: This property is used to set the z-coordinate at which to place this app bar relative to
its parent.
• shape: This property is used to give shape to the Appbar and manage its shadow.

39
BIM30603 Lab Activity #5

Example Demonstration of AppBar in Flutter Application


Example 1:

import 'package:flutter/material.dart';

void main() {
runApp(gfgApp()); //MaterialApp
}

MaterialApp gfgApp() {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('BIM30603'),
), //AppBar
body: const Center(
child: Text(
'BIM30603',
style: TextStyle(fontSize: 24),
), //Text
), // center
), //Scaffold
debugShowCheckedModeBanner: false, //Removing Debug Banner
);
}

Output:

Explanation of the above Program:


First, we have imported the material.dart file as the AppBar widget utilizes it, we will also do the same in
the following two examples. Then we have our main function calling runApp.
• At top, we have MaterialApp widget followed by Scaffold.

40
BIM30603 Lab Activity #5

• The MaterialApp widget provided Style to AppBar and the Scaffold widget by default places
the AppBar widget at the top of the screen.
• This is just the bare basic out of the box AppBar provided by flutter.
• This AppBar is utilizing only the title property of the AppBar class, which takes in the main widget
to be displayed in the AppBar.
• In this case, it is a Text widget.
In the body, we have a child text widget inside the center widget displaying the text ‘Selamat datang ke
FSKTM, with a font size of 24. In the end, the debug banner has been disabled. This will be followed by
the next two examples below.

Example 2:

import "package:flutter/material.dart";

// function to trigger the build process


void main() {
runApp(MyApp()); //MaterialApp
}

// ignore: non_constant_identifier_names
MaterialApp MyApp() {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("BIM30603"),
titleSpacing: 00.0,
centerTitle: true,
toolbarHeight: 60.2,
toolbarOpacity: 0.8,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(25),
bottomLeft: Radius.circular(25)),
),
elevation: 0.00,
backgroundColor: Colors.greenAccent[400],
), //AppBar
body: const Center(
child: Text(
'Selamat Datang ke FSKTM',
style: TextStyle(fontSize: 24),
),
), //Center
), //Scaffold
debugShowCheckedModeBanner: false, //Removing Debug Banner
);
}

41
BIM30603 Lab Activity #5

Output:

Explanation of the above Program:

Here the AppBar widget is utilizing seven properties in total.

• It starts with the title ‘BIM30603’.

• The second is the titlespacing which takes in double as a parameter and in this case, it is set to
00.0 to keep text close together.

• The third property is centerTitle which takes in boolean as a parameter and is set to true here.

• The fourth property is toolbarHeight which also takes in double as a parameter. This property
provides a shadow underneath the AppBar which in turn makes it look elevated. toolBarOpacity is
responsible for controlling the opacity of the toolbar portion of the appBar. It takes a double value
as the parameter where 1.0 is the maximum opacity and 0.0 is full transparency.

• The fifth property is shape it is utilized to give a different shape to the AppBar by modifying the
border of the AppBar. Inside the shape property we have used the borderRadius to make the
bottom edges of the AppBar rounded by an angle of 25 degrees.

42
BIM30603 Lab Activity #5

• The sixth property is elevation, it defines the z-coordinates at which the AppBar is to be placed
with respect to its parent. It also takes in double as a parameter.

• And the last is the backgroundColor which controls the background color of the AppBar.

Example 3:

import "package:flutter/material.dart";
import 'package:flutter/services.dart';

void main() {
runApp(gfgApp()); //MaterialApp
}

MaterialApp gfgApp() {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("BIM30603"),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.comment),
tooltip: 'Comment Icon',
onPressed: () {},
), //IconButton
IconButton(
icon: const Icon(Icons.settings),
tooltip: 'Setting Icon',
onPressed: () {},
), //IconButton
], //<Widget>[]
backgroundColor: Colors.greenAccent[400],
elevation: 50.0,
leading: IconButton(
icon: const Icon(Icons.menu),
tooltip: 'Menu Icon',
onPressed: () {},
),
systemOverlayStyle: SystemUiOverlayStyle.light,
), //AppBar
body: const Center(
child: Text(
"Selamat Datang ke FSKTM",
style: TextStyle(fontSize: 24),
), //Text
), //Center
), //Scaffold
debugShowCheckedModeBanner: false, //Removing Debug Banner
);
}

43
BIM30603 Lab Activity #5

Output:

Explanation of the above Program:


Here we can see that in addition to the title on the app Bar we have three more icons on the AppBar, one
on the left and two on the right of the title.
• This AppBar widget starts with the usual title property which is taking Text widget as a parameter.
• The title is followed by the action property which takes in a list of widgets as a parameter to be
displayed after the title if the AppBar is a row.
• In this case, we can see the two icons namely the comment and setting.
• These two icons are IconsButton widgets, utilizing three properties namely icon, tooltip,
and onPressed function.
• The onPressed function is not specified in any of the IconButton so it is null.
• The icon property takes in a string as a parameter which is the name of the specific icon.
• The tooltip property also takes in a string as the parameter which is displayed in a floating label,
while hovering with the mouse or on the long-press.
• In the first IconButton we have Icons.comment & Comment Icon and in the second IconButton we
have Icons.setting & Setting Icon as the parameter for the icon and tooltip respectively.
• Now, all this is followed but the backgroundColor and elevation are set to
Colors.greenAccent[400] and 50.0 respectively.
• After that, we have the leading property which takes in a widget as a parameter, to be displayed
before the title in the AppBar.

44
BIM30603 Lab Activity #5

• In this case, the leading is also an IconButton, which displays a menu icon. The onPressed property
is not mentioned and the tooltip property is given a parameter of string ‘Menu Icon’. And the
body is similar to the first and second examples.

Row and Column Widgets


Row and Column are the two most important and powerful widgets in Flutter. These widgets let you
align children horizontally and vertically as per the requirement. As we know that when we design any
UI(User Interface) in a flutter, we need to arrange its content in the Row and Column manner so these
Row and Column widgets are required when designing UI.

Constructor Of Column Class:


Column(
{Key key,
MainAxisAlignment mainAxisAlignment: MainAxisAlignment.start,
MainAxisSize mainAxisSize: MainAxisSize.max,
CrossAxisAlignment crossAxisAlignment: CrossAxisAlignment.center,
TextDirection textDirection,
VerticalDirection verticalDirection: VerticalDirection.down,
TextBaseline textBaseline,
List<Widget> children: const <Widget>[]}
)

Constructor Of Row Class:


Row(
{Key key,
MainAxisAlignment mainAxisAlignment: MainAxisAlignment.start,
MainAxisSize mainAxisSize: MainAxisSize.max,
CrossAxisAlignment crossAxisAlignment: CrossAxisAlignment.center,
TextDirection textDirection,
VerticalDirection verticalDirection: VerticalDirection.down,
TextBaseline textBaseline: TextBaseline.alphabetic,
List<Widget> children: const <Widget>[]}
)

Properties of Row and Column Widgets:


• children: This property takes in List<Widget>, that is a list of widgets to display inside the Row or
the Column widget.

• clipBehaviour: This property holds Clip class as the object to decide whether the content on
the Row or Column should be clipped or not.

45
BIM30603 Lab Activity #5

• crossAxisAlignment: The crossAxisAlignment takes in CrossAxisAlignment enum as the object to


how the children’s widgets should be places in crossAxisAlignment. For Row it is vertical and
for Column it is horizontal.

• direction: This property holds as the Axis enum object to decide the direction used in the main
axis. For Row and Column, it is fixed.

• mainAxisAlignment: This property takes in MainAxisAlignment enum as the object to decide


how the children widgets should be place in mainAxisAlignment. For Row it is horizontal and
for Column it is vertical.

• mainAxisSize: This property decides the size of main-axis by taking in MainAxisSize enum as the
object.

• runtimeType: This property tells the run-time type of the Row or Column widget.

• textBaseline: This property is responsible for the alignment of the text in


the Row or Column widget with respect to a baseline.

• textDirection: This property controls the text direction of the Row or Column widget, which can
either be from left-to-right (by default) or right-to-left.

• verticalDirection: This property takes in VerticalDirection enum as the object to determine the
order in which the children should be layered.

Row:
It creates a horizontal array of children.

Alignment Properties: We can align content as per our choice by


using mainAxisAlignment and crossAxisAlignment. Row’s mainAxis is horizontal and cross Axis to Row’s
main Axis is vertical. We can align children horizontally using MainAxisAlignment and vertically using
CrossAxisAlignment in that row.

Apart from these mainAxisAlignment and crossAxisAlignment, we also have some other properties like
mainAxisSize,textDirection,verticalDirection etc. but we will focus on these two(mainAxisAlignment and
crossAxisAlignment) in this article as these are mostly used.

Main Axis

Cross
Axis

Row
We can align the content by using the following properties:
• start: Place the children from the starting of the row.
• end: Place the children at the end of the row.
• center: Place the children at the center of the row.

46
BIM30603 Lab Activity #5

• spaceBetween: Place the space evenly between the children.


• spaceAround: Place the space evenly between the children and also half of that space before
and after the first and last child.
• spaceEvenly: Place the space evenly between the children and also before and after the first
and last child.

We will see the difference with the help of examples. Let’s suppose we want to align content such that
there is space around the children in a row :

import 'package:flutter/material.dart';

//function to trigger build


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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'BIM30603',
theme: ThemeData(
primarySwatch: Colors.green,
), // ThemeData
home: const MyHomePage(),
debugShowCheckedModeBanner: false,
); // MaterialApp
}
}

class MyHomePage extends StatefulWidget {


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

@override
// ignore: library_private_types_in_public_api
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("BIM30603"),
), // AppBar
// App body consists of single Row
// Row consists of three children widgets
body: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Container(
decoration: BoxDecoration(

47
BIM30603 Lab Activity #5

borderRadius: BorderRadius.circular(10), color:


Colors.green),
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Saya",
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10), color:
Colors.green),
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Suka",
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10), color:
Colors.green),
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Flutter",
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
)
],
),
);
}
}

48
BIM30603 Lab Activity #5

Output:

Column:
It creates a vertical array of children.

Alignment Properties:
In this also we have mainAxisAlignment and crossAxisAlignment. In column, children are aligned from top
to bottom. Main Axis is vertical and the Cross Axis is horizontal. MainAxisAlignment aligns its children
vertically and CrossAxisAlignment aligns horizontally in that Column.

Main
Axis

Cross Axis
Column
We can align the content by using the same properties as discussed above in Row (start, end,
spaceBetween, spaceAround, spaceEvenly).

We will see the difference with the help of examples. Let’s suppose we want to align content so that we
have space around the children. Assign mainAxisAlignment as spaceAround as shown below:

49
BIM30603 Lab Activity #5

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

//function to trigger build


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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'BIM30603',
theme: ThemeData(
primarySwatch: Colors.green,
), // ThemeData
home: const MyHomePage(),
debugShowCheckedModeBanner: false,
); // MaterialApp
}
}

class MyHomePage extends StatefulWidget {


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

@override
// ignore: library_private_types_in_public_api
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("BIM30603"),
), // AppBar
// App body consists of single Column
// Column consists of three children widgets
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10), color:
Colors.green),
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Saya Suka Flutter",
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),

50
BIM30603 Lab Activity #5

Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10), color:
Colors.green),
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Saya Suka Flutter",
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10), color:
Colors.green),
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Saya Suka Flutter",
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
)
],
), // Column
);
}
}
Output:

51
BIM30603 Lab Activity #5

Some more examples are :


mainAxisAlignment.spaceEvenly

mainAxisAlignment.center

52
BIM30603 Lab Activity #5

mainAxisAlignment.spaceBetween

We can also align content using combination of mainAxisAlignment and crossAxisAlignment for both Row
and Column. Lets take an example of Row, set mainAxisAlignment as
MainAxisAlignment.spaceAround and crossAxisAlignment as CrossAxisAlignment.stretch. By
doing this (crossAxisAlignment.stretch), the height of the row will be equal to the height of the
body because we have only one row.
...
body: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
...

53
BIM30603 Lab Activity #5

Output:

Drawbacks:

• The row has no horizontal scrolling so when a large number of children are inserted in a single row that is
not able to fit in the row then it will give us an Overflow message (for ex: Right overflowed by 560px).

• The column has no vertical scrolling so when a large number of children are inserted in a single Column
whose total children size is more than the total height of the screen then it will give us an Overflow
message (for ex: Bottom overflowed by 684px).

54

You might also like