0% found this document useful (0 votes)
27 views95 pages

ADF Unit 2 StarterProjectTemplatesWidgetCommonWidgetsGestureWidget

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

ADF Unit 2 StarterProjectTemplatesWidgetCommonWidgetsGestureWidget

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

APP DEVELOPMENT USING FLUTTER

01CE0610

Unit 2
Starter Project Template,
Common Widgets, Gestures Widget

Presented by: Prof. Harsh Nagar


Contents
● Create Flutter Project
● Important Packages
● “Hello World”Program
● Scafflod
● const
● Widgets
● Layout
● Stateless And Stateful Widget
● Login page Example
● Form Widget
● Custom Gesture
● Navigation Widget
Create Flutter Project
● Step 1: File -> New Flutter Project -> Select Flutter Option
● Step 2 : Give SDK path Of Flutter (C:/src/flutter) -> Next
Create Flutter Project
● Step 3 : Give Project name, Provide location -> Click on Create option.
Create Flutter Project
● Step 4 : Go to device manager and run VM
● Step 5: Run the main.dart file. (shift +f10).

Run
Important Packages

● The Following files were created when you created a new Flutter project.

● lib/: This directory contains the Dart code files for your Flutter application. The
main.dart file is the entry point for your app.

● Android/ios/windows /web : These folders that carry platform names like


Android or macOS or Web or Windows simply contain platform specific files.

○ Flutter Manage, Change and Configure those based on needs.


○ Publish an app to a specific platform, the files and folders in the respective
platform folder will become important.
Important Packages

● Build/: It only contains temporary files and output files generated by Flutter as it
builds your app for different target platforms.

● Test/: you could write code that tests your main application code. You could define
automated tests, which can be very useful for catching errors early and for making
sure that you don't have to test everything manually.

● .gitignore: is a file that's used by Git, this version controlled software, which you can
use for managing code snapshots and going back to snapshots if you messed
something up, for example Flutter Manage, Change and Configure those based on
needs.
Important folders

● .metadata: is actually a file that is managed automatically by Flutter to keep track


of some internal information and metadata about your project.

● analysisoptions.yaml: file configures some Flutter and Dart tooling that's being
used by your code editor to show you warnings and errors in your code before
you even run the app which is amazing for catching errors early.

● pubspec.yaml: This YAML file defines your Flutter project's dependencies,


metadata, and other configuration settings. In the provided example, it specifies
the project's name, description, version, and required dependencies such as http
and provider.
Important folders

● pubspec.lock: file records the exact versions of these dependencies that were
resolved during the last dependency resolution process, ensuring consistency
across development environments and facilitating reproducible builds.

● firstapp.xml:It contains more metadata and information for building your Flutter
app for different platforms.

● assets/: This directory is used to store static assets such as images, fonts, and
configuration files
The “Hello World” Program
main.dart
import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
home: Text("Hello World"),
),
);
}
The “Hello World” Program
● import 'package:flutter/material.dart';

○ imports the Flutter material library


○ contains widgets and classes for building user interfaces following the
Material Design guidelines.
○ MaterialApp, Text, Scaffold, etc.

● void main()

○ main function, which serves as the entry point of the Dart program.
○ typically calls the runApp function to start the application.
The “Hello World” Program

● runApp(

MaterialApp(

○ runApp function takes a widget as its argument and starts the Flutter application
○ MaterialApp is a widget that configures the top-level MaterialApp settings, like
theme, home, and navigation.

● home: Text("Hello World"),

○ Home is property use for set and display widget on the screen. The Text widget
displays a string of text on the screen.
What Is Scafflod
● Scaffold is a basic skeletal structure for a Material Design app. It provides a visual
structure that includes the common elements needed in many apps, such as an app
bar, a body for the main content, and potentially a bottom navigation bar.

● Provide the Three main components:

○ AppBar with various properties like title, actions, and backgroundColor.


○ body property is where you define the main content of your app.
○ BottomNavigationBar :if your app has multiple screens or sections, you might
include a BottomNavigationBar at the bottom of the Scaffold.
Using Scaffold
main.dart
import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
home: Scaffold(
body: Text("Hello World"),
),
),
);
}
debugShowCheckedCodeBanner
main.dart
import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text('My App'),
),
body: Center( ● debugShowCheckedCodeBanner
child: Text('Hello World'),
), ○ True: banner of debug shows on running app.
),
), ○ False: banner of debug not show on running app.
);
}
What is Const?
main.dart
import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text('My App'),
), ● Const: helps Dart optimize runtime Performance
body: const Center(
child: Text('Hello World'), ○ const is used to declare a constant widget.
), ○ In Flutter, you can use const to create widgets or values that
), won't change during the lifetime of the application.
),
); ○ It reuse the memory.
}
“Hello World” Program Using Scaffold
main.dart
import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text('My App'),
),
body: const Center(
child: Text('Hello World'),
),
),
),
);
}
Widgets
● Text ● OutlinedButton

● Image ● ElevatedButton

● Icon
● Floating Button

● RichText
● Container

● Row

● Cloumn

● TextField

● TextButton
Text
● Displays a paragraph of text.
Property Description
data The actual text content to be displayed by the Text widget.
Defines the style of the text, including properties like fontSize, color, fontWeight,
style
fontStyle, etc.

textAlign Specifies the alignment of the text within its container.

textDirection Defines the direction of the text, such as ltr (left-to-right) or rtl (right-to-left).

overflow Specifies how overflowing text should be handled.


Text
import 'package:flutter/material.dart'; fontWeight: FontWeight.bold,
color: Colors.blue,
void main() { overflow: TextOverflow.ellipsis,
runApp( ),
MaterialApp( ),
home: Scaffold( ),
),
appBar: AppBar( );
title: Text('Text Widget Example'), }
),

body: Text(
'Hello, Flutter!',

style: TextStyle(
fontSize: 24.0,
Image
● The Image widget in Flutter is used to display images within your application.
● Image Sources:
○ Local Images: You can use images stored locally in your project by referencing
them through their file paths.
○ Network Images: Display images from the internet by providing a URL.

● Image Formats:
○ Flutter supports various image formats, including PNG, JPEG, GIF, WebP, and
more.
Image
Property Description

The image to be displayed by the Image widget. This can be an asset image,
image
network image, memory image, etc.

width The width of the image.

height The height of the image.

fit How the image should be inscribed into the space allocated by its parent.

alignment How the image should be aligned within its parent widget.
Image
import 'package:flutter/material.dart'; );
}
void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Image Widget Example'),
),
body: Image.asset(
'assets/image.jpg',
width: 200,
height: 200,
alignment: Alignment.center,
fit: BoxFit.cover,
),
),
),
Icon
● Icon :
○ The Icon widget uses a specific icon to represent an action or an object.
○ Icons can be chosen from predefined sets such as Icons.materialIcons or
Icons.cupertinoIcons.

Property Description
The graphical symbol to be displayed by the Icon widget. This can be a built-in icon
icon
provided by the Icons class or a custom icon.

size The size of the icon.


color The color of the icon.
semanticLabel A brief description of the icon for accessibility purposes.
Icon
import 'package:flutter/material.dart'; ),
),
void main() { );
runApp( }
MaterialApp(
home: Scaffold(

appBar: AppBar(
title: Text('Icon Widget Example'),
),

body: Icon(

Icons.favorite,
size: 50.0,
color: Colors.red,
semanticLabel: 'Favorite',
),
Container
● The Container widget is a versatile box model that can contain and decorate other
widgets.

Property Description
child The widget that is contained within the Container
alignment Aligns the child within the Container.
Margin Provides space outside the Container.
padding Provides space inside the Container.
color Sets the background color of the Container.
width The width of the container.
Height The height of the container.
Allows for more complex visual effects, such as borders, shadows, and
decoration
gradients.
Container
import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
home: Scaffold(

appBar: AppBar(
title: Text('Container with Text Example'),
),

body: Container(
width: 200.0,
height: 100.0,
margin: EdgeInsets.all(16.0),
padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
color: Colors.blue,
Container
alignment: Alignment.center,

child: Text(

'Hello, Container!',

style: TextStyle(color: Colors.white),


),
),
),
),
);
}
Container → decoration
import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Container with Text Example'),
),
body: Container(
width: 200.0,
height: 100.0,
margin: EdgeInsets.all(16.0),
padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
decoration: BoxDecoration(
color: Colors.blue,
Container → decoration
border: Border.all(color: Colors.black, width: 2.0),
),
child: Text(
'Hello, Container!',
style: TextStyle(color: Colors.white),
),
),
),
),
);
}
Row
● The Row widget is used to arrange its child widgets in a horizontal line.

● It allows you to create layouts where child widgets are placed side by side along the main axis, which
is typically horizontal.

Property Description

children A list of widgets to be arranged horizontally.

mainAxisAlignment Aligns children along the main axis (horizontal axis).

crossAxisAlignment Aligns children along the cross axis (vertical axis).

mainAxisSize Defines how the Row should size itself..

Determines the order of arrangement for children in languages


textDirection
that are read from right to left or right to left.
Row
import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Row Example'),
),

body: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,

mainAxisSize: MainAxisSize.max,
textDirection: TextDirection.ltr,
Row
children: <Widget>[
Text('Item 1', style: TextStyle(color: Colors.red)),
Text('Item 2', style: TextStyle(color: Colors.green)),
Text('Item 3', style: TextStyle(color: Colors.blue)),
],
),
),
),
);
}
Column
● the Column widget is used to arrange its child widgets in a Vertical line.
● It allows you to create layouts where child widgets are placed side by side along the main axis, which
is typically vertical.

Property Description
children A list of widgets to be arranged vertically.

mainAxisAlignment Aligns children along the main axis (vertical axis).

crossAxisAlignment Aligns children along the cross axis (horizontal axis).

mainAxisSize Defines how the column should size itself..

Determines the order of arrangement for children in languages


textDirection
that are read from right to left or right to left.
Column

import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Column Example'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
textDirection: TextDirection.ltr,
Column

children: <Widget>[
Text('Item 1', style: TextStyle(color: Colors.red)),
Text('Item 2', style: TextStyle(color: Colors.green)),
Text('Item 3', style: TextStyle(color: Colors.blue)),
],
),
),
),
);
}
TextField
● TextField is a widget used to allow users to input text. It provides a text input field
where users can type and edit text.

Property Description

controller An optional controller for manipulating the text field's content and selection.

Configures the appearance of the text field, including the label, border,
decoration
placeholder text, and more.

Determines the type of keyboard that appears when the text field gains focus,
keyboardType
such as numeric, email, URL, etc.

Specifies the action button on the keyboard, such as done, send, next, etc., which
textInputAction
can control the focus or submit the form.
TextField
Property Description

A callback function that gets called whenever the text field's content
onChanged
changes.

A callback function that gets called when the user submits the text field's
onSubmitted
content.

obscureText If true, hides the text being entered (useful for password fields).

maxLines The maximum number of lines to display in the text field (defaults to 1).

maxLength The maximum number of characters allowed in the text field.


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

void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('TextField Example'),
),
body: TextField(
decoration: InputDecoration(
labelText: 'Enter your name',
hintText: 'John Doe',
prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(),
),
keyboardType: TextInputType.text,
textInputAction: TextInputAction.done,
TextField
onChanged: (value) {
print('Text field value changed: $value');
},
onSubmitted: (value) {
print('Text field submitted: $value');
},
),
),
),
);
}
Button
● TextButton:
○ Represents a button containing text.
○ Typically has no background color or border by default.
○ Often used for less prominent actions in the user interface where a simple text label
suffices.
● OutlinedButton:
○ Represents a button with an outlined border and optional text.
○ Has no background color but displays an outlined border around the button's child
widget.
○ Useful for actions that are slightly more prominent than those represented by
TextButton but not as prominent as ElevatedButton.
Button
● ElevatedButton:
○ Represents a button with a filled background and optional text.
○ Has a background color that fills the button's area, making it visually stand out.
○ Typically used for primary actions in the user interface, such as submitting forms or
confirming actions.
● IconButton:
○ Represents a button containing only an icon.
○ Often used for actions that are better represented by graphical symbols or icons rather
than text.
○ Provides a compact and visually appealing way to represent actions.
Button
Button Description
TextButton
A button that contains only text.

OutlinedButton A button that contains text and has an outlined border.


ElevatedButton A button that contains text and has a filled background.
IconButton A button that contains an icon.

Property Description
onPressed Callback function that is called when the button is pressed.
child The widget to display inside the button, typically a Text widget.
The style to apply to the button, including properties like textStyle,
style
foregroundColor, backgroundColor, etc.
textStyle The style to apply to the text displayed inside the button.
foregroundColor The color of the text displayed inside the button.
backgroundColor The background color of the button.
TextButton
import 'package:flutter/material.dart'; }

void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Text Button Example'),
),
body: TextButton(
onPressed: () {
print('TextButton pressed!');
},
child: Text('Press Me'),
),
),
),
);
OutlinedButton
import 'package:flutter/material.dart'; }

void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Outlined Button Example'),
),
body: OutlinedButton(
onPressed: () {
print('OutlinedButton pressed!');
},
child: Text('Press Me'),
),
),
),
);
ElevatedButton
import 'package:flutter/material.dart'; }

void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Elevated Button Example'),
),
body: ElevatedButton(
onPressed: () {
print('ElevatedButton pressed!');
},
child: Text('Press Me'),
),
),
),
);
IconButton
import 'package:flutter/material.dart'; ),
);
void main() { }
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Icon Button Example'),
),
body: IconButton(
onPressed: () {
print('IconButton pressed!');
},
icon: Icon(Icons.star),
color: Colors.yellow,
iconSize: 40,
),
),
Floating Button
• The FloatingActionButton widget in Flutter represents a special type of button that
floats above the content of the app.

• It is commonly used to trigger primary or frequently-used actions within an


application.

• The floating action button typically appears as a circular button with an icon at the
bottom-right corner of the screen, providing users with easy access to important
features.
Floating Button
Property Description
onPressed A callback function called when the button is pressed.

child The widget displayed inside the button, usually an Icon.

backgroundColor The background color of the button.

foregroundColor The color of the button's foreground content, such as the icon.

elevation The elevation of the button, controlling the shadow appearance. Defaults to 6.0.
A short description of the action, displayed as a tooltip when the button is long-
tooltip
pressed.
Floating Button
import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('FloatingActionButton
Example'),
),
body: Center(
child: Text('Press the button below!'),
),
floatingActionButton:
FloatingActionButton(
onPressed: () {
Floating Button
print('FloatingActionButton pressed');
},
child: Icon(Icons.add),
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
elevation: 6.0,
tooltip: 'Add',
),
),
),
);
}
RichText
• The RichText widget in Flutter is used to display text with different styles, such as
varying fonts, font sizes, colors, and decorations, within a single widget.

• It allows for more complex text layouts than the basic Text widget by using a
TextSpan tree to define rich text with multiple styles.

Property Description
text The TextSpan object that defines the rich text with different styles.
textAlign Specifies the alignment of the text within its container.
Defines the direction of the text, such as ltr (left-to-right) or rtl (right-
textDirection
to-left).
RichText
RichText( ),
text: const TextSpan( ],
text: 'My Bonnie', ),
style: TextStyle( )
fontWeight: FontWeight.bold,
decoration: TextDecoration.underline,
color: Colors.red,
fontSize: 20,
),
children: [
TextSpan(
text:' lies over the ocean.My Bonnie lies
over the sea. My Bonnie lies over the ocean.
Oh, bring back my Bonnie to me.',
style: TextStyle(
color: Colors.blue,
fontSize: 20,
)
Layout
● Align and Center
● Expanded
● Padding
● Row
● Column
● SizedBox
● Stack
● Table
Align class and Center Widget
● A widget that aligns its child within itself and optionally sizes itself based on the child's size.
● A Center that align the widget when you wrapped that widget as center.
import 'package:flutter/material.dart';

Center(
child: Container(
height: 120.0,
width: 120.0,
color: Colors.blue[50],
child: Align(
alignment: Alignment.topRight,
child: FlutterLogo(
size: 60,
),
),
),
),
),
);}
Expanded
● The Expanded widget is used within a Row, Column, or Flex to control how its child widget should
flexibly occupy the available space along the main axis. It's commonly used to distribute space
among multiple children within a layout.
Row( ),
children: [ Expanded(
Expanded( child: Container(
child: Container( color: Colors.blue,
color: Colors.red, height: 50,
height: 50, ),
), ),
), ],
Expanded( )
child: Container(
color: Colors.green,
height: 50,
),
Padding
● The Padding widget is used to add padding around its child widget. It's commonly
used to create space between the child widget and its parent or between multiple
child widgets within a layout.

Padding(
padding: EdgeInsets.all(20.0),
child: Container(
color: Colors.blue,
width: 100,
height: 100,
),
)
SizedBox
● The SizedBox widget is used to create a box with a specified size. It's particularly
useful for adding fixed-size space between widgets or for setting the dimensions of
a widget.

SizedBox(
width: 200,
height: 100,
child: Container(
color: Colors.blue,
child: Center(
child: Text(
'SizedBox Example',
style: TextStyle(color: Colors.white),
),
),
),
)
Stack
● In Flutter, the Stack widget is used to stack multiple widgets on top of each other, allowing for
complex layouts and precise control over the positioning of its children. The Stack class is quite
flexible and versatile, enabling developers to create various UI designs.
Property Description
A list of widgets that are stacked on top of each other. The order of the children determines
children
their stacking order, with later children appearing on top of earlier ones.
Defines the alignment of the children within the stack. By default, children are aligned to the
alignment
top-left corner of the stack.
Determines how the stack should size itself in relation to its children. It accepts StackFit.loose
fit (default) or StackFit.expand. When set to StackFit.expand, the stack will expand to fill the
available space.
Defines how overflowing children are handled. It accepts Overflow.clip (default) or
overflow Overflow.visible. When set to Overflow.clip, overflowing children are clipped to the bounds of
the stack.
Sets the text direction for the stack's children. It's typically used for right-to-left (RTL) layout
textDirection
support.
Stack
import 'package:flutter/material.dart'; child: Container(
color: Colors.red,
void main() { height: 100,
runApp( width: 100,
MaterialApp( ),
home: Scaffold( ),
appBar: AppBar( Positioned(
title: Text('Stack Example'), bottom: 50,
), right: 50,
body: Center( child: Container(
child: Stack( color: Colors.green,
alignment: Alignment.center, height: 100,
fit: StackFit.expand, width: 100,
textDirection: TextDirection.ltr, ),
children: [ ),
Container( ],
color: Colors.blue[100], ),
height: 200, ),
width: 200, ),
), ),
Positioned( );
top: 50, }
left: 50,
Table
• The Table widget in Flutter is used to create a grid of cells, similar to an HTML table. It arranges its
children in rows and columns, allowing for the creation of structured layouts with consistent cell
sizes. The Table widget is useful for displaying tabular data or organizing multiple widgets in a grid-like
format.
Property Description
A list of TableRow widgets, each representing a row in the table. Each TableRow contains a list of
children
TableCell widgets representing the cells in that row.

A map that specifies the widths of the columns in the table. It maps column indices to FlexColumnWidth
columnWidths
or FixedColumnWidth objects, which determine the width of each column.

Specifies the default width to be applied to columns that don't have a specific width specified in
defaultColumnWidth
columnWidths.
border An optional TableBorder widget that defines the border appearance of the table.

textDirection Sets the text direction for the table's children. It's typically used for right-to-left (RTL) layout support.
Table
import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Table Example'),
),
body: Center(
child: Table(
border: TableBorder.all(),
columnWidths: {
0: FlexColumnWidth(1),
1: FlexColumnWidth(2),
},
children: [
TableRow(
children: [
TableCell(
child: Center(child: Text('Header 1')),
Table
), );
TableCell( }
child: Center(child: Text('Header 2')),
),

],
),
TableRow(
children: [
TableCell(
child: Center(child: Text('Data 1')),
),
TableCell(
child: Center(child: Text('Data 2')),
),
],
),
],
),
),
),
),
Stateless widget
import 'package:flutter/material.dart'; child: Text('Hello, I am a
StatelessWidget!'),
void main() { ),
runApp(MyStatelessWidget()); ),
} );
}
class MyStatelessWidget extends }
StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('StatelessWidget Example'),
),
body: Center(
Stateful widget
import 'package:flutter/material.dart';
void main() {
runApp(MyStatefulWidget());
}
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
Stateful widget
home: Scaffold( ),
appBar: AppBar( floatingActionButton: FloatingActionButton(
title: Text('Counter App'), onPressed: _incrementCounter,
), tooltip: 'Increment',
body: Center( child: Icon(Icons.add),
child: Column( ),
mainAxisAlignment: ),
MainAxisAlignment.center, );
children: <Widget>[ }
Text( }
'Counter:',
),
Text(
'$_counter',
style: TextStyle(fontSize: 24),
),
],
),
Login Page
● import 'package:flutter/material.dart';

void main() {
runApp(LoginApp());
}

class LoginApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Login Page',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LoginPage(),
);
}
}
Login Page
class LoginPage extends StatelessWidget {
final TextEditingController usernameController = TextEditingController();
final TextEditingController passwordController = TextEditingController();

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Login'),
),
body: Padding(
padding: EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(
controller: usernameController,
decoration: InputDecoration(hintText: 'Username'),
),
Login Page
SizedBox(height: 20.0),
TextField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(hintText: 'Password'),
),
SizedBox(height: 20.0),
ElevatedButton(
onPressed: () {
String username = usernameController.text;
String password = passwordController.text;
if (username == 'admin' && password == 'password') {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => OnTapExample()),
);
}
Login Page
else {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Error'),
content: Text('Invalid username or password.'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('OK'),
),
],
),
);
}
},
child: Text('Login'),
Login Page
),
],
),
),
);
}
}
class OnTapExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Welcome'),
),
body: Center(
child: Text('Welcome! You are now logged in.'),
),
);
}
}
Login Page
Form Widget
● Flutter provides a Form widget to create a form.

● The form widget acts as a container, which allows us to group and validate the multiple form fields.

When you create a form, it is necessary to provide the GlobalKey.

● This key uniquely identifies the form and allows you to do any validation in the form fields.

● The form widget uses child widget TextFormField to provide the users to enter the text field. This

widget renders a material design text field and also allows us to display validation errors when they

occur.
Form Widget
● GlobalKey: A GlobalKey is created and assigned to the Form widget using the _formKey variable.

This key is used to uniquely identify the Form widget and to interact with its state, such as

performing validation or resetting the form.

● Validation Logic: The validator property of each TextFormField is used to define validation logic for

the corresponding form field. When the form is submitted, these validators are triggered to validate

the input. If the validation fails, an error message is returned, which is displayed to the user.
Form Widget
● Form Submission: The form submission logic is implemented within the onPressed callback of the
Button. It checks if the form is valid using the _formKey.currentState?.validate() method. If the form
is valid, the data is printed to the console and the user is navigated to another screen.

● Handling User Input: The user input for the textFormFields captured using TextEditingControllers,
These controllers are assigned to the controller property of the corresponding TextFormFields,
allowing the form fields to be controlled programmatically.

● Scrollable Content: To ensure that all form fields are visible even when the keyboard is displayed,
the SingleChildScrollView widget is used as the parent of the Form. This allows the content to be
scrolled vertically if needed.
Form Widget
● import 'package:flutter/material.dart';

class LoginPageFormValidation extends StatefulWidget {


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

@override
State<LoginPageFormValidation> createState() =>
_LoginPageFormValidationState();
}

class _LoginPageFormValidationState extends State<LoginPageFormValidation> {


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

TextEditingController _username = TextEditingController();


TextEditingController _pass = TextEditingController();
Form Widget
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("My first App"),
backgroundColor: Colors.deepPurple,
foregroundColor: Colors.white,
//automaticallyImplyLeading: true,
),
body: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
children: [
const SizedBox(height: 100),
Image.asset("assets/butterfly.png"),
const SizedBox(height: 15),
const Text("Login to your account"),
const SizedBox(height: 20),
Form Widget
Container(
margin: const EdgeInsets.symmetric(horizontal: 20),
padding: const EdgeInsets.symmetric(horizontal: 10),
decoration: BoxDecoration(
border: Border.all(color: Colors.black, width: 1.5),
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20),
bottomRight: Radius.circular(20),
),
),
child: TextFormField(
controller: _username,
// keyboardType: TextInputType.number,
decoration: const InputDecoration(
hintText: "Username or email",
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your username or email';
}
Form Widget
return null;
},
spellCheckConfiguration: const SpellCheckConfiguration(
misspelledSelectionColor: Colors.red,
),
),
),
const SizedBox(height: 20),
Container(
margin: const EdgeInsets.symmetric(horizontal: 20),
padding: const EdgeInsets.symmetric(horizontal: 10),
decoration: BoxDecoration(
border: Border.all(color: Colors.black, width: 1.5),
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20),
bottomRight: Radius.circular(20),
),
),
Form Widget
child: TextFormField(
controller: _pass,
obscureText: true,
decoration: const InputDecoration(
hintText: "Password",
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your password';
}
return null;
},
),
),
const SizedBox(height: 30),
Container(
height: 50,
width: 350,
child: OutlinedButton(
Form Widget
onPressed: () { "Login", style: TextStyle(
if fontSize: 20,
(_formKey.currentState?.validate() ?? false) { ),
),
print("Username:$_username"); ),
print("Password: $_pass"); ),
],
} ),
}, ),
style: ButtonStyle( ),
foregroundColor: );
MaterialStateProperty.all(Colors.white), }
backgroundColor: }

MaterialStateProperty.all(Colors.deepPurpleAcc
ent),
),
child: const Text(
Form Widget
Gesture Detector
● A is a widget provided by Flutter for recognizing gestures made by the user.

● It allows you to detect various gestures such as taps, drags, and long presses.

Property Description

onTap A callback function invoked when the widget is tapped.

onDoubleTap A callback function invoked when the widget is double-tapped.

onLongPress A callback function invoked when the widget is long-pressed.

onPanStart / onPanUpdate /
Callbacks for the start, update, and end of a pan gesture (drag).
onPanEnd
Gesture Detector
Property Description
onVerticalDragStart /
onVerticalDragUpdate / Callbacks for the start, update, and end of a vertical drag gesture.
onVerticalDragEnd

onHorizontalDragStart /
Callbacks for the start, update, and end of a horizontal drag
onHorizontalDragUpdate /
gesture.
onHorizontalDragEnd

onVerticalDragStart /
onVerticalDragUpdate / Callbacks for the start, update, and end of a vertical drag gesture.
onVerticalDragEnd

onHorizontalDragStart /
Callbacks for the start, update, and end of a horizontal drag
onHorizontalDragUpdate /
gesture.
onHorizontalDragEnd
Gesture Detector

import 'package:flutter/material.dart'; title: Text('GestureDetector Example'),


),
void main() { body: Center(
runApp(MyApp()); child: MyGestureWidget(),
} ),
),
class MyApp extends StatelessWidget { );
@override }
Widget build(BuildContext context) { }
return MaterialApp(
home: Scaffold(
appBar: AppBar(
Gesture Detector

class MyGestureWidget extends StatelessWidget { },


@override onPanStart: (DragStartDetails details) {
Widget build(BuildContext context) { print('Pan start: ${details.localPosition}');
return GestureDetector( },
onTap: () { onPanUpdate: (DragUpdateDetails details) {
print('Widget tapped!'); print('Pan update: ${details.localPosition}');
}, },
onDoubleTap: () { onPanEnd: (DragEndDetails details) {
print('Widget double-tapped!'); print('Pan end: ${details.velocity}');
}, },
onLongPress: () {
print('Widget long-pressed!');
Gesture Detector

onVerticalDragStart: (DragStartDetails details) { child: Text(


print('Vertical drag start: ${details.localPosition}'); 'Tap or drag here!',
}, style: TextStyle(color: Colors.white),
onVerticalDragUpdate: (DragUpdateDetails details) { ),
print('Vertical drag update: ${details.localPosition}'); ),
}, ),
onVerticalDragEnd: (DragEndDetails details) { );
print('Vertical drag end: ${details.velocity}'); }
}, }
child: Container(
width: 200,
height: 200,
color: Colors.blue,
child: Center(
Navigation widget

● The navigation widget in Flutter facilitates moving between different


screens or routes within an application.

● It's typically managed by the Navigator widget and related classes.

● The navigator maintains a stack of routes and provides methods to


navigate between them, such as pushing new routes onto the stack and
popping routes off the stack.
Navigation widget
Property/Method Description

Navigator Widget used to manage a stack of routes within the application.

Method to navigate to a new screen by pushing a new route onto the stack.

Navigator.push() It's typically used when you want to navigate to a new screen while keeping
the previous screen accessible for navigation back.

Replaces the current route on the navigation stack with a new route,
effectively navigating to a different screen.
pushReplacement()
It's commonly used when you want to navigate to a new screen and ensure
that the user cannot return to the previous screen using the back button or
gesture.
Navigation widget
Property/Method Description

Method to go back to the previous screen by popping the current route off
Navigator.pop()
the stack.

A type of route that represents a screen with material design transitions and
MaterialPageRoute
features. Created using MaterialPageRoute class.

This method in Flutter is used to remove a specific route from the navigation
stack.
removeRoute
This method is particularly useful when you need to programmatically
remove a route from the stack in response to some user action or condition.
Navigation widget

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: FirstScreen(),
);
}
}
Navigation widget

class FirstScreen extends StatelessWidget { context,


@override MaterialPageRoute(builder: (context) =>
Widget build(BuildContext context) { SecondScreen()),
return Scaffold( );
appBar: AppBar( },
title: Text('First Screen'), child: Text('Go to Second Screen'),
), ),
body: Center( ),
child: ElevatedButton( );
onPressed: () { }
// Navigate to the second screen }
Navigator.push(
Navigation widget

class SecondScreen extends StatelessWidget { child: Text('Go back to First Screen'),


@override ),
Widget build(BuildContext context) { ),
return Scaffold( );
appBar: AppBar( }}
title: Text('Second Screen'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
// Navigate back to the first screen
Navigator.pop(context);
},

You might also like