You are on page 1of 51

Lecture 3:

z Basic Flutter Widgets

Robel M
z
Flutter File Structure

▪ The file structure is the organization of the data of an application. The


file structure is something that plays a very important role in the
effective and easy management of the project be it of any size. As the
size of a project grows, it becomes more and more important to have
a proper structure and format for the code
z
A. Assets: static assets for the app

▪ This directory is on the root level will contain all the static assets that are
used in the application, for example, fonts, icons, logos, background
images, demo videos, etc. It is very much recommended that we should
have different directories for a different type of data for example images,
videos & logos, should have a different folder of their own so that it
becomes easier to maintain and access them.
z
B. lib: Entire code of the Application

▪ Lib: This is the most important folder in the


project, used to write most of the dart code.
By default, the lib folder contains the main.
dart file, which is the application's entry point.
This configuration, however, can be changed.
z
Potential subfolders in lib folder

▪ Screens

▪ Providers

▪ Service

▪ Theme

▪ Models

▪ Blocs


z
C: test

▪ Testing codes
z
D: Android

▪ Android configuration folder

- build.gradle

- AndroidManifest.xml
z
E. ios

▪ Ios configuration files

- Runner

- pods
z
G. Pubspec.yaml

▪ Every Flutter project includes a pubspec.yaml file, often referred to as the


pubspec. A basic pubspec is generated when you create a new Flutter
project. It’s located at the top of the project tree and contains metadata
about the project that the Dart and Flutter tooling needs to know.
▪ The pubspec file specifies dependencies that the project requires, such as
particular packages (and their versions), fonts, or image files. It also specifies
other requirements, such as dependencies on developer packages (like
testing or mocking packages), or particular constraints on the version of the
Flutter SDK.
z

Flutter Code organization


z
main.dart

▪ The foundation of any Flutter app, the main.dart file, should hold very little
code and only serve as an overview to an app.

▪ The widget being run by runApp should be a StatelessWidget, and the itself
should be no more complicated than a simple MaterialApp.

▪ The MaterialApp itself should have no heavy code in it, instead pulling the
Theme and the widget screens from other files.
z void main() {

runApp(ExampleApp());

class ExampleApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'ExampleApp’,

initialRoute: '/',

routes: <String, WidgetBuilder>{

"/": (BuildContext context) => ExScreen1(),

"/ExScreen2": (BuildContext context) => ExScreen2(),}, ),};}


z

User Interface Design


Flutter Basic Widgets
z Layouts in Flutter
z

▪ The core of Flutter’s layout mechanism is widgets. In Flutter,


almost everything is a widget—even layout models are widgets.
The images, icons, and text that you see in a Flutter app are all
widgets. But things you don’t see are also widgets, such as the
rows, columns, and grids that arrange, constrain, and align the
visible widgets.
z
Widget

▪ Widgets describe what their view should look like given their current
configuration and state. When a widget’s state changes, the widget rebuilds
its description, which the framework diffs against the previous description in
order to determine the minimal changes needed in the underlying render tree
to transition from one state to the next.
z
Stateless widget

▪ A widget that does not require mutable state.


z

class name extends StatelessWidget {

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

@override

Widget build(BuildContext context) {

return Container();

}
z
Stateful Widget

▪ A stateful Widget means a widget that has a mutable state


z

class Employee extends StatefulWidget {

Employee({Key? key}) : super(key: key);


@override

_Employee State createState() => _Employee State();

}
class _Employee State extends State< Employee > {

@override

Widget build(BuildContext context) {

return Container();

}
z
import
'package:flutter/material.dart';

void main() { The runApp() function takes the


runApp( given Widget and makes it the root
of the widget tree.
const Center(
In this example, the widget tree
child: Text(
consists of two widgets,
'Hello, world!' the Center widget and its child,
),
the Text widget.

),

);}
z

▪ When writing an app, you’ll commonly author new widgets


that are subclasses of either StatelessWidget or StatefulWidget,
depending on whether your widget manages any state. A
widget’s main job is to implement a build() function, which
describes the widget in terms of other, lower-level widgets.
z
MaterialApp

▪ 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 identified by
strings, also known as “routes”. The Navigator lets you transition
smoothly between screens of your application. Using
the MaterialApp widget is entirely optional but a good practice.
z
Scaffold
▪ The scaffold will expand to fill the available space. That
usually means that it will occupy its entire window or device
screen

▪ Elements
✓ AppBar

✓ BottomAppBar

✓ FloatingActionButton

✓ BottomSheet

✓ Drawer

body: is the primary content of the scaffold


z AppBar

▪ Which is a horizontal bar typically shown at the top of an app using


the appBar property.

▪ App bars typically expose one or more common actions with IconButtons
which are optionally followed by a PopupMenuButton for less common
operations (sometimes called the "overflow menu").
appBar: AppBar(

leading:Text('') ,

title: Text('') ,

actions: [],

),.
z
Drawer
▪ A panel displayed to the side of the body, often hidden
on mobile devices.

▪ You can easily add to Scaffold widget:

drawer: Drawer(

child: ListView()

),
z

Text
▪ The Text widget lets you create a run of styled
text within your application.

Attributes:
Text(“HELLO!”, style: TextStyle(fontSize: 14, fontweight:
FontWeight.bold))
z

Single Child Widgets


z
Container
▪ The Container widget lets you create a rectangular visual
element. A container can be decorated with a BoxDecoration,
such as a background, a border, or a shadow.

▪ A Container can also have margins, padding, and constraints


applied to its size.
Container(
child: Text(‘’)

)
z
Icon

Icon(
child: Icons.home,
color:Colors.red,
size: 10,

▪ Icon widget have on tap functionality, but you can wrap this widget with other
widgets
z
IconButton

IconButton(

icon: const Icon(Icons.volume_up),

tooltip: ‘this is tooltip',

onPressed: () {

setState(() {

// do somthing

});

},

),
z Image

▪ NetworkImage(String url): this widget is user to read image


from the network/remote server

▪ Image.asset(String image_path): this widget helps to read


image from local asset folder.

▪ Image.file(File file): read image from file

▪ Image.memory(Uint8List byte): read an image from byte array


z
TextButton

TextButton(

style: TextButton.styleFrom(

textStyle: const TextStyle(fontSize: 20),

),

onPressed: () {},

child: const Text('Enabled'),

),
z Inkwell
❖ Inkwell is A rectangular area of a Material that responds
to touch.
InkWell(

child: Text(“ ”),

onTap: () {},

onDoubleTap: () {},

onLongPress: () {},

),
z Gesture Detector
▪ A widget that detects gestures.

▪ Attempts to recognize gestures that correspond to its non-null callbacks.


GestureDetector(

child: Text(“check”),

onLongPress: () {},

onLongPressStart: () {},

onLongPressUp: () {},

onLongPressDown: () {},

onLongDoubleTap () {},

),
z

Center

▪ To make Widget element to center of the container widget(upper


father widget)
Center(

child: Text(“Centered Text”);

)
z
Card

▪ A material design card: a panel with slightly rounded


corners and an elevation shadow.
Card(

elevation: 2, // the size of the shadow below the card

color: Colors.red, // childs background color

child: ListView(

)
z
Reading Assignments

▪ Flexible

▪ Expanded

▪ SizedBox
z

Multi Child Layout Widgets


z
Column

▪ A widget that displays its children in a vertical array.

▪ To cause a child to expand to fill the available vertical space,


wrap the child in an Expanded widget.
Column(
children:<Widget> [
Text(“Hello”),
Container()

])
z
Row

▪ A widget that displays its children in a horizontal array.

▪ To cause a child to expand to fill the available horizontal space, wrap the
child in an Expanded widget.

Row(

children:<Widget> [
Text(“Hello”),
Container()

])
z
Wrap

▪ Displays its children in multiple horizontal or vertical runs

▪ A Wrap lays out each child and attempts to place the child adjacent to the previous
child in the main axis, given by direction, leaving spacing space in between. If there is
not enough space to fit the child, Wrap creates a new run adjacent to the existing
children in the cross axis.
Wrap(
direction: Axis.horizontal,

children: <Widget>[ ]

)
z
▪ ListView is the most commonly used
Listview
scrolling widget. It displays its
children one after another in the
scroll direction. In the cross axis, the
children are required to fill
the ListView.
ListView(

children: <Widget>[
Container( height: 50, color: Colors.blue),

Container( height: 50 , color: Colors.green),

])
z

Stack
▪ Instead of being linearly oriented (either horizontally or
vertically), a Stack widget lets you place widgets on top of
each other in paint order. You can then use
the Positioned widget on children of a Stack to position them
relative to the top, right, bottom, or left edge of the stack.
Stacks are based on the web’s absolute positioning
layout model.
z GridView

▪ In some cases, you might want to display your items as a


grid rather than a normal list of items that come one after
the next. For this task, use the GridView widget.

▪ The simplest way to get started using grids is by using


the GridView.count() constructor, because it allows you to
specify how many rows or columns you’d like.
z GridView cont…
GridView.count(

// Create a grid with 2 columns. If you change the scrollDirection to

//horizontal, this produces 2 rows.

crossAxisCount: 2, // Generate 100 widgets that display their index in the List.

children: List.generate(100, (index) {

return Center(

child: Text( 'Item $index'),

);

}),

);
z
Listview Builder

If the number of ui elements to be printed is unknown builder functions can be used to


iterate n times over the data to print widgets many times.

ListView.builder(
itemCount: entries.length,
itemBuilder: (BuildContext context, int index) {
return Container(
child: Text('Entry ‘),

);

} );

Related: GridView.builder
z

Navigation and Routing


z

▪ Navigator.pushNamed(context, “/path”)

▪ Navigator.push(context, MaterialPageRoute(builder: (context)=>


Home()))

▪ Navitor.pop(context)
z

MaterialApp(
title: 'Named Routes Demo’,
initialRoute: ‘/’,
routes: {
‘/': (context) => const FirstScreen(),
‘/second': (context) => const SecondScreen(), },
)
z

THANK YOU!

You might also like