0% found this document useful (0 votes)
31 views15 pages

Lab 3 - Drawer Form

Uploaded by

Alwan Sahmi
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)
31 views15 pages

Lab 3 - Drawer Form

Uploaded by

Alwan Sahmi
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/ 15

[Document title]

CREATE DRAWER MENU

1. Create new project name formapp


I. Hit Ctrl + Shift + p to create new project.
II. Select Application
III. Choose the location (folder/directory) where
you want to create your project.
IV. Name your project as formapp.

Create all dart files as follows:

2. In the main.dart file, insert the following codes:

import 'package:flutter/material.dart';
import 'package:formapp/formtask.dart';
import 'package:formapp/formvalid.dart';
import 'package:formapp/regform.dart';
import 'package:formapp/ratecourse.dart';

Page 1 of 15
[Document title]

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

class MyApp extends StatelessWidget {


const MyApp({super.key});

static const appTitle = 'Drawer Demo';

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

class MyHomePage extends StatefulWidget {


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

final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: Home',
style: optionStyle,
),
Text(
'Index 1: My Registration',
style: optionStyle,
),
Text(
'Index 2: My To Do Tasks',
style: optionStyle,
),
Text(
'Index 3: My Rating',
style: optionStyle,
),
Text(
'Index 4: Validation Form',
style: optionStyle,
),
];

void _onItemTapped(int index) {


setState(() {
_selectedIndex = index;

Page 2 of 15
[Document title]

});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Center(
child: _widgetOptions[_selectedIndex],
),
drawer: Drawer(
// Add a ListView to the drawer. This ensures the user can scroll
// through the options in the drawer if there isn't enough vertical
// space to fit everything.
child: ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: [
const DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue,
),
child: Text('Drawer Header'),
),
ListTile(
title: const Text('Home'),
selected: _selectedIndex == 0,
onTap: () {
// Update the state of the app
_onItemTapped(0);
// Then close the drawer
Navigator.pop(context);
},
),
ListTile(
title: const Text('My Registration'),
selected: _selectedIndex == 1,
onTap: () {
// Update the state of the app
_onItemTapped(1);
// Then close the drawer
// Navigator.pop(context);
Navigator.push(context,
MaterialPageRoute(builder: (context) => const RegForm(title: 'Registration Form',)));
},
),
ListTile(
title: const Text('My To Do Tasks'),
selected: _selectedIndex == 2,
onTap: () {
// Update the state of the app
_onItemTapped(2);
// Then close the drawer
// Navigator.pop(context);
Navigator.push(context,
MaterialPageRoute(builder: (context) => const FormTasks()));

Page 3 of 15
[Document title]

},
),
ListTile(
title: const Text('My Rating'),
selected: _selectedIndex == 3,
onTap: () {
// Update the state of the app
_onItemTapped(3);
// Then close the drawer
// Navigator.pop(context);
Navigator.push(context,
MaterialPageRoute(builder: (context) => const RateCourse()));
},
),
ListTile(
title: const Text('Validation Form'),
selected: _selectedIndex == 4,
onTap: () {
// Update the state of the app
_onItemTapped(3);
// Then close the drawer
// Navigator.pop(context);
Navigator.push(context,
MaterialPageRoute(builder: (context) => const FormValid()));
},
),
],
),
),
);
}
}

Page 4 of 15
[Document title]

3. Create formtask.dart, insert the following codes:


import 'package:flutter/material.dart';

class FormTasks extends StatefulWidget {


const FormTasks({super.key});

@override
State<FormTasks> createState() => _FormTasksState();
}

class _FormTasksState extends State<FormTasks> {


List<Widget> list = [];
int fieldCount = 0;

List<Map<String, dynamic>> items = [];

final _formKey = GlobalKey<FormState>();

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Daily Work Tasks"),
actions: [
InkWell(
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Icon(Icons.tab_rounded),
),
onTap: () => itinerariesDialog(context),
),
],
),
body: Form(
key: _formKey,
child: ListView(
shrinkWrap: true,
children: [
fieldCount == 0
? const Padding(
padding: EdgeInsets.all(15.0),
child: Align(
alignment: Alignment.center,
child: Text(
"No Tasks!",
style: TextStyle(
fontSize: 33, fontWeight: FontWeight.bold),
),
),
)
: Column(
children: [
ListView.builder(
itemCount: list.length,
shrinkWrap: true,

Page 5 of 15
[Document title]

itemBuilder: (_, i) => buildField(i),


),
const SizedBox(height: 12),
ElevatedButton(
onPressed: () {
if (!_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Add Tasks")));
}
},
child: const Text("Submit")),
],
),
],
),
),
floatingActionButton: FloatingActionButton(
child: const Text("ADD\nNEW"),
onPressed: () {
setState(() {
fieldCount++;
list.add(buildField(fieldCount));
});
},
),
);
}

itinerariesDialog(BuildContext context) {
showDialog(
barrierDismissible: true,
context: context,
builder: (context) {
return AlertDialog(
title: const Text("Work Tasks"),
content: SizedBox(
width: double.maxFinite,
child: ListView(
shrinkWrap: true,
children: items.map((e) => Text(e["TodoList"].trim())).toList(),
),
),
);
});
}

Widget buildField(int i) {
return ListTile(
leading: CircleAvatar(
child: Text((i + 1).toString()),
),
title: TextFormField(
decoration: InputDecoration(
border: const OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8))),

Page 6 of 15
[Document title]

labelText: "TodoList ${i + 1}",


),
onChanged: (data) => storeValue(i + 1, data),
validator: (val) => val!.isEmpty ? "Required" : null,
),
trailing: InkWell(
child: const Icon(Icons.delete_outlined, color: Colors.red),
onTap: () {
setState(() {
fieldCount--;
list.removeAt(i);

items.removeAt(i);
});
},
),
);
}

dynamic storeValue(int i, String v) {


bool valueFound = false;

for (int j = 0; j < items.length; j++) {


if (items[j].containsKey("field_id")) {
if (items[j]["field_id"] == i) {
valueFound = !valueFound;
break;
}
}
}

/// If value is found


if (valueFound) {
items.removeWhere((e) => e["field_id"] == i);
}
items.add({
"field_id": i,
"TodoList": v,
});
}
}

Page 7 of 15
[Document title]

4. Create regform.dart, insert the following codes

import 'package:flutter/material.dart';
import 'package:formapp/nextpage.dart';

class RegForm extends StatefulWidget {


const RegForm({super.key, required this.title});
final String title;
@override
State<RegForm> createState() => _RegFormState();
}

class _RegFormState extends State<RegForm> {


// To listen to the changes in the textfield.
final TextEditingController _name = TextEditingController();
final TextEditingController _email = TextEditingController();
final TextEditingController _phoneno = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(25),
child: TextField(
// To set the appropriate controller to the text field.
controller: _name,
decoration: const InputDecoration(
border: OutlineInputBorder(), labelText: "Enter your Name"),
),
),
Padding(
padding: const EdgeInsets.all(25),
child: TextField(
controller: _email,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: "Enter your Email"),
),
),
Padding(
padding: const EdgeInsets.all(25),
child: TextField(
controller: _phoneno,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: "Enter your Phone Number"),
),
),

Page 8 of 15
[Document title]

// Button to go to nextpage.
ElevatedButton(
onPressed: () {
// Navigator to the next page.
Navigator.of(context).push(
MaterialPageRoute(

// Builder for the nextpage class's constructor.


builder: (context) => NextPage(
// Data as arguments to send to next page.
name: _name.text,
email: _email.text,
phoneno: _phoneno.text,
)),
);
},
child: const Text("SUBMIT"))
],
),
),
);
}
}

5. Create nextpage.dart

import 'package:flutter/material.dart';

class NextPage extends StatefulWidget {

// Constructor to get the data from the previous page.


const NextPage(
{super.key,
required this.name,
required this.email,
required this.phoneno});
final String name, email, phoneno;

@override
State<NextPage> createState() => _NextPageState();
}

class _NextPageState extends State<NextPage> {


@override
Widget build(BuildContext context) {
// To listen to the changes in the textfield.
TextEditingController name1 = TextEditingController(text: widget.name);
TextEditingController email1 = TextEditingController(text: widget.email);
TextEditingController phoneno1 = TextEditingController(text: widget.phoneno);

return Scaffold(
appBar: AppBar(

Page 9 of 15
[Document title]

title: const Text('Next Page'),


),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(25),
child: TextField(
// To set the appropriate controller to the text field.
controller: name1,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: "Name",
),
),
),
Padding(
padding: const EdgeInsets.all(25),
child: TextField(
controller: email1,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: "Email",
),
),
),
Padding(
padding: const EdgeInsets.all(25),
child: TextField(
controller: phoneno1,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: "Number",
),
),
),
],
),
),
);
}
}

Page 10 of 15
[Document title]

6. Create ratecourse.dart

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

class RateCourse extends StatefulWidget {


const RateCourse({super.key});

@override
State<RateCourse> createState() => _RateCourseState();
}

class _RateCourseState extends State<RateCourse> {


double? _ratingValue;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Rate Course'),
),
body: Padding(
padding: const EdgeInsets.all(25),
child: Center(
child: Column(
children: [
const Text(
'Rate Course?',
style: TextStyle(fontSize: 24),
),
const SizedBox(height: 25),
// implement the rating bar
RatingBar(
initialRating: 0,
direction: Axis.horizontal,
allowHalfRating: true,
itemCount: 5,
ratingWidget: RatingWidget(
full: const Icon(Icons.star, color: Colors.orange),
half: const Icon(

Page 11 of 15
[Document title]

Icons.star_half,
color: Colors.orange,
),
empty: const Icon(
Icons.star_outline,
color: Colors.orange,
)),
onRatingUpdate: (value) {
setState(() {
_ratingValue = value;
});
}),
const SizedBox(height: 25),
// Display the rate in number
Container(
width: 200,
height: 200,
decoration: const BoxDecoration(
color: Colors.red, shape: BoxShape.circle),
alignment: Alignment.center,
child: Text(
_ratingValue != null ? _ratingValue.toString() : 'Rate it!',
style: const TextStyle(color: Colors.white, fontSize: 30),
),
)
],
),
),
));
}
}

7. Create formvalid.dart
import 'package:flutter/material.dart';

class FormValid extends StatefulWidget {


const FormValid({super.key});

@override

Page 12 of 15
[Document title]

State<FormValid> createState() => _FormValidState();


}

class _FormValidState extends State<FormValid> {


final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
AutovalidateMode _autoValidate = AutovalidateMode.disabled;

TextEditingController name = TextEditingController();


TextEditingController mobile = TextEditingController();
TextEditingController email = TextEditingController();

void _validateInputs() {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
} else {
setState(() {
_autoValidate = AutovalidateMode.always;
});
}
}

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Attendance Form'),
),
body: SingleChildScrollView(
child: Container(
margin: const EdgeInsets.all(15.0),
child: Form(
key: _formKey,
autovalidateMode: _autoValidate,
child: formUI(),
),
),
),
),
);
}

Widget formUI() {
return Column(
children: <Widget>[
TextFormField(
decoration: const InputDecoration(labelText: 'Name'),
keyboardType: TextInputType.text,
validator: validateName,
onSaved: (String? val) {
name.text = val!;
},
),
TextFormField(
decoration: const InputDecoration(labelText: 'Mobile'),

Page 13 of 15
[Document title]

keyboardType: TextInputType.phone,
validator: validateMobile,
onSaved: (String? val) {
mobile.text = val!;
},
),
TextFormField(
decoration: const InputDecoration(labelText: 'Email'),
keyboardType: TextInputType.emailAddress,
validator: validateEmail,
onSaved: (String? val) {
email.text = val!;
},
),
const SizedBox(
height: 10.0,
),
OutlinedButton(
onPressed: _validateInputs,
child: const Text('Submit'),
)
],
);
}

String? validateName(String? value) {


if (value!.isEmpty) {
return 'Name cannot be empty';
}
if (value.length < 3) {
return 'Name must be more than 2 charater';
} else {
return null;
}
}

String? validateMobile(String? value) {


if (value!.isEmpty) {
return 'Phone number cannot be empty';
}
if (value.length != 10) {
return 'Mobile Number must be of 10 digit';
} else {
return null;
}
}

String? validateEmail(String? value) {


String pattern =
r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-
9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regex = RegExp(pattern);
if (value!.isEmpty) {
return 'Email cannot be empty';
}
if (!regex.hasMatch(value)) {

Page 14 of 15
[Document title]

return 'Enter Valid Email';


} else {
return null;
}
}
}

Then before you run the codes, you are required to run this command to get all the Flutter
dependencies.

I. flutter pub get

Once completed, key in the command => flutter run.

TASKS:

Modify the formvalid.dart so the information key in the form will display in the next page when the
form does not show any errors.

Page 15 of 15

You might also like