SlideShare a Scribd company logo
1 of 85
Lecture 5 : Building Layouts
T. Fatima Al-azazi
2
Agenda
● Basic Widgets
● Single-Child Layout Widgets
● Multi-child Layout Widgets
● Common Layout Widgets
● How to Lay out a Widget by Example
● In-Class Activity
3
USING BASIC WIDGETS
4
Structural widgets
● There are a few convenience widgets that you’ll likely use in every
Flutter app you build. They provide configuration and structure to your
app, with little work from you.
○ MaterialApp widget
○ Scaffold
○ AppBar
○ Theme
5
MaterialApp widget
● An extension of the generic top-level widget: WidgetsApp.
● WidgetsApp is a convenience widget that abstracts away a number of
features required for most mobile apps, such as setting up a navigator
and using an appwide theme.
● WidgetsApp requires more work to set up than MaterialApp or
CupertinoApp
● MaterialApp provides
○ a ton of benefits that affect its entire widget subtree.
○ provides configuration and functionality to your app.
6
Using Material Components
● A Material app starts with the MaterialApp widget, which builds a
number of useful widgets at the root of your app, including a
Navigator, which manages a stack of widgets.
● The Navigator lets you transition smoothly between screens of your
application.
● Material app implements the animations that happen when a user
navigates between pages.
● MaterialApp takes care of the appwide theme .
● Home property represents the app’s home page, which can be any
widget.
7
The Scaffold widget
● Scaffold is a designed to make applications as easy as possible to build.
● Scaffold is the widget that gives your app structure.
● Scaffold defines the “basic Material Design visual layout,” which means
it can make your app look like this pretty easily.
● The Scaffold widget provides many optional features, pick and choose
which features you want.
● It’s common for each of the different screens in your application to
have its own Scaffold widget.
8
The Scaffold widget
● It provides functionality to add
○ a drawer (an element that animates in from one Listing
○ a bottom sheet (an element that animates into view from the
bottom of the screen).
○ the AppBar in a scaffold is automatically set up to display a menu
button in the top-left corner of your app, which will open the
drawer;
○ Body is a Scaffold argument that represents the main portion of
the screen.
● If there is no app bar, body is essentially the entire screen.
9
Scaffold Properties
10
AppBar widget
● Typically used in the Scaffold.appBar property, which fixes it to the top
of the screen with a certain height.
● The most notable feature of AppBar is that it provides navigation
features for free. It automatically inserts a menu button if the app bar’s
parent is a scaffold and the drawer argument isn’t null.
● And if the Navigator of your app detects that you’re on a page that can
navigate “back” (like a browser’s back button), it automatically inserts a
back button.
11
AppBar widget
● Usually contains the standard title, toolbar, leading, and actions
properties (along with buttons), as well as many customization options.
● The property that handles these menu buttons and back buttons is
called the leading action.
● If you don’t want a menu button to appear, You can set
AppBar.automaticallyImplyLeading to false and then pass the leading
argument to whatever widget you wish.
12
AppBar Properties
● The title property is typically implemented with a Text widget.
● The leading property is displayed before the title property. Usually this
is an IconButton or BackButton.
● The actions property is a list of widgets aligned to the upper right of an
AppBar widget usually with an IconButton or PopupMenuButton.
● The flexibleSpace property is stacked behind the Toolbar or TabBar
widget.
● A background image is commonly applied to the flexibleSpace
property, but any widget, such as an Icon, could be used.
13
ThemeData widget
● allows you to set many default styles in your app, such as colors, font
styles, button styles, and more.
● Theme will be automatically applied throughout your app.
● some of the properties you can set on the widget that will permeate
throughout the app:
○ brightness
○ primarySwatch
○ primaryColor
○ accentColor
● Watch https://youtu.be/oTvQDJOBXmM?feature=shared
14
SafeArea
● Necessary for today’s devices such
as the iPhone X or Android devices
with a notch (a partial cut-out
obscuring the screen usually
located on the top portion of the
device).
● Automatically adds sufficient
padding to the child widget to avoid
intrusions by the operating system.
15
RichText
● A great way to display text using multiple styles.
● The RichText widget takes TextSpans as children to style different
parts of the strings.
● There are two main parts to styling, the default text property and the
children list of TextSpan.
● The text property using a TextSpan sets the default styling for the
RichText.
● The children list of TextSpan allows you to use multiple TextSpan
objects to format different strings.
16
IMAGES
● Images can make an app look tremendous or ugly depending on the
quality of the artwork. Images, icons, and other resources are
commonly embedded in an app.
● The AssetBundle class provides access to custom resources such as
images, fonts, audio, data files, and more. Before a Flutter app can use a
resource, you must declare it in the pubspec.yaml file.
17
Image Widget
● The Image widget displays an image from a local or URL (web) source.
● To load an Image widget, there are a few different constructors to use.
18
19
Silhouette -Style Image
● If you add color to the image, it colorizes the image portion and leaves
any transparencies alone, giving a silhouette look
20
orientation
● You can detect device orientation by
calling
MediaQuery.of(context).orientation,
which returns either a portrait or
landscape value.
● There is also OrientationBuilder,
which returns the amount of space
available to the parent to figure out
the orientation.
21
Layouts in Flutter
22
Layouts in Flutter
● The core of Flutter’s layout mechanism is widgets.
● Things you don’t see are also widgets, such as the rows, columns, and
grids that arrange, constrain, and align the visible widgets.
● You create a layout by composing widgets to build more complex
widgets. For example, the first screenshot below shows 3 icons with a
label under each one.
23
widget tree for this UI
24
Layout widgets
● Layout widgets arrange other widgets columns, rows, grids, and many
other layouts.
● Single-child layout widgets
● Multi-child layout widgets
● Sliver widgets
25
Single-child layout widgets
● Center: A widget that centers its child within itself.
● Container: A convenience widget that combines common painting,
positioning, and sizing widgets.
● Expanded: A widget that expands a child of a Row, Column, or Flex.
● Padding: A widget that insets its child by the given padding.
● SizedBox: A box with a specified size. If given a child, this widget forces
its child to have a specific width and/or height
● ConstrainedBox:A widget that imposes additional constraints on its
child.
26
Single-child layout widgets
● CustomSingleChildLayout: A widget that defers the layout of its single
child to a delegate.
● FittedBox: Scales and positions its child within itself according to fit.
● FractionallySizedBox: A widget that sizes its child to a fraction of the total
available space.
● IntrinsicHeight: A widget that sizes its child to the child's intrinsic height.
● IntrinsicWidth: A widget that sizes its child to the child's intrinsic width.
● Baseline: A widget that positions its child according to the child's baseline.
● LimitedBox: A box that limits its size only when it's unconstrained.
27
Single-child layout widgets
● Offstage: A widget that lays the child out as if it was in the tree, but without
painting anything, without making the child available for hit.
● OverflowBox: A widget that imposes different constraints on its child than
it gets from its parent, possibly allowing the child to overflow the parent.
● SizedOverflowBox: A widget that is a specific size but passes its original
constraints through to its child, which will probably overflow.
● Transform: A widget that applies a transformation before painting its child.
● Align: A widget that aligns its child within itself and optionally sizes itself
based on the child's size.
● AspectRatio: A widget that attempts to size the child to a specific aspect
ratio.
28
Multi-child layout widgets
● Column: Layout a list of child widgets in the vertical direction.
● Row: Layout a list of child widgets in the horizontal direction.
● GridView: A grid list consists of a repeated pattern of cells arrayed in a
vertical and horizontal layout.
● ListView: A scrollable, linear list of widgets. ListView is the most
commonly used scrolling widget. It displays its children one after
another in the scroll direction.
● Stack: This class is useful if you want to overlap several children in a
simple way, for example having some text and an image, overlaid with.
29
Multi-child layout widgets
● ListBody: A widget that arranges its children sequentially along a given
axis, forcing them to the dimension of the parent in the other axis.
● Table: A widget that uses the table layout algorithm for its children.
● Wrap: A widget that displays its children in multiple horizontal or vertical
runs.
● IndexedStack: A Stack that shows a single child from a list of children.
● LayoutBuilder: Builds a widget tree that can depend on the parent
widget's size.
● CustomMultiChildLayout: A widget that uses a delegate to size and
position multiple children.
● Flow: A widget that implements the flow layout algorithm.
30
Sliver widgets
● Sliver is a portion of the scrollable area which is used to achieve a
custom scrolling effect.
● We can implement all of the scrollable views, such as ListView,
GridView using slivers.
● It is useful while scrolling large numbers of children widgets in a
scrollable area.
● Flutter provides several kinds of slivers, some of them are given below:
○ SliverAppBar
○ SliverList
○ SliverGrid
○ CupertinoSliverNavigationBar
31
Common layout widgets
32
Common layout widgets
● Flutter has a rich library of layout widgets. Here are a few of those
most commonly used.
● Also, the widget pages in the API docs often make suggestions about
similar widgets that might better suit your needs.
● The following widgets fall into two categories:
○ standard widgets from the widgets library,
○ specialized widgets from the Material library.
● Any app can use the widgets library but only Material apps can use the
Material Components library.
33
Common Layout Widgets
❖ Standard widgets
● Container: Adds padding, margins, borders, background color,
or other decorations to a widget.
● GridView: Lays widgets out as a scrollable grid.
● ListView: Lays widgets out as a scrollable list.
● Stack: Overlaps a widget on top of another.
❖ Material widgets
● Card: Organizes related info into a box with rounded corners and
a drop shadow.
● ListTile: Organizes up to 3 lines of text, and optional leading
34
Container
● A commonly used widget that allows customization of its child widget.
● Container widget can be used as an empty placeholder (invisible) to
add space between widgets.
● A BoxDecoration is a great way to customize a Container widget to
create shapes by setting the borderRadius, color, gradient, and
boxShadow properties.
● Many layouts make liberal use of Containers to separate widgets
using padding, or to add borders or margins.
35
Examples (Container)
● This layout consists of a column with
two rows, each containing 2 images.
● A Container is used to change the
background color to a lighter grey.
36
● A Container is also used to add a
rounded border and margins to
each image:
BoxDecoration
37
Column
● A Column widget displays its children vertically.
● It takes a children property containing an array of List.
● 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, MainAxisAlignment, and MainAxisSize can be used to
align and size how much space is occupied on the main axis.
38
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.
39
Column and Row Nesting
● A great way to create unique layouts is to
combine Column and Row widgets.
● Nesting the Column and Row widgets
creates flexible layouts needed for each
circumstance.
● Nesting widgets is at the heart of
designing Flutter UI layouts.
40
41
CARD Widget
● The Card widget is part of the Material Design and has minimal rounded
corners and shadows.
● To group and lay out data, it is a perfect widget to enhance the look of the
UI.
● The elevation property is a value of double, and the higher the number, the
larger the shadow that is cast.
● To customize the shape and borders of the Card widget, you modify the
shape property.
● Some of the shape properties are StadiumBorder, UnderlineInputBorder,
OutlineInputBorder, and others.
42
Card
● By default, a Card shrinks its size to 0 by 0 pixels. You can use
SizedBox to constrain the size of a card.
● In Flutter, a Card features slightly rounded corners and a drop shadow,
giving it a 3D effect.
● Used for presenting related nuggets of information
● Displayed with rounded corners and a drop shadow
● A Card is often used with ListTile. Card
● A Card containing 3 ListTiles and sized by wrapping it with a
SizedBox. A Divider separates the first and second ListTiles.
43
44
Card shape customizations
45
LISTVIEW
● ListView, a column-like widget, automatically provides scrolling when its
content is too long for its render box.
● ListView.builder is used to create an on-demand linear scrollable list of
widgets. Watch https://youtu.be/KJpkjHGiI5A?feature=shared
● When you have a large set of data, the builder is called only for visible
widgets, which is great for performance.
● use the itemBuilder callback to create the list of children widgets.
● the itemBuilder is called only if the itemCount argument is greater than zero.
● the List starts at row 0, not 1. If you have 20 items in the List, it loops from
row 0 to 19.
● The scrollDirection Can be laid out horizontally or vertically.
46
Examples (ListView)
47
ListTile
● Use ListTile, a specialized row widget from the Material library, for
an easy way to create a row containing up to 3 lines of text and optional
leading and trailing icons.
● ListTile is most commonly used in Card or ListView.
● The main properties are leading, trailing, title, and subtitle properties,
but there are others.
● You can also use the onTap and onLongPress callbacks to execute an
action when the user taps the ListTile.
● Usually the leading and trailing properties are implemented with icons,
but you can add any type of widget. Watch
https://youtu.be/l8dj0yPBvgQ?feature=shared
48
49
50
GridView
● Use GridView to lay widgets out as a two-dimensional list.
● GridView provides two pre-fabricated lists, or you can build your own
custom grid.
● Lays widgets out in a grid
● Detects when the column content exceeds the render box and
automatically provides scrolling
● Build your own custom grid with GridView.builder, or use one of the
provided grids:
○ GridView.count allows you to specify the number of columns
○ GridView.extent allows you to specify the maximum pixel
width of a tile
51
GRIDVIEW
● The GridView displays tiles of scrollable widgets in a
grid format.
● The GridView.count and GridView.extent are usually
used with a fixed or smaller data set.
● Using these constructors means that all of the data,
not just visible widgets, is loaded at init.
● If you have a large set of data, the user does not see
the GridView until all data is loaded, which is not a
great user experience (UX). Watch
https://youtu.be/bLOtZDTm4H8?feature=shared
52
Using the GridView.count
● The GridView.count requires the crossAxisCount and the children.
● The crossAxisCount sets the number of tiles to display
● The children is a list of widgets.
● The scrollDirection argument sets the main axis direction for the Grid to
scroll, either Axis .vertical or Axis.horizontal.
● Uses GridView.count to create a grid that’s 2 tiles wide in portrait mode,
and 3 tiles wide in landscape mode.
● The titles are created by setting the footer property for each GridTile.
53
GridView.count
● For the children, you use the List.generate to create your sample data,
a list of values. Watch https://youtu.be/bLOtZDTm4H8?feature=shared
● the entire list of values is built at the same time, not just the visible
rows like the GridView.builder.
● Note for the following sample code, 7,000 records are generated to
show that the GridView.count does not show any data until all of the
records are processed first.
● Usually you use the GridView.count when you need a layout with a
fixed number of tiles in the crossaxis.
● For example, it shows three tiles in portrait and landscape modes.
54
GridView.count
55
GridView.extent
● The GridView.extent requires you to set the maxCrossAxisExtent and
children argument.
● The maxCrossAxisExtent argument sets the maximum size of each tile
for the axis.
● For example, in portrait, it can fit two to three tiles, but when rotating
to landscape, it can fit five to six depending on the screen size .
● use the GridView.extent when you need a layout with the tiles that
need a maximum cross-axis extent.
● in other words, it fits as many tiles that it can depending on screen size.
56
GridView.extent
57
GridView.extent
● Uses GridView.extent to create a
grid
● with tiles a maximum 150 pixels wide
58
GridView.builder
● The GridView.builder constructor is used with a larger, infinite, or
unknown size set of data.
● when you have a large set of data, the builder is called only for visible
widgets.
● you use the itemBuilder to create the list of children widgets.
● the itemBuilder is called only if the itemCount argument is greater
than zero, and it is called as many times as the itemCount value.
59
GridView.builder
60
USING THE STACK
● The Stack widget is commonly used to overlap, position, and align widgets
to create a custom look. Watch https://youtu.be/liEGSeD3Zt8
● Use Stack to arrange widgets on top of a base widget—often an image.
● The first widget in the list of children is the base widget; subsequent
children are overlaid on top of that base widget
● The Stack children list of the widget is either positioned or nonpositioned.
● When you use a Positioned widget, each child widget is placed at the
appropriate location. Watch https://youtu.be/EgtPleVwxBQ
● You can choose to clip children that exceed the render box
● The nonpositioned children are positioned to the alignment property
(Top-Left or Top-Right depending on the environment).
61
Examples (Stack)
● Uses Stack to overlay a Container
(that displays its Text on a
translucent black background) on top
of a CircleAvatar. The Stack
offsets the text using the alignment
property and Alignments.
62
Examples (Stack)
● Uses Stack to overlay an icon
on top of an image.
63
Stack layout showing Image and Text widgets
stacked over the background image
64
Note
● There’s no way a single book or app could cover all of Flutter’s built-in
widgets (or features).
● The intention of this lecture is learning, and although you won’t learn
about every single widget, you will learn how to find and use what
you’re looking for when the time comes.
● You can find all the widgets and their descriptions in the official Widget
Catalog: https://flutter.dev/docs/development/ui/widgets.
65
Lay out a widget
66
Lay out a widget
1. Select a layout widget
2. Create a visible widget
3. Add the visible widget to the layout widget
4. Add the layout widget to the page
● Material apps: use a Scaffold widget, then you can add the
Center widget directly to the body property for the home page.
● Non-Material apps: you can add the Center widget to the app’s
build() method:
67
Lay out multiple widgets vertically and horizontally
❖ One of the most common layout patterns is to arrange widgets
vertically or horizontally.
● Row and Column are two of the most commonly used layout
patterns.
● A child widget can itself be a Row, Column, or other complex
widget.
68
Example
● The following example shows
how it is possible to nest rows
or columns inside of rows or
columns.
● This layout is organized as a
Row. The row contains two
children: a column on the left,
and an image on the right:
69
Aligning widgets
● You control how a row or column aligns its children using the
mainAxisAlignment and crossAxisAlignment properties.
● For a row, the main axis runs horizontally and the cross axis runs vertically.
● For a column, the main axis runs vertically and the cross axis runs
horizontally.
● The MainAxisAlignment and CrossAxisAlignment enums offer a
variety of constants for controlling alignment
70
Aligning widgets Example 1
❖ In the following example,
setting the main axis alignment
to spaceEvenly divides the
free horizontal space evenly
between, before, and after
each image.
71
Aligning widgets Example 2
❖ Columns work the same way as
rows.
❖ setting the main axis alignment
to spaceEvenly divides the
free vertical space evenly
between, above, and below
each image.
72
Expanded Widget
● When a layout is too large to fit a device, a
yellow and black striped pattern appears.
Widgets can be sized to fit within a row or
column by using the Expanded widget.
● wrap each image with an Expanded
widget.
73
Flex Property of Expanded widget
● Perhaps you want a widget to
occupy twice as much space as
its siblings.
● use the Expanded widget
flex property, an integer that
determines the flex factor for a
widget.
● The default flex factor is 1.
74
Packing widgets
❖ By default, a row or column
occupies as much space along
its main axis as possible
❖ if you want to pack the
children closely together, set
its mainAxisSize to
MainAxisSize.min.
75
Nesting Rows and Columns
❖ The outlined section is
implemented as two rows.
➢ The ratings row contains five
stars and the number of
reviews.
➢ The icons row contains three
columns of icons and text.
76
The Widget Trees
The Ratings Row
77
The Icons Row
implement Widgets in variables
and functions
❖ To minimize the visual
confusion that can result from
heavily nested layout code,
implement pieces of the UI in
variables and functions.
78
In-class Activity
79
80
81
82
83
84
Assignment 3
Design the following UI
and draw the widget
tree
85

More Related Content

Similar to Lecture 5 _ Building Layouts (1).pptx

Android Development - ConstraintLayout
Android Development - ConstraintLayoutAndroid Development - ConstraintLayout
Android Development - ConstraintLayoutManuel Vicente Vivo
 
Session 8 - Xcode 5 and interface builder for iOS 7 application
Session 8 - Xcode 5 and interface builder for iOS 7 applicationSession 8 - Xcode 5 and interface builder for iOS 7 application
Session 8 - Xcode 5 and interface builder for iOS 7 applicationVu Tran Lam
 
How to create ui using droid draw
How to create ui using droid drawHow to create ui using droid draw
How to create ui using droid drawinfo_zybotech
 
User experience and interactions design
User experience and interactions design User experience and interactions design
User experience and interactions design Rakesh Jha
 
W1_Lec01_Lec02_Layouts.pptx
W1_Lec01_Lec02_Layouts.pptxW1_Lec01_Lec02_Layouts.pptx
W1_Lec01_Lec02_Layouts.pptxssuserc1e786
 
Getting Started With Material Design
Getting Started With Material DesignGetting Started With Material Design
Getting Started With Material DesignYasin Yildirim
 
Flutter-Festivals Day-2.pptx
Flutter-Festivals Day-2.pptxFlutter-Festivals Day-2.pptx
Flutter-Festivals Day-2.pptxDSCVSSUT
 
Application Development - Overview on Android OS
Application Development - Overview on Android OSApplication Development - Overview on Android OS
Application Development - Overview on Android OSPankaj Maheshwari
 
03.Controls in Windows Phone
03.Controls in Windows Phone03.Controls in Windows Phone
03.Controls in Windows PhoneNguyen Tuan
 
Day 4 android bootcamp
Day 4  android bootcampDay 4  android bootcamp
Day 4 android bootcampFatimaYousif11
 
Baparekraf Digital Talent Day: Monitoring dan Coaching Penerima Fasilitasi BD...
Baparekraf Digital Talent Day: Monitoring dan Coaching Penerima Fasilitasi BD...Baparekraf Digital Talent Day: Monitoring dan Coaching Penerima Fasilitasi BD...
Baparekraf Digital Talent Day: Monitoring dan Coaching Penerima Fasilitasi BD...DicodingEvent
 
Apple Watch Human Interface Guidelines
Apple Watch Human Interface GuidelinesApple Watch Human Interface Guidelines
Apple Watch Human Interface GuidelinesShengWen Chiou
 
Java GUI Programming for beginners-graphics.pdf
Java GUI Programming for beginners-graphics.pdfJava GUI Programming for beginners-graphics.pdf
Java GUI Programming for beginners-graphics.pdfPBMaverick
 

Similar to Lecture 5 _ Building Layouts (1).pptx (20)

Flutter workshop
Flutter workshopFlutter workshop
Flutter workshop
 
Android Development - ConstraintLayout
Android Development - ConstraintLayoutAndroid Development - ConstraintLayout
Android Development - ConstraintLayout
 
leggi
leggileggi
leggi
 
Session 8 - Xcode 5 and interface builder for iOS 7 application
Session 8 - Xcode 5 and interface builder for iOS 7 applicationSession 8 - Xcode 5 and interface builder for iOS 7 application
Session 8 - Xcode 5 and interface builder for iOS 7 application
 
How to create ui using droid draw
How to create ui using droid drawHow to create ui using droid draw
How to create ui using droid draw
 
Mobile Application Development class 003
Mobile Application Development class 003Mobile Application Development class 003
Mobile Application Development class 003
 
User experience and interactions design
User experience and interactions design User experience and interactions design
User experience and interactions design
 
W1_Lec01_Lec02_Layouts.pptx
W1_Lec01_Lec02_Layouts.pptxW1_Lec01_Lec02_Layouts.pptx
W1_Lec01_Lec02_Layouts.pptx
 
Getting Started With Material Design
Getting Started With Material DesignGetting Started With Material Design
Getting Started With Material Design
 
Flutter-Festivals Day-2.pptx
Flutter-Festivals Day-2.pptxFlutter-Festivals Day-2.pptx
Flutter-Festivals Day-2.pptx
 
Drawing Tool
Drawing ToolDrawing Tool
Drawing Tool
 
Application Development - Overview on Android OS
Application Development - Overview on Android OSApplication Development - Overview on Android OS
Application Development - Overview on Android OS
 
03.Controls in Windows Phone
03.Controls in Windows Phone03.Controls in Windows Phone
03.Controls in Windows Phone
 
Introduction of Xcode
Introduction of XcodeIntroduction of Xcode
Introduction of Xcode
 
Day 4 android bootcamp
Day 4  android bootcampDay 4  android bootcamp
Day 4 android bootcamp
 
unity basics
unity basicsunity basics
unity basics
 
Baparekraf Digital Talent Day: Monitoring dan Coaching Penerima Fasilitasi BD...
Baparekraf Digital Talent Day: Monitoring dan Coaching Penerima Fasilitasi BD...Baparekraf Digital Talent Day: Monitoring dan Coaching Penerima Fasilitasi BD...
Baparekraf Digital Talent Day: Monitoring dan Coaching Penerima Fasilitasi BD...
 
Apple Watch Human Interface Guidelines
Apple Watch Human Interface GuidelinesApple Watch Human Interface Guidelines
Apple Watch Human Interface Guidelines
 
Swift
SwiftSwift
Swift
 
Java GUI Programming for beginners-graphics.pdf
Java GUI Programming for beginners-graphics.pdfJava GUI Programming for beginners-graphics.pdf
Java GUI Programming for beginners-graphics.pdf
 

Lecture 5 _ Building Layouts (1).pptx

  • 1. Lecture 5 : Building Layouts T. Fatima Al-azazi
  • 2. 2
  • 3. Agenda ● Basic Widgets ● Single-Child Layout Widgets ● Multi-child Layout Widgets ● Common Layout Widgets ● How to Lay out a Widget by Example ● In-Class Activity 3
  • 5. Structural widgets ● There are a few convenience widgets that you’ll likely use in every Flutter app you build. They provide configuration and structure to your app, with little work from you. ○ MaterialApp widget ○ Scaffold ○ AppBar ○ Theme 5
  • 6. MaterialApp widget ● An extension of the generic top-level widget: WidgetsApp. ● WidgetsApp is a convenience widget that abstracts away a number of features required for most mobile apps, such as setting up a navigator and using an appwide theme. ● WidgetsApp requires more work to set up than MaterialApp or CupertinoApp ● MaterialApp provides ○ a ton of benefits that affect its entire widget subtree. ○ provides configuration and functionality to your app. 6
  • 7. Using Material Components ● A Material app starts with the MaterialApp widget, which builds a number of useful widgets at the root of your app, including a Navigator, which manages a stack of widgets. ● The Navigator lets you transition smoothly between screens of your application. ● Material app implements the animations that happen when a user navigates between pages. ● MaterialApp takes care of the appwide theme . ● Home property represents the app’s home page, which can be any widget. 7
  • 8. The Scaffold widget ● Scaffold is a designed to make applications as easy as possible to build. ● Scaffold is the widget that gives your app structure. ● Scaffold defines the “basic Material Design visual layout,” which means it can make your app look like this pretty easily. ● The Scaffold widget provides many optional features, pick and choose which features you want. ● It’s common for each of the different screens in your application to have its own Scaffold widget. 8
  • 9. The Scaffold widget ● It provides functionality to add ○ a drawer (an element that animates in from one Listing ○ a bottom sheet (an element that animates into view from the bottom of the screen). ○ the AppBar in a scaffold is automatically set up to display a menu button in the top-left corner of your app, which will open the drawer; ○ Body is a Scaffold argument that represents the main portion of the screen. ● If there is no app bar, body is essentially the entire screen. 9
  • 11. AppBar widget ● Typically used in the Scaffold.appBar property, which fixes it to the top of the screen with a certain height. ● The most notable feature of AppBar is that it provides navigation features for free. It automatically inserts a menu button if the app bar’s parent is a scaffold and the drawer argument isn’t null. ● And if the Navigator of your app detects that you’re on a page that can navigate “back” (like a browser’s back button), it automatically inserts a back button. 11
  • 12. AppBar widget ● Usually contains the standard title, toolbar, leading, and actions properties (along with buttons), as well as many customization options. ● The property that handles these menu buttons and back buttons is called the leading action. ● If you don’t want a menu button to appear, You can set AppBar.automaticallyImplyLeading to false and then pass the leading argument to whatever widget you wish. 12
  • 13. AppBar Properties ● The title property is typically implemented with a Text widget. ● The leading property is displayed before the title property. Usually this is an IconButton or BackButton. ● The actions property is a list of widgets aligned to the upper right of an AppBar widget usually with an IconButton or PopupMenuButton. ● The flexibleSpace property is stacked behind the Toolbar or TabBar widget. ● A background image is commonly applied to the flexibleSpace property, but any widget, such as an Icon, could be used. 13
  • 14. ThemeData widget ● allows you to set many default styles in your app, such as colors, font styles, button styles, and more. ● Theme will be automatically applied throughout your app. ● some of the properties you can set on the widget that will permeate throughout the app: ○ brightness ○ primarySwatch ○ primaryColor ○ accentColor ● Watch https://youtu.be/oTvQDJOBXmM?feature=shared 14
  • 15. SafeArea ● Necessary for today’s devices such as the iPhone X or Android devices with a notch (a partial cut-out obscuring the screen usually located on the top portion of the device). ● Automatically adds sufficient padding to the child widget to avoid intrusions by the operating system. 15
  • 16. RichText ● A great way to display text using multiple styles. ● The RichText widget takes TextSpans as children to style different parts of the strings. ● There are two main parts to styling, the default text property and the children list of TextSpan. ● The text property using a TextSpan sets the default styling for the RichText. ● The children list of TextSpan allows you to use multiple TextSpan objects to format different strings. 16
  • 17. IMAGES ● Images can make an app look tremendous or ugly depending on the quality of the artwork. Images, icons, and other resources are commonly embedded in an app. ● The AssetBundle class provides access to custom resources such as images, fonts, audio, data files, and more. Before a Flutter app can use a resource, you must declare it in the pubspec.yaml file. 17
  • 18. Image Widget ● The Image widget displays an image from a local or URL (web) source. ● To load an Image widget, there are a few different constructors to use. 18
  • 19. 19
  • 20. Silhouette -Style Image ● If you add color to the image, it colorizes the image portion and leaves any transparencies alone, giving a silhouette look 20
  • 21. orientation ● You can detect device orientation by calling MediaQuery.of(context).orientation, which returns either a portrait or landscape value. ● There is also OrientationBuilder, which returns the amount of space available to the parent to figure out the orientation. 21
  • 23. Layouts in Flutter ● The core of Flutter’s layout mechanism is widgets. ● Things you don’t see are also widgets, such as the rows, columns, and grids that arrange, constrain, and align the visible widgets. ● You create a layout by composing widgets to build more complex widgets. For example, the first screenshot below shows 3 icons with a label under each one. 23
  • 24. widget tree for this UI 24
  • 25. Layout widgets ● Layout widgets arrange other widgets columns, rows, grids, and many other layouts. ● Single-child layout widgets ● Multi-child layout widgets ● Sliver widgets 25
  • 26. Single-child layout widgets ● Center: A widget that centers its child within itself. ● Container: A convenience widget that combines common painting, positioning, and sizing widgets. ● Expanded: A widget that expands a child of a Row, Column, or Flex. ● Padding: A widget that insets its child by the given padding. ● SizedBox: A box with a specified size. If given a child, this widget forces its child to have a specific width and/or height ● ConstrainedBox:A widget that imposes additional constraints on its child. 26
  • 27. Single-child layout widgets ● CustomSingleChildLayout: A widget that defers the layout of its single child to a delegate. ● FittedBox: Scales and positions its child within itself according to fit. ● FractionallySizedBox: A widget that sizes its child to a fraction of the total available space. ● IntrinsicHeight: A widget that sizes its child to the child's intrinsic height. ● IntrinsicWidth: A widget that sizes its child to the child's intrinsic width. ● Baseline: A widget that positions its child according to the child's baseline. ● LimitedBox: A box that limits its size only when it's unconstrained. 27
  • 28. Single-child layout widgets ● Offstage: A widget that lays the child out as if it was in the tree, but without painting anything, without making the child available for hit. ● OverflowBox: A widget that imposes different constraints on its child than it gets from its parent, possibly allowing the child to overflow the parent. ● SizedOverflowBox: A widget that is a specific size but passes its original constraints through to its child, which will probably overflow. ● Transform: A widget that applies a transformation before painting its child. ● Align: A widget that aligns its child within itself and optionally sizes itself based on the child's size. ● AspectRatio: A widget that attempts to size the child to a specific aspect ratio. 28
  • 29. Multi-child layout widgets ● Column: Layout a list of child widgets in the vertical direction. ● Row: Layout a list of child widgets in the horizontal direction. ● GridView: A grid list consists of a repeated pattern of cells arrayed in a vertical and horizontal layout. ● ListView: A scrollable, linear list of widgets. ListView is the most commonly used scrolling widget. It displays its children one after another in the scroll direction. ● Stack: This class is useful if you want to overlap several children in a simple way, for example having some text and an image, overlaid with. 29
  • 30. Multi-child layout widgets ● ListBody: A widget that arranges its children sequentially along a given axis, forcing them to the dimension of the parent in the other axis. ● Table: A widget that uses the table layout algorithm for its children. ● Wrap: A widget that displays its children in multiple horizontal or vertical runs. ● IndexedStack: A Stack that shows a single child from a list of children. ● LayoutBuilder: Builds a widget tree that can depend on the parent widget's size. ● CustomMultiChildLayout: A widget that uses a delegate to size and position multiple children. ● Flow: A widget that implements the flow layout algorithm. 30
  • 31. Sliver widgets ● Sliver is a portion of the scrollable area which is used to achieve a custom scrolling effect. ● We can implement all of the scrollable views, such as ListView, GridView using slivers. ● It is useful while scrolling large numbers of children widgets in a scrollable area. ● Flutter provides several kinds of slivers, some of them are given below: ○ SliverAppBar ○ SliverList ○ SliverGrid ○ CupertinoSliverNavigationBar 31
  • 33. Common layout widgets ● Flutter has a rich library of layout widgets. Here are a few of those most commonly used. ● Also, the widget pages in the API docs often make suggestions about similar widgets that might better suit your needs. ● The following widgets fall into two categories: ○ standard widgets from the widgets library, ○ specialized widgets from the Material library. ● Any app can use the widgets library but only Material apps can use the Material Components library. 33
  • 34. Common Layout Widgets ❖ Standard widgets ● Container: Adds padding, margins, borders, background color, or other decorations to a widget. ● GridView: Lays widgets out as a scrollable grid. ● ListView: Lays widgets out as a scrollable list. ● Stack: Overlaps a widget on top of another. ❖ Material widgets ● Card: Organizes related info into a box with rounded corners and a drop shadow. ● ListTile: Organizes up to 3 lines of text, and optional leading 34
  • 35. Container ● A commonly used widget that allows customization of its child widget. ● Container widget can be used as an empty placeholder (invisible) to add space between widgets. ● A BoxDecoration is a great way to customize a Container widget to create shapes by setting the borderRadius, color, gradient, and boxShadow properties. ● Many layouts make liberal use of Containers to separate widgets using padding, or to add borders or margins. 35
  • 36. Examples (Container) ● This layout consists of a column with two rows, each containing 2 images. ● A Container is used to change the background color to a lighter grey. 36 ● A Container is also used to add a rounded border and margins to each image:
  • 38. Column ● A Column widget displays its children vertically. ● It takes a children property containing an array of List. ● 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, MainAxisAlignment, and MainAxisSize can be used to align and size how much space is occupied on the main axis. 38
  • 39. 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. 39
  • 40. Column and Row Nesting ● A great way to create unique layouts is to combine Column and Row widgets. ● Nesting the Column and Row widgets creates flexible layouts needed for each circumstance. ● Nesting widgets is at the heart of designing Flutter UI layouts. 40
  • 41. 41
  • 42. CARD Widget ● The Card widget is part of the Material Design and has minimal rounded corners and shadows. ● To group and lay out data, it is a perfect widget to enhance the look of the UI. ● The elevation property is a value of double, and the higher the number, the larger the shadow that is cast. ● To customize the shape and borders of the Card widget, you modify the shape property. ● Some of the shape properties are StadiumBorder, UnderlineInputBorder, OutlineInputBorder, and others. 42
  • 43. Card ● By default, a Card shrinks its size to 0 by 0 pixels. You can use SizedBox to constrain the size of a card. ● In Flutter, a Card features slightly rounded corners and a drop shadow, giving it a 3D effect. ● Used for presenting related nuggets of information ● Displayed with rounded corners and a drop shadow ● A Card is often used with ListTile. Card ● A Card containing 3 ListTiles and sized by wrapping it with a SizedBox. A Divider separates the first and second ListTiles. 43
  • 44. 44
  • 46. LISTVIEW ● ListView, a column-like widget, automatically provides scrolling when its content is too long for its render box. ● ListView.builder is used to create an on-demand linear scrollable list of widgets. Watch https://youtu.be/KJpkjHGiI5A?feature=shared ● When you have a large set of data, the builder is called only for visible widgets, which is great for performance. ● use the itemBuilder callback to create the list of children widgets. ● the itemBuilder is called only if the itemCount argument is greater than zero. ● the List starts at row 0, not 1. If you have 20 items in the List, it loops from row 0 to 19. ● The scrollDirection Can be laid out horizontally or vertically. 46
  • 48. ListTile ● Use ListTile, a specialized row widget from the Material library, for an easy way to create a row containing up to 3 lines of text and optional leading and trailing icons. ● ListTile is most commonly used in Card or ListView. ● The main properties are leading, trailing, title, and subtitle properties, but there are others. ● You can also use the onTap and onLongPress callbacks to execute an action when the user taps the ListTile. ● Usually the leading and trailing properties are implemented with icons, but you can add any type of widget. Watch https://youtu.be/l8dj0yPBvgQ?feature=shared 48
  • 49. 49
  • 50. 50
  • 51. GridView ● Use GridView to lay widgets out as a two-dimensional list. ● GridView provides two pre-fabricated lists, or you can build your own custom grid. ● Lays widgets out in a grid ● Detects when the column content exceeds the render box and automatically provides scrolling ● Build your own custom grid with GridView.builder, or use one of the provided grids: ○ GridView.count allows you to specify the number of columns ○ GridView.extent allows you to specify the maximum pixel width of a tile 51
  • 52. GRIDVIEW ● The GridView displays tiles of scrollable widgets in a grid format. ● The GridView.count and GridView.extent are usually used with a fixed or smaller data set. ● Using these constructors means that all of the data, not just visible widgets, is loaded at init. ● If you have a large set of data, the user does not see the GridView until all data is loaded, which is not a great user experience (UX). Watch https://youtu.be/bLOtZDTm4H8?feature=shared 52
  • 53. Using the GridView.count ● The GridView.count requires the crossAxisCount and the children. ● The crossAxisCount sets the number of tiles to display ● The children is a list of widgets. ● The scrollDirection argument sets the main axis direction for the Grid to scroll, either Axis .vertical or Axis.horizontal. ● Uses GridView.count to create a grid that’s 2 tiles wide in portrait mode, and 3 tiles wide in landscape mode. ● The titles are created by setting the footer property for each GridTile. 53
  • 54. GridView.count ● For the children, you use the List.generate to create your sample data, a list of values. Watch https://youtu.be/bLOtZDTm4H8?feature=shared ● the entire list of values is built at the same time, not just the visible rows like the GridView.builder. ● Note for the following sample code, 7,000 records are generated to show that the GridView.count does not show any data until all of the records are processed first. ● Usually you use the GridView.count when you need a layout with a fixed number of tiles in the crossaxis. ● For example, it shows three tiles in portrait and landscape modes. 54
  • 56. GridView.extent ● The GridView.extent requires you to set the maxCrossAxisExtent and children argument. ● The maxCrossAxisExtent argument sets the maximum size of each tile for the axis. ● For example, in portrait, it can fit two to three tiles, but when rotating to landscape, it can fit five to six depending on the screen size . ● use the GridView.extent when you need a layout with the tiles that need a maximum cross-axis extent. ● in other words, it fits as many tiles that it can depending on screen size. 56
  • 58. GridView.extent ● Uses GridView.extent to create a grid ● with tiles a maximum 150 pixels wide 58
  • 59. GridView.builder ● The GridView.builder constructor is used with a larger, infinite, or unknown size set of data. ● when you have a large set of data, the builder is called only for visible widgets. ● you use the itemBuilder to create the list of children widgets. ● the itemBuilder is called only if the itemCount argument is greater than zero, and it is called as many times as the itemCount value. 59
  • 61. USING THE STACK ● The Stack widget is commonly used to overlap, position, and align widgets to create a custom look. Watch https://youtu.be/liEGSeD3Zt8 ● Use Stack to arrange widgets on top of a base widget—often an image. ● The first widget in the list of children is the base widget; subsequent children are overlaid on top of that base widget ● The Stack children list of the widget is either positioned or nonpositioned. ● When you use a Positioned widget, each child widget is placed at the appropriate location. Watch https://youtu.be/EgtPleVwxBQ ● You can choose to clip children that exceed the render box ● The nonpositioned children are positioned to the alignment property (Top-Left or Top-Right depending on the environment). 61
  • 62. Examples (Stack) ● Uses Stack to overlay a Container (that displays its Text on a translucent black background) on top of a CircleAvatar. The Stack offsets the text using the alignment property and Alignments. 62
  • 63. Examples (Stack) ● Uses Stack to overlay an icon on top of an image. 63
  • 64. Stack layout showing Image and Text widgets stacked over the background image 64
  • 65. Note ● There’s no way a single book or app could cover all of Flutter’s built-in widgets (or features). ● The intention of this lecture is learning, and although you won’t learn about every single widget, you will learn how to find and use what you’re looking for when the time comes. ● You can find all the widgets and their descriptions in the official Widget Catalog: https://flutter.dev/docs/development/ui/widgets. 65
  • 66. Lay out a widget 66
  • 67. Lay out a widget 1. Select a layout widget 2. Create a visible widget 3. Add the visible widget to the layout widget 4. Add the layout widget to the page ● Material apps: use a Scaffold widget, then you can add the Center widget directly to the body property for the home page. ● Non-Material apps: you can add the Center widget to the app’s build() method: 67
  • 68. Lay out multiple widgets vertically and horizontally ❖ One of the most common layout patterns is to arrange widgets vertically or horizontally. ● Row and Column are two of the most commonly used layout patterns. ● A child widget can itself be a Row, Column, or other complex widget. 68
  • 69. Example ● The following example shows how it is possible to nest rows or columns inside of rows or columns. ● This layout is organized as a Row. The row contains two children: a column on the left, and an image on the right: 69
  • 70. Aligning widgets ● You control how a row or column aligns its children using the mainAxisAlignment and crossAxisAlignment properties. ● For a row, the main axis runs horizontally and the cross axis runs vertically. ● For a column, the main axis runs vertically and the cross axis runs horizontally. ● The MainAxisAlignment and CrossAxisAlignment enums offer a variety of constants for controlling alignment 70
  • 71. Aligning widgets Example 1 ❖ In the following example, setting the main axis alignment to spaceEvenly divides the free horizontal space evenly between, before, and after each image. 71
  • 72. Aligning widgets Example 2 ❖ Columns work the same way as rows. ❖ setting the main axis alignment to spaceEvenly divides the free vertical space evenly between, above, and below each image. 72
  • 73. Expanded Widget ● When a layout is too large to fit a device, a yellow and black striped pattern appears. Widgets can be sized to fit within a row or column by using the Expanded widget. ● wrap each image with an Expanded widget. 73
  • 74. Flex Property of Expanded widget ● Perhaps you want a widget to occupy twice as much space as its siblings. ● use the Expanded widget flex property, an integer that determines the flex factor for a widget. ● The default flex factor is 1. 74
  • 75. Packing widgets ❖ By default, a row or column occupies as much space along its main axis as possible ❖ if you want to pack the children closely together, set its mainAxisSize to MainAxisSize.min. 75
  • 76. Nesting Rows and Columns ❖ The outlined section is implemented as two rows. ➢ The ratings row contains five stars and the number of reviews. ➢ The icons row contains three columns of icons and text. 76
  • 77. The Widget Trees The Ratings Row 77 The Icons Row
  • 78. implement Widgets in variables and functions ❖ To minimize the visual confusion that can result from heavily nested layout code, implement pieces of the UI in variables and functions. 78
  • 80. 80
  • 81. 81
  • 82. 82
  • 83. 83
  • 84. 84
  • 85. Assignment 3 Design the following UI and draw the widget tree 85