Professional Documents
Culture Documents
Book Flutter
Book Flutter
1
الفهرس
6 .......................................................................................................... Dart لغة البرمجة الدارت 1
6 ................................................................................................................................................ main() 1.1
6 .................................................................................................................. Variables المتغيرات 1.2
7 ........................................................................................ Data Types أنواع المتغيرات 1.2.1
21 .......................................................................................................... Dart Conditional Operators 1.3
21 .................................................................................................................................... If Statement 1.4
24 ........................................................................................................................IF – Else Statement 1.5
21 ............................................................................................ IF…Else and Else…IF... Statement 1.6
21 ..................................................................................................... IF Else and Logical Operators 1.7
26 ........................................................................................................................................ For Loops 1.8
27 ................................................................................................................................... While Loops 1.9
27 ......................................................................................................................... Do-while Loops 1.10
21 ......................................................................................................................... Break Statement 1.11
21 .............................................................................................................. Switch Case Statement 1.12
21 .....................................................................................................................................Functions 1.13
12 ........................................................................................................................ Void Function 1.13.1
12 ........................................................................................... Function Returning Expression 1.13.2
11 ............................................................................................. Functions and Variable Scope 1.13.3
11 .................................................................................... Object-Oriented Programming (OOP) 1.14
11 ........................................................................... Providing Constructors for Your Classes 1.14.1
16 ................................................................................................. Class — Getters and Setters 1.14.2
17 .................................................................................................................... Class Inheritance 1.14.3
17 ........................................................................................................................ Abstract Class 1.14.4
11 .................................................................................................................................. مقدمة للفالتر 2
11 ........................................................................................................................... ماهو الفالتر 2.1
11 ..................................................................................SDK فالتر:تثبيت بيئة البرمجة 2.2
11 .......................................Visual Studio Code Editor المحرر:تثبيت بيئة البرمجة 2.3
11 ...................................................................... Android Studio IDE :تثبيت بيئة البرمجة 2.4
11 ......................................................................................Xcode IDE :تثبيت بيئة البرمجة 2.5
2
11 .................................................................................................. إنشاء مشروع فالتر جديد 1.6
11 ................... Navigate with Named Routes اإلنتقال باستعمال المسارات المحددة 4.1
11 ........................... Send and Return Data Among Screens نقل البيانات بين الصفحات 4.1
3
251 .......................................................................................................................... ListView Widget 1.4
4
211 ............................................................................................... Capture an App User’s Location 7.4
5
Dart لغة البرمجة الدارت1
/https://dartpad.dev : بإمكاننا استعمال هذا الموقع. نحتاج إلى كتابة األكواد وتنفيذها،لنتعلم لغة البرمجة الدارت
main() 1.1
void main() {
print('Welcome to Flutter Course');
}
main() {
print('Welcome to Flutter Course');
var x = 1;
print(x);
}
Output:
Welcome to Flutter Course
1
var y = 2;
void main() {
print('Welcome to Flutter Course');
var x = 1;
print(x);
print(y);
}
Output:
Welcome to Flutter Course
1
2
6
Data Types أنواع المتغيرات1.1.1
String
void main() {
String firstName = 'Saleh';
print(firstName);
Output
Saleh
Otaibi
Boolean
void main() {
bool isGreater;
isGreater = 12 > 5;
print(isGreater);
}
Output
true
Numbers
Int and Double
void main() {
int x = 3;
int y = 2;
int z = x + y;
print(z);
}
Output
5
void main() {
7
double height = 1.5;
double width = 2.6;
double area = height * width;
print(area);
}
Output
3.9000000000000004
Output
1.5
Lists
void main() {
var test_list = [7, 3, 100, 50, 9, 30, 8, 11, 6, -4];
print(test_list[2]);
}
Output
100
void main() {
List<int> test_list = [7, 3, 100, 50, 9, 30, 8, 11, 6, -4];
print(test_list[2]);
}
8
Output
100
void main() {
var test_list = [7, 3, 100, 50, 9, 30, 8, 11, 6, -4];
print(test_list);
}
Output
[7, 3, 100, 50, 9, 30, 8, 11, 6, -4]
void main() {
var test_list = [7, 3, 100, 50, 9, 30, 8, 11, 6, -4];
test_list.add(400);
print(test_list);
}
Output
[7, 3, 100, 50, 9, 30, 8, 11, 6, -4, 400]
void main() {
var test_list = [7,3,100,50,9,30,8,11,6,-4];
print(test_list.length);
}
Output
10
void main() {
var test_list = [7, 3, 100, 50, 9, 30, 8, 11, 6, -4];
test_list.forEach((x) {
print(x);
});
}
Output
7
3
100
50
9
9
30
8
11
6
-4
Maps
maps is an interface designed to manipulate a collection of keys which points to values.
void main() {
var info = {
'UserName': 'amir.hammami@su.edu.sa',
'Password': 'pass123',
};
print(info);
}
Output
{UserName: amir.hammami@su.edu.sa, Password: pass123}
void main() {
var info = new Map();
info['UserName'] = 'amir.hammami@su.edu.sa';
info['Password'] = 'afif@123';
info['Country'] = 'KSA';
info['City'] = 'Afif';
print(info);
}
Output
{UserName: amir.hammami@su.edu.sa, Password: afif@123, Country: KSA, City: Afif}
10
Input of Information to Dart Program
import 'dart:io';
void main() {
print('=============================');
print('Please enter your full name:');
String Full_Name=stdin.readLineSync();
print('Hello:$Full_Name');
print('=============================');
}
import 'dart:io';
void main() {
print('Please enter the first number:');
int num1=int.parse(stdin.readLineSync());
print('Please enter the second number:');
int num2=int.parse(stdin.readLineSync());
var sum=num1+num2;
print('The sum result = $sum');
}
Writing Comments
// The following code to input data to Dart program
/*
*/
11
1.3 Dart Conditional Operators
void main() {
int x = 3;
int y = 5;
print(x == y);
}
Output
false
void main() {
var Age = 40;
var x = Age > 60 ? "Allow" : "Deny";
print(x);
}
12
Output
Deny
void main() {
var x = null;
var y = 10;
var z = x ?? y;
print(z);
}
Output
10
void main() {
int x = 5;
print(x is bool);
}
Output
false
1.4 If Statement
void main() {
int x = 10;
if (x > 5) {
print("Welcome, I am If statement running now ......");
}
print('The End');
}
Output
Welcome, I am If statement running now ......
The End
void main() {
int x = 2;
if (x > 5) {
13
print("Welcome, I am If statement running now ......");
}
print('The End');
}
Output
The End
void main() {
int x = 10;
if (x > 30) {
print("Welcome, I am If statement running now ......");
} else {
print("Welcome, I am Else statement running now ......");
}
}
Output
Welcome, I am Else statement running now ......
14
1.6 IF…Else and Else…IF... Statement
void main() {
var score = 85;
if (score >= 90) {
print('Grade: A');
} else if (score >= 80) {
print('Grade: B');
} else if (score >= 70) {
print('Grade: C');
} else if (score >= 50) {
print('Grade: D');
} else {
print('Grade: F');
}
}
Output
Grade: B
15
void main() {
var Age = 16;
var DOB = 1420;
if (Age >= 18 || DOB >= 1420) {
print('He is Authorized');
} else {
print('He is Not Authorized');
}
}
Output
He is Authorized
void main() {
var Age = 16;
var DOB = 1420;
if (Age >= 18 && DOB >= 1420) {
print('He is Authorized');
} else {
print('He is Not Authorized');
}
}
Output
He is Not Authorized
void main() {
// for loop
for (var i = 0; i < 5; i++) {
print("i= $i");
}
}
Output
i= 0
i= 1
i= 2
i= 3
i= 4
16
1.9 While Loops
void main() {
var x = 1;
while (x <= 5) {
print("x= $x");
x++;
// this is the counter for the loop means x=x+1 i.e. increment x by 1
//each time
}
}
Output
x= 1
x= 2
x= 3
x= 4
x= 5
17
void main() {
var x = 1;
do {
print('x= $x');
x++;
} while (x <= 5);
}
Output
x= 1
x= 2
x= 3
x= 4
x= 5
void main() {
var x = 1;
do {
print('x= $x');
x++;
if (x == 3) break;
} while (x <= 5);
}
Output
x= 1
x= 2
void main() {
int day = 2;
String today = null;
switch (day) {
case 1:
today = 'Sunday';
break;
18
case 2:
today = 'Monday';
break;
case 3:
today = 'Tuesday';
break;
case 4:
today = 'Wednesday';
break;
case 5:
today = 'Thursday';
break;
case 6:
today = 'Friday';
break;
case 7:
today = 'Saturday';
break;
default:
today = 'Invalid Day';
}
print("Today is : $today");
}
Output
Today is : Monday
1.13 Functions
main() {
PrintSomething();
}
PrintSomething() {
print("Welcome Functions !!");
print("Welcome to KSA");
}
Output
Welcome Functions !!
Welcome to KSA
19
String course = CourseName();
print(course);
}
String CourseName() {
return "Flutter Application Development";
}
Output
Flutter Application Development
main() {
var result = SumCalculator(3, 7);
print("Sum Result = $result");
}
int SumCalculator(x, y) {
var z = x + y;
return z;
}
Output
Sum Result = 10
main() {
print("Sum Result = ${SumCalculator(3, 7)}");
}
int SumCalculator(x, y) {
var z = x + y;
return z;
}
Output
Sum Result = 10
main() {
print(age(20));
}
bool age(x) {
if (x >= 60) {
return true;
} else {
return false;
20
}
}
Output
false
main() {
TheFunction();
}
void TheFunction() {
var FirstName = 'Saleh';
if (FirstName.startsWith('S')) {
print("The first name starts with S");
} else {
print("The first name does not start with S");
}
}
Output
The first name starts with S
main() {
print('The Sum Result is: ${sum(3, 5)}');
print('The Multiply Result is : ${multiply(3, 5)}');
}
sum(x, y) {
var z = x + y;
return z;
}
multiply(x, y) {
var w = x * y;
return w;
}
21
main() {
var x = 3;
var y = 5;
int sum() => x + y;
int multiply() => x * y;
print('The Sum Result is : ${sum()}');
print('The Multiply Result is : ${multiply()}');
}
Output
The Sum Result is: 8
The Multiply Result is : 15
CompanyName(name) {
print('My Company Name is : $name');
}
Output
My Company Name is : Microsoft
CompanyName(name) {
var name = 'Google';
print('My Company Name is : $name');
}
Output
My Company Name is : Google
22
var name = 'Microsoft';
main() {
CompanyName('Flutter');
}
CompanyName(name) {
print('My Company Name is : $name');
}
Output
My Company Name is : Flutter
class car {
String type;
String color;
int MaxSpeed;
int NumOfSeats = 4;
}
main() {
var toyota = new car();
toyota.MaxSpeed = 200;
toyota.color = "red";
toyota.type = "Camry";
print("Car Type is: ${toyota.type}");
print("Number of Seats is : ${toyota.NumOfSeats}");
23
}
Output
Car Type is: Camry
Number of Seats is : 4
class car {
String type;
String color;
int MaxSpeed;
int NumOfSeats = 4;
}
main() {
var toyota = new car();
toyota.MaxSpeed = 200;
toyota.color = "red";
toyota.type = "Camry";
toyota.NumOfSeats = 7;
Output
Car Type is: Camry
Number of Seats is : 7
main() {
var toyota = new car();
toyota.MaxSpeed = 200;
24
toyota.color = "red";
toyota.type = "Camry";
toyota.NumOfSeats = 7;
print("Number of Seats is : ${toyota.NumOfSeats}");
toyota.CarSpeed();
}
Output
Number of Seats is : 7
Car Speed is : 200
class car {
String type;
String color;
int MaxSpeed;
int NumOfSeats;
main() {
var toyota = new car("Camery", "red", 200, 5);
print("Car Type is :${toyota.type}");
print("Number of Seats is :${toyota.NumOfSeats}");
}
Output
Car Type is :Camery
Number of Seats is :5
class car {
String type;
String color;
int MaxSpeed;
int NumOfSeats;
25
}
main() {
var toyota = new car("Camery", "red", 200, 5);
print("Car Type is :${toyota.type}");
print("Number of Seats is :${toyota.NumOfSeats}");
}
class car {
String type;
String color;
int MaxSpeed;
int NumOfSeats;
car.initialize() {
type = "Mini Van";
color = "Green";
MaxSpeed = 230;
NumOfSeats = 2;
}
}
main() {
var toyota = new car.initialize();
print("Car Type is :${toyota.type}");
print("Number of Seats is :${toyota.NumOfSeats}");
}
Output
Car Type is :Mini Van
Number of Seats is :2
class car {
String type;
String color;
int MaxSpeed;
int NumOfSeats;
set setType(String value) => type = value; //setter
String get getType => type; //getter
}
26
main() {
var toyota = new car();
toyota.setType = "Bus";
print(toyota.getType);
}
Output
Bus
class Student {
String Name;
String Address;
int TelNumber;
String Email;
}
main() {
var trainer = new Teacher();
trainer.Email = "test@gmail.com";
trainer.TelNumber = 123456789;
print("Email Address : ${trainer.Email}");
print("Telephone Number: ${trainer.TelNumber}");
}
Output
Email Address : test@gmail.com
Telephone Number: 123456789
27
print("Dart fundamentals");
}
}
main() {
var SoftwareStudent = new ITStudent();
SoftwareStudent.contactInfo();
}
Output
Dart fundamentals
main() {
var SoftwareStudent = new ITStudent();
SoftwareStudent.contactInfo();
SoftwareStudent.CourseInfo();
}
Output
Dart fundamentals
Flutter Application Development Course
28
1مقدمة للفالتر
فالتر هو ) (SDKللهاتف المحمول أي حزمة تطوير تطبيقات الهواتف الذكية ،يسمح لك بكتابة تطبيق واحد وتترجم لكل من Androidو
IOS.يعتبر فالتر Flutterاطار عمل حسب التعريف الرسمي الطار العمل من ويكيبيديا
تم انشاء اطار عمل فالتر Flutterمن الصفر واستخدم لكتابته وبنائه لغة Dartولغة C++ويعتبر احدة من افضل اللغات المستخدمة في
برمجة تطبيقات الهواتف الذكية ،و ذلك لما تحتويه من الكثير من المميزات و االضافات الرائعة .
وهي من انتاج شركة جوجل خيث تم عرضها الول مرة في العام .1521
منذ ذلك الوقت كانت شركة Flutterفي طور البيتا و بقيت في هذه المرحلة حتى تم إطالقها الرسمي في ديسمبر ، 1521
ومنذ ذلك الحين يزداد الضجيج حول هذا اللغة قوة.
و تعد هذه اللغة من أفضل 22عملية إعادة شراء برمجيات تعتمد على النجوم في متجر ، GitHub
حيث شهدنا بالفعل آالف التطبيقات المصممة بفالتر التي يتم نشرها على متاجر التطبيقات.
يستخدم اطار عمل فالتر في األساس لتطوير واجهات االستخدام UIويتعاون مع لغة البرمجة Dartللتعامل مع العمليات البرمجية
.BackEnd
عند إنشاء مشروع جديد ،بإمكانك إضافة واجهة أساسية تسمى السقالة .Scaffoldهذا العنصر يعمل كوعاء لعناصر أخرى مثل شريط المهام
كماهو موضح في هذه الصورة:
29
.سنقوم اآلن بإنشاء مشروع فالتر جديد
: ونقوم بإضافة الكود التاليmain.dart بعد ذلك نفتح ملف.1
import 'package:flutter/material.dart';
30
void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(),
body: Text(
''مرحبا,
textDirection: TextDirection.rtl,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 40.0,
),
),
),
),
);
}
بما أن النص باللغة العربية فنحتاج إلى إعتماد الطريقة العربية من اليمين إلى اليسار و ذلك من خالل تثبيت.3
: ونكتب الكود التاليpubspec.yaml نفتح ملف.flutter_localizations مكتبة
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
31
:main.dart بعد ذلك نقوم بالتعديالت التالي في ملف
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
void main() {
runApp(
MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
Locale("ar", "SA"),
],
locale: Locale("ar", "SA"),
home: Scaffold(
appBar: AppBar(),
body: Align(
alignment: Alignment.topRight,
child: Text(
''مرحبا,
textDirection: TextDirection.rtl,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 40.0,
),
),
),
),
),
);
}
32
.4اآلن بإمكانكم إضافة خصائص أخرآ مثل عنوان الواجهة وتغيير لون خلفية شريط التطبيقات :AppBar
(appBar: AppBar
'),أول تطبيق'(title: Text
centerTitle: true,
backgroundColor: Colors.green,
),
(home: Scaffold
backgroundColor: Colors.amberAccent,
(appBar: AppBar
والنتيجة هي:
33
Container Widget عنصر 2.1
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
void main() {
runApp(
MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
Locale("ar", "SA"),
],
locale: Locale("ar", "SA"),
home: Scaffold(
backgroundColor: Colors.amberAccent,
34
appBar: AppBar(
title: Text(')'أول تطبيق,
centerTitle: true,
backgroundColor: Colors.green[500]),
),
),
);
}
35
void main() {
runApp(
MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
Locale("ar", "SA"),
],
locale: Locale("ar", "SA"),
home: Scaffold(
backgroundColor: Colors.amberAccent,
appBar: AppBar(
title: Text(')'أول تطبيق,
centerTitle: true,
backgroundColor: Colors.green[500],
),
body: Container(
color: Colors.grey,
),
),
),
);
}
. على كامل الواجهةContainer وبالتالي تم إضافة. يحتوي على لون الخلفية الرماديbodyاآلن عنصر ال
36
: كما هو موضح في الكود،Container إلى الText لو نضيف عنصر
body: Container(
color: Colors.grey,
child: Text(
''مرحبا في دورة تعليم الفالتر,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
),
),
:نتحصل على
37
:Container بإمكاننا تعديل حجم عنصر
body: Container(
height: 80,
width: 300,
color: Colors.grey,
child: Text(
''مرحبا في دورة تعليم الفالتر,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
),
),
38
height: 80,
width: 300,
color: Colors.grey,
child: Text(
''مرحبا في دورة تعليم الفالتر,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
),
),
body: Container(
padding: EdgeInsets.all(20.0),
margin: EdgeInsets.all(30),
height: 80,
width: 300,
color: Colors.grey,
child: Text(
''مرحبا في دورة تعليم الفالتر,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
),
),
39
.padding والmarginالحظ الفرق بين ال
:BoxDecoration عن طريق استعمالContainerلو نضيف نسق معين لل
body: Container(
decoration: BoxDecoration(
color: Colors.green,
shape: BoxShape.circle,
),
padding: EdgeInsets.all(20.0),
margin: EdgeInsets.all(30),
height: 80,
width: 300,
//color: Colors.grey,
child: Text(
''مرحبا في دورة تعليم الفالتر,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
),
),
40
body: Container(
transform: Matrix4.rotationZ(0.1),
void main() {
runApp(
MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
Locale("ar", "SA"),
],
locale: Locale("ar", "SA"),
home: Scaffold(
41
body: SafeArea(
child: Column(
children: <Widget>[],
),
),
),
),
);
}
import 'package:flutter/material.dart';
42
Widget build(BuildContext context) {
return Container();
}
}
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
Text('Data 1'),
Text('Data 2'),
Container(
child: Text('Data 3'),
color: Colors.grey,
margin: EdgeInsets.only(left: 20.0),
height: 50.0,
width: 70.0,
),
Container(
child: Text('Data 4'),
color: Colors.amber,
margin: EdgeInsets.only(left: 20.0),
height: 50.0,
width: 70.0,
),
],
),
),
),
debugShowCheckedModeBanner: false,
),
);
}
43
. لكن يمكن تغيير ذلك وعرض العناصر من أسفل إلى أعلى. يتم عرض العناصر من أعلى إلى أسفل،حاليا
child: Column(
verticalDirection: VerticalDirection.up,
mainAxisAlignment: MainAxisAlignment.start .1
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Icon(Icons.settings),
Icon(Icons.settings),
Icon(Icons.settings),
Icon(Icons.settings),
44
],
),
),
),
debugShowCheckedModeBanner: false,
),
);
}
mainAxisAlignment: MainAxisAlignment.end .2
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Icon(Icons.settings),
Icon(Icons.settings),
Icon(Icons.settings),
Icon(Icons.settings),
45
],
),
),
),
debugShowCheckedModeBanner: false,
),
);
}
mainAxisAlignment: MainAxisAlignment.spaceBetween .3
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
46
children: <Widget>[
Icon(Icons.settings),
Icon(Icons.settings),
Icon(Icons.settings),
Icon(Icons.settings),
],
),
),
),
debugShowCheckedModeBanner: false,
),
);
}
mainAxisAlignment: MainAxisAlignment.spaceEvenly .4
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
47
Icon(Icons.settings),
Icon(Icons.settings),
Icon(Icons.settings),
Icon(Icons.settings),
],
),
),
),
debugShowCheckedModeBanner: false,
),
);
}
48
:بإمكان إستعمال هذه الخصائص مع عنصر الصف
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: SafeArea(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Icon(Icons.settings),
Icon(Icons.settings),
Icon(Icons.settings),
Icon(Icons.settings),
],
),
),
),
debugShowCheckedModeBanner: false,
),
);
}
49
Button Widgets األزرار 2.2
50
Floating Action Button زر اإلجراء العائم2.2.1
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Floting Action Button'),
),
floatingActionButton: FloatingActionButton(
onPressed: _onClicked,
backgroundColor: Colors.red,
mini: false,
child: Icon(Icons.timer),
),
51
body: Container(
padding: EdgeInsets.all(32.0),
child: Center(
child: Column(
children: <Widget>[Text(_value)],
),
)),
);
}
}
@override
52
_MyHomePageState createState() => _MyHomePageState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Floting Action Button'),
),
floatingActionButton: FloatingActionButton(
onPressed: _onClicked,
backgroundColor: Colors.red,
mini: false,
child: Icon(Icons.timer),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
body: Container(
padding: EdgeInsets.all(32.0),
child: Center(
child: Column(
children: <Widget>[Text(_value)],
),
)),
);
}
}
53
روابط مفيدة
https://api.flutter.dev/flutter/material/FloatingActionButton-class.html
https://pub.dev/packages/fab_circular_menu
RaisedButton 2.2.1
2 مثال
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
54
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter RisedButton Demo'),
);
}
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
void _onPressed() {
setState(() {
_value = 'Welcome in Flutter Course';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
padding: EdgeInsets.all(32.0),
child: Column(
children: <Widget>[
Text(_value),
RaisedButton(
onPressed: _onPressed,
child: new Text('Click me'),
)
],
),
),
55
);
}
}
1 مثال
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
56
String _value = 'Welcome';
void _onPressed(String v) {
setState(() {
_value = v;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
padding: EdgeInsets.all(32.0),
child: Column(
children: <Widget>[
Text(_value),
RaisedButton(
onPressed: () => _onPressed('Welcome in Flutter Course'),
child: new Text('Click me'),
)
],
),
),
);
}
}
1 مثال
RaisedButton(
color: Colors.greenAccent,
onPressed: () => _onPressed('Welcome in Flutter Course'),
child: new Text('Click me'),
),
57
RaisedButton(
disabledColor: Colors.greenAccent[100],
disabledTextColor: Colors.blue[100],
color: Colors.greenAccent,
onPressed: null,
child: new Text('Click me'),
),
RaisedButton(
color: Colors.greenAccent,
onPressed: () => _onPressed('Welcome'),
child: new Text('Click me'),
elevation: 15.0,
),
58
RaisedButton(
splashColor: Colors.yellow[200],
color: Colors.greenAccent,
onPressed: () => _onPressed('Welcome'),
child: new Text('Click me'),
elevation: 10.0,
),
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(18.0),
side: BorderSide(color: Colors.black),
),
splashColor: Colors.yellow[200],
color: Colors.greenAccent,
onPressed: () => _onPressed('Saudi Arabia'),
child: new Text('Click me'),
elevation: 10.0,
),
59
RaisedButton(
padding: EdgeInsets.all(
5.0), //distance of all the sides to the //child
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0.0),
side: BorderSide(color: Colors.black)),
color: Colors.greenAccent,
onPressed: () => _onPressed('Saudi Arabia'),
child: new Text('Click me'),
elevation: 10.0,
),
FlatButton 2.2.2
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
60
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
void _onPressed() {
setState(() {
_value = new DateTime.now().toString();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
padding: const EdgeInsets.all(32.0),
child: Center(
child: Column(
children: <Widget>[
Text(_value),
SizedBox(
height: 16.0,
),
RaisedButton(
onPressed: _onPressed,
child: new Text('RB Click me'),
),
SizedBox(
height: 16.0,
),
FlatButton(
onPressed: _onPressed,
child: Text('FB Click me'),
)
],
),
)),
);
61
}
}
FlatButton(
color: Colors.blueAccent,
textColor: Colors.white,
onPressed: _onPressed,
child: Text('FB Click me'),
),
62
IconButton 2.2.2
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
void _add() {
setState(() {
_value++;
});
}
void _subtract() {
setState(() {
_value--;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
63
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
padding: EdgeInsets.all(32.0),
child: Center(
child: Column(
children: <Widget>[
Text('Value = ${_value}'),
SizedBox(
height: 16.0,
),
IconButton(icon: new Icon(Icons.add), onPressed: _add),
IconButton(icon: new Icon(Icons.remove), onPressed: _subtract)
],
),
)),
);
}
}
64
child: Column(
children: <Widget>[
Ink(
decoration: const ShapeDecoration(
color: Colors.lightBlue,
shape: CircleBorder(),
),
child: IconButton(
icon: Icon(
Icons.local_airport,
),
iconSize: 100,
onPressed: () {},
),
),
],
),
)),
);
}
}
MaterialButton 2.2.2
MaterialButton(
minWidth: 200.0,
height: 42.0,
onPressed: () {},
65
color: Colors.lightBlueAccent,
child: Text(
'Log in',
style: TextStyle(color: Colors.white),
),
),
Material(
//Wrap with Material
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(22.0)),
elevation: 18.0,
color: Color(0xFF801E48),
clipBehavior: Clip.antiAlias, // Add This
child: MaterialButton(
minWidth: 200.0,
height: 35,
color: Color(0xFF801E48),
child: new Text('Sign up',
style:
new TextStyle(fontSize: 16.0, color: Colors.white)),
onPressed: () {},
),
),
66
Toggle Buttons 2.2.2
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
@override
67
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Center(child: Text('ToggleButtons')),
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.only(top: 16.0),
child: Center(
child: ToggleButtons(
children: <Widget>[
Icon(Icons.camera),
Icon(Icons.airline_seat_individual_suite),
Icon(Icons.add_location),
],
isSelected: _selections,
onPressed: (int index) {
setState(() {
_selections[index] = !_selections[index];
});
},
),
),
),
],
),
),
);
}
}
Circular Button
68
class _MyHomePageState extends State<MyHomePage> {
List<bool> _selections = List.generate(3, (_) => false);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Center(child: Text('ToggleButtons')),
),
body: Center(
child: SizedBox.fromSize(
size: Size(80, 80), // button width and height
child: ClipOval(
child: Material(
color: Colors.pink[300], // button color
child: InkWell(
splashColor: Colors.yellow, // splash color
onTap: () {}, // button pressed
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.linked_camera), // icon
Text("Picture"), // text
],
),
),
),
),
),
),
),
);
}
}
69
DropdownButton 2.2.2
.هذا العنصر يشبه شريط المهام أو القائمة المنسدلة التي تُمكن المستخدم من اختيار عنصر من القائمة
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('DropdownButtons'),
),
body: SafeArea(
child: Column(
children: <Widget>[
Center(
child: SafeArea(
child: Text(
70
"Welcome to Flutter course",
style: TextStyle(
fontWeight: FontWeight.normal,
color: Colors.black,
fontSize: 25.0),
),
),
),
DropdownButton<String>(
items: country.map((String dropDownStringItem) {
return DropdownMenuItem<String>(
value: dropDownStringItem,
child: Text(dropDownStringItem),
);
}).toList(),
onChanged: (String newUserValue) {
setState(() {
this.firstcountry = newUserValue;
});
},
value: firstcountry,
// Here, firstcountry variable value is KSA.
// value:firstcountry means, the default country value which will
// appear to the app user.
),
// End of DropdownButton Code //
],
),
),
),
);
}
}
71
OutlineButton 2.2.2
72
],
),
),
),
);
}
}
ButtonBar 1.1.1
73
onPressed: () {},
),
OutlineButton(
shape: StadiumBorder(),
highlightedBorderColor: Colors.blue,
child: Text('Cars'),
onPressed: () {},
),
],
),
],
),
),
),
);
}
}
PopupMenuButton 2.2.2
. يفتح قائمة منسدلة، عندما يضغط المستخدم عليه.يمكن إضافة هذا الزر في أي مكان من التطبيق
74
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text('DropdownButtons'),
actions: <Widget>[
PopupMenuButton(
onSelected: choiceAction,
itemBuilder: (BuildContext context) {
return Item.choices.map((choice) {
return PopupMenuItem(
value: choice,
child: Text(choice),
);
}).toList();
},
)
],
),
body: SafeArea(
child: Column(
children: <Widget>[
Center(
child: SafeArea(
child: Text(
"Welcome to Flutter course",
style: TextStyle(
fontWeight: FontWeight.normal,
color: Colors.black,
fontSize: 20.0),
),
),
),
],
),
),
),
);
}
void choiceAction(choice) {
if (choice == Item.Inbox) {
print('Inbox');
} else if (choice == Item.SentItems) {
print('Sent Items');
} else if (choice == Item.JunckEmail) {
print('Junck E-mail');
} else if (choice == Item.SignOut) {
75
print('Sign Out');
}
}
}
class Item {
static const Inbox = 'Inbox';
static const SentItems = 'Sent Items';
static const JunckEmail = 'Junck E-mail';
static const SignOut = 'Sign Out';
static const List choices = [Inbox, SentItems, JunckEmail, SignOut];
}
76
Navigate to a New Screen and Back اإلنتقال إلى واجهة جديدة والرجوع 2.1
. ونبين لكم كيفية اإلنتقال بين هذه الصفحات. سنقوم من برمجة ثالث صفحات أو ثالث واجهات،في هذا المثال
main.dart :الملف األول
import 'package:flutter/material.dart';
import './screen1.dart';
void main() {
runApp(MyApp());
}
77
}
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
78
من خالل هذه الواجهة االولى ،يمكن النتقال إلى الواجهة الثانية بالضغط على الزر.
(Navigator.push
context,
{ )MaterialPageRoute(builder: (context
;)(return Screen1
}),
;)
79
screen1.dart :الملف الثاني
import 'package:flutter/material.dart';
import './screen2.dart';
80
screen2.dart:الملف الثالث
import 'package:flutter/material.dart';
81
RaisedButton(
color: Colors.green,
child: Text('Return'),
onPressed: () {
Navigator.pop(context);
},
),
],
),
),
);
}
}
82
. سيتم غلق الصفحة وبالتالي الرجوع إلى الصفح الثانية،Return إذا ضغطنا على،من خالل هذه الواجهة الثالثة
Navigator.pop(context);
@override
void initState() {
_timer = Timer(Duration(milliseconds: 500), () {
// SOMETHING: pushReplacement
});
super.initState();
}
@override
void dispose() {
if (_timer != null) {
_timer.cancel();
_timer = null;
}
super.dispose();
}
كذاك
RaisedButton(
color: Colors.blue,
child: Text('Go To Screen 1'),
onPressed: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) =>
return Screen1()),
);
},
),
:main.dart ملف
import 'package:flutter/material.dart';
import './homepage.dart';
83
import './screen0.dart';
import './screen1.dart';
import './screen2.dart';
main() {
runApp(
MyApp(),
);
}
:homepage.dart ملف
import 'package:flutter/material.dart';
84
body: Center(
child: Column(
children: <Widget>[
RaisedButton(
color: Colors.green,
child: Text('Go To Screen 0'),
onPressed: () {
Navigator.pushNamed(context, '0');
}),
RaisedButton(
color: Colors.green,
child: Text('Go To Screen 1'),
onPressed: () {
Navigator.pushNamed(context, '1');
}),
RaisedButton(
color: Colors.green,
child: Text('Go To Screen 2'),
onPressed: () {
Navigator.pushNamed(context, '2');
}),
],
),
),
);
}
}
: وذلك باستعمال الكود التالي. يمكن اإلنتقال إلى كل واجهة حسب المسار،في أي مكان من التطبيق
Navigator.pushNamed(context, '0');
85
:screen2.dart ،screen1.dart ،screen0.dart ثم بقية الصفحات
import 'package:flutter/material.dart';
86
RaisedButton(
color: Colors.green,
child: Text('Return'),
onPressed: () {
Navigator.pop(context);
},
),
],
)),
);
}
}
87
Send and Return Data Among Screens نقل البيانات بين الصفحات 2.2
:screen1.dart ملف
import 'package:flutter/material.dart';
import './screen2.dart';
screen2.dart ملف
import 'package:flutter/material.dart';
88
String firstName = "";
Screen2({Key key, this.firstName}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
title: Text(firstName),
),
body: Center(
child: Column(
children: <Widget>[
RaisedButton(
color: Colors.green,
child: Text('Return'),
onPressed: () {
Navigator.pop(context);
},
),
],
),
),
);
}
}
89
Animate a Widget Across Screens 2.2
pubspec.yaml ملف
assets:
- assets/images/
:main.dart ملف
import 'package:flutter/material.dart';
import './second.dart';
main() {
runApp(
MyApp(),
);
}
90
image: AssetImage('assets/images/book.png'),
width: 120.0,
height: 120.0,
),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (_) {
return Second();
}),
);
},
),
);
}
}
:second.dart ملف
import 'package:flutter/material.dart';
91
عنصر الويب WebView 2.2
92
dependencies:
flutter:
sdk: flutter
webview_flutter: ^1.0.7
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
main() {
runApp(
MyApp(),
);
}
93
body: WebView(
initialUrl: 'http://al-soger.com/',
javascriptMode: JavascriptMode.unrestricted),
),
);
}
}
94
عناصر متقدمة2
import 'package:flutter/material.dart';
main() {
runApp(
MyApp(),
);
}
95
label: 'School',
),
],
),
),
);
}
}
96
backgroundColor: Colors.black54,
selectedItemColor: Colors.white,
selectedFontSize: 19.0,
unselectedFontSize: 14.0,
iconSize: 30.0,
currentIndex: 0,
circular_bottom_navigation مكتبة2.1.1
main.dart ملف
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'screen1.dart';
import 'screen2.dart';
import 'screen3.dart';
main() {
runApp(
MyApp(),
97
);
}
98
),
),
),
);
}
}
99
ListTile Widget 2.2
import 'package:flutter/material.dart';
100
trailing: Icon(Icons.shopping_cart),
onTap: () => print('onTap Action'),
onLongPress: () => print('On Long Press Action'),
dense: false, // true means intensive content.
selected: true, // sets this tile as default.
enabled: true, // means that it can be tapped.
),
ListTile(
leading: Icon(Icons.school),
title: Text('Main Title'),
subtitle: Text('This is my sub title'),
trailing: Icon(Icons.share),
onTap: () => print('onTap Action'),
onLongPress: () => print('On Long Press Action'),
dense: false,
selected: true,
enabled: true,
),
],
)),
);
}
}
101
ListView Widget 2.2
import 'package:flutter/material.dart';
102
onTap: () => print('onTap Action'),
),
ListTile(
leading: Icon(Icons.phone),
title: Text('Main Title'),
subtitle: Text('This is my sub title'),
trailing: Icon(Icons.shopping_cart),
onTap: () => print('onTap Action'),
selected: true,
),
Image(
image: AssetImage('assets/images/book.png'),
height: 120.0,
),
],
),
),
);
}
}
103
Drawer Widget 2.2
:home.dart ماف
import 'package:flutter/material.dart';
:main.dart ملف
import 'package:flutter/material.dart';
import './home.dart';
104
}
}
105
color: Colors.blue,
),
title: Text(
'Inbox',
style: TextStyle(color: Colors.blue, fontSize: 20.0),
),
subtitle: Text('This is my sub title'),
trailing: Icon(Icons.arrow_right),
onTap: () => print('1'),
),
ListTile(
leading: Icon(
Icons.send,
color: Colors.blue,
),
title: Text(
'Sent Items',
style: TextStyle(color: Colors.blue, fontSize: 20.0),
),
subtitle: Text('This is my sub title'),
trailing: Icon(Icons.arrow_right),
onTap: () => print('2'),
),
ListTile(
leading: Icon(
Icons.person,
color: Colors.blue,
),
title: Text(
'Profile',
style: TextStyle(color: Colors.blue, fontSize: 20.0),
),
subtitle: Text('This is my sub title'),
trailing: Icon(Icons.arrow_right),
onTap: () => print('3'),
),
ListTile(
leading: Icon(
Icons.settings,
color: Colors.blue,
),
title: Text(
'Settngs',
style: TextStyle(color: Colors.blue, fontSize: 20.0),
),
subtitle: Text('This is my sub title'),
trailing: Icon(Icons.arrow_right),
onTap: () => print('4'),
106
),
ListTile(
leading: Icon(
Icons.calendar_today,
color: Colors.blue,
),
title: Text(
'Calendar',
style: TextStyle(color: Colors.blue, fontSize: 20.0),
),
subtitle: Text('This is my sub title'),
trailing: Icon(
Icons.arrow_right,
color: Colors.blue,
),
onTap: () => print('5'),
),
]),
),
body: Center(
child: Container(
child: Text(
'Welcome',
style: TextStyle(fontSize: 20.0),
),
),
),
),
);
}
}
107
:نضيف عنوان
drawer: Drawer(
child: ListView(children: <Widget>[
Container(
height: 70.0,
child: DrawerHeader(
margin: EdgeInsets.all(2.0),
padding: EdgeInsets.all(2.0),
child: Text(
'Flutter course',
style: TextStyle(fontSize: 20.0, color: Colors.white),
),
decoration: BoxDecoration(color: Colors.blue),
),
),
108
DataTable Widget 2.2
import 'package:flutter/material.dart';
109
DataRow(
cells: [
DataCell(Text('Honda')),
DataCell(Text('2010')),
DataCell(Text('5000')),
],
),
DataRow(
cells: [
DataCell(Text('Honda')),
DataCell(Text('2011')),
DataCell(Text('6000')),
],
),
DataRow(
cells: [
DataCell(Text('Honda')),
DataCell(Text('2012')),
DataCell(Text('7000')),
],
),
]),
),
)),
);
}
}
110
SelectableText Widget 2.2
import 'package:flutter/material.dart';
111
),
),
);
}
}
body: SelectableText(
'T...',
style: TextStyle(fontSize: 20.0),
showCursor: true,
cursorColor: Colors.green,
cursorWidth: 20,
),
import 'package:flutter/material.dart';
112
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Stack Widget'),
),
body: Stack(children: <Widget>[
Positioned(
bottom: -20,
right: 0,
child: Container(
color: Colors.teal,
width: 100.0,
height: 100.0,
),
),
]),
),
);
}
}
113
import 'package:flutter/material.dart';
114
),
),
Positioned(
top: 150,
right: 100,
child: Container(
color: Colors.yellow,
width: 100.0,
height: 100.0,
),
),
Positioned(
top: 210,
right: 160,
child: Container(
color: Colors.grey,
width: 50.0,
height: 50.0,
),
),
],
),
),
);
}
}
115
Text Field Widget 2.2
هذه األداة تستعمل غالبا إلدخال بيانات النص مثل كتابة االسم وكلمة المرور .فالتر يعتمد على TextFieldو .TextFormField
في هذه الفقرة ،سندرس أداة .TextFieldثم في الفقرة الموالية ،سندرس أداة .TextFormField
لكن قبل ذلك سنتعرض فيما يلي إلى الفرق بين هذين األداتين:
للحصول على إدخال المستخدم TextFieldكافية .لكن ،إذا كنت تقوم بعمل نموذج Formبحيث تحتاج إلى حفظ العمليات saveأو إعادة
تعيينها resetأو التحقق من صحتها ،validateفاستخدم .TextFormField
إذن TextField ،هو حقل النص األساسي بدون استعمال النموذج.
;'import 'package:flutter/material.dart
116
appBar: AppBar(
title: Text('Input Data'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Stack(
children: <Widget>[
ListView(
shrinkWrap: true,
children: <Widget>[
Text(
'Please enter the following information',
style: TextStyle(
fontSize: 22.0,
color: Colors.blue,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10.0,
),
Row(
children: [
Text(
'Full Name:',
style: TextStyle(fontSize: 20.0),
),
SizedBox(
width: 20.0,
),
SizedBox(
width: 220.0,
child: TextField(),
),
],
),
],
),
],
),
),
),
);
}
}
117
import 'package:flutter/material.dart';
118
fontSize: 22.0,
color: Colors.blue,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10.0,
),
Row(
children: [
Text(
'Full Name:',
style: TextStyle(fontSize: 20.0),
),
SizedBox(
width: 20.0,
),
SizedBox(
width: 220.0,
child: TextField(
maxLength: 25,
style: TextStyle(fontSize: 20, color: Colors.blue),
keyboardType: TextInputType.text,
textInputAction: TextInputAction.done,
autocorrect: true,
cursorColor: Colors.red,
decoration: InputDecoration(
hintText: 'Enter your name',
border: InputBorder.none,
focusedBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(7.0)),
borderSide: BorderSide(color: Colors.blue),
),
),
),
)
],
),
SizedBox(
height: 10.0,
),
// ****************Email Address ****************
Row(
children: [
Text(
'Email Address:',
style: TextStyle(fontSize: 20.0),
),
119
SizedBox(
width: 20.0,
),
SizedBox(
width: 220.0,
child: TextField(
maxLength: 50,
style: TextStyle(fontSize: 20, color: Colors.blue),
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.done,
autocorrect: false,
cursorColor: Colors.red,
decoration: InputDecoration(
icon: Icon(Icons.email),
hintText: 'Your Email',
border: InputBorder.none,
focusedBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(7.0)),
borderSide: BorderSide(color: Colors.blue),
),
),
),
),
],
),
SizedBox(
height: 10.0,
),
// **************** Password ****************
Row(
children: [
Text(
'Password:',
style: TextStyle(fontSize: 20.0),
),
SizedBox(
width: 20.0,
),
SizedBox(
width: 220.0,
child: TextField(
maxLength: 50,
obscureText: true,
style: TextStyle(fontSize: 20, color: Colors.blue),
textInputAction: TextInputAction.done,
autocorrect: false,
cursorColor: Colors.red,
120
decoration: InputDecoration(
border: InputBorder.none,
focusedBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(7.0)),
borderSide: BorderSide(color: Colors.blue),
),
),
),
),
],
),
SizedBox(
height: 10.0,
),
// **************** Telephone ****************
Row(
children: [
Text(
'Telephone:',
style: TextStyle(fontSize: 20.0),
),
SizedBox(
width: 20.0,
),
SizedBox(
width: 220.0,
child: TextField(
maxLength: 12,
style: TextStyle(fontSize: 20, color: Colors.blue),
textInputAction: TextInputAction.done,
keyboardType: TextInputType.number,
autocorrect: false,
cursorColor: Colors.red,
decoration: InputDecoration(
border: InputBorder.none,
focusedBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(7.0)),
borderSide: BorderSide(color: Colors.blue),
),
),
),
)
],
),
],
),
121
],
),
),
),
);
}
}
طريقة ثانية2.2.1
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
122
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Name here'),
),
body: new Container(
padding: new EdgeInsets.all(32.0),
child: new Center(
child: new Column(
children: <Widget>[
Text(_value),
TextField(
decoration: new InputDecoration(
labelText: 'Welcome ',
hintText: 'Hint',
icon: Icon(Icons.people)),
autocorrect: true,
autofocus: true,
keyboardType: TextInputType.text,
onChanged: (value) {
setState(() => _value = 'Change: ${value}');
},
onSubmitted: (value) {
123
setState(() => _value = 'Submit: ${value}');
},
)
],
),
),
),
);
}
}
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
124
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Name here'),
),
body: new Container(
padding: new EdgeInsets.all(32.0),
child: new Center(
child: new Column(
children: <Widget>[
Text(_value),
125
TextField(
decoration: new InputDecoration(
labelText: 'Welcome ',
hintText: 'Hint',
icon: Icon(Icons.people)),
autocorrect: true,
autofocus: true,
keyboardType: TextInputType.text,
onChanged: _onChange,
onSubmitted: _onSubmit,
)
],
),
)),
);
}
}
TextEditingController استعمال2.12
و ذلك باتباعTextEditingController نتعرف على كيفية استرداد النص الذي أدخله المستخدم في حقل النص باستخدام،في هذه الفقرة
:الخطوات التالية
TextEditingController. إنشاء.1
TextField. إلىTextEditingController إلحاق.2
. عرض القيمة الحالية لحقل النص.3
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
126
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
@override
void dispose() {
// Clean up the controller when the widget is disposed.
myController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Retrieve Text Input'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
controller: myController,
),
),
floatingActionButton: FloatingActionButton(
// When the user presses the button, show an alert dialog containing
// the text that the user has entered into the text field.
onPressed: () {
return showDialog(
context: context,
127
builder: (context) {
return AlertDialog(
// Retrieve the text the that user has entered by using the
// TextEditingController.
content: Text(myController.text),
);
},
);
},
tooltip: 'Show me the value!',
child: Icon(Icons.text_fields),
),
);
}
}
128
2.11استعمال AutoFocusو FocusNode
بعض واجهات الجوال تعتمد على عدة حقول نص .ومن المناسب عندما تظهر هذه الواجهة أن يكون النص األول يحتوي على بداية الكتابة ثم
إذا انتهى المستخدم وضغط على Enterفي لوحة المفاتيح أن ينتقل مباشرة إلى الحقل الثاني الموالي.
فيما يلي سنستعرض مثالين لهذا االستعمال:
;'import 'package:flutter/material.dart
129
void main() {
runApp(MyApp());
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
@override
void initState() {
_focusNode = FocusNode();
super.initState();
}
@override
void dispose() {
_focusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Focus Node'),
130
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
autofocus: true,
onEditingComplete: () => _focusNode.requestFocus(),
),
SizedBox(
height: 16.0,
),
TextField(
focusNode: _focusNode,
),
],
),
),
);
}
}
131
في هذا المثال ،عندنا متغير _focusNodeنقوم بإنشائه في الدالة )( initStateونقوم بحذفه في الدالة )(.dispose
هذا المتغير نربطه بالحقل الثاني.
في الحقل األول ،نقوم بإعطاء الخاصية autofocusيساوي trueوذلك لكي يأخذ النص بداية الكتابة عند ظهور الواجهة.
والخاصية onEditingCompleteنعطيها الكود )( _focusNode.requestFocusالذي من خالله يتمكن الحقل الثاني من أخذ بداية
الكتابة عندما يضغط المستخدم على Enterمن الحقل األول.
بهذه الطريقة يتم التنقل من الحقل األول إلى الحقل الثاني.
;'import 'package:flutter/material.dart
{ )(void main
;))(runApp(MyApp
}
132
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
133
(TextField
onEditingComplete: () => FocusScope.of(context).unfocus(),
),
],
),
),
;)
}
}
في البداية عند ظهور الواجهة ،الحقل األول يحتوي على بداية الكتابة (ما يسمى ال .)focusوكل مرة يضغط المستخدم على ،Enterينتقل
إلي الحقل الموالي وذلك باستعمال )(FocusScope.of(context).nextFocus
في الحقل األخير ينفذ األمر )( FocusScope.of(context).unfocusو ذلك لتختفي لوحة المفاتيح وينتهي ال .focus
هنا يمكن مثال تنفيذ أوامر أخرى مثل تسجيل البيانات واالنتقال إلى واجهة أخرى.
إ
134
فادة
keyboardType: TextInputType.number,
keyboardType: TextInputType.emailAddress,
keyboardType: TextInputType.phone,
keyboardType: TextInputType.url,
reset أو إعادة تعيينهاsave ولديها ميزات خاصة تحتاج إلى حفظ العملياتForm هذه األداة تشبه األداة السابقة لكنها تُستعمل داخل النموذج
.validate أو التحقق من صحتها
dependencies:
fluttertoast: ^7.1.8
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
void main() {
runApp(MyApp());
}
135
MyHomePage({Key key, this.title}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
@override
Widget build(BuildContext context) {
// Build a Form widget using the _formKey created above.
return Scaffold(
appBar: AppBar(title: Text('Form')),
body: Form(
key: _formKey,
child: Column(
children: <Widget>[
// Add TextFormFields and RaisedButton here.
TextFormField(
decoration: const InputDecoration(
icon: Icon(Icons.person),
hintText: 'What do people call you?',
labelText: 'Name *',
),
onChanged: (text) {
name = text;
},
onSaved: (String value) {
// This optional block of code can be used to run
// code when the user saves the form.
},
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text.';
}
if (value.contains('@')) {
return 'Do not use the @ char.';
}
return null;
},
),
SizedBox(
height: 16.0,
136
),
RaisedButton(
onPressed: () {
final _form = _formKey.currentState;
// Validate returns true if the form is valid, otherwise false.
if (_form.validate()) {
// If the form is valid, display a toast message. In the real wor
ld,
// you'd often call a server or save the information in a databas
e.
_form.save();
Fluttertoast.showToast(
msg: "Processing Data: " + name,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
}
},
child: Text('Submit'),
),
],
),
),
);
}
}
137
نحتاج إلى معرف موحدUnique Identifier يتيح لنا. الستعمال النموذجGlobalKey إنشاء معرف موحد على مستوى التطبيق
:يمكننا ربطه بنموذجنا
final _formKey = GlobalKey<FormState>();
body: Form(
key: _formKey,
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text.';
}
if (value.contains('@')) {
return 'Do not use the @ char.';
}
return null;
138
},
_form.save();
Fluttertoast.showToast(
msg: "Processing Data: " + name,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
}
},
child: Text('Submit'),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
RaisedButton(
onPressed: () {
final _form = _formKey.currentState;
// Validate returns true if the form is valid, otherwise false.
if (_form.validate()) {
// If the form is valid, display a toast message. In the real world,
// you'd often call a server or save the information in a database.
//_form.save();
139
Fluttertoast.showToast(
msg: "Processing Data: " + name,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
}
},
child: Text('Submit'),
),
SizedBox(
width: 16.0,
),
RaisedButton(
onPressed: () {
final _form = _formKey.currentState;
_form.reset();
},
child: Text('Reset'),
),
],
),
.كثير من تطبيقات الجوال تعتمد على تسجيل دخول المستخدم من خالل إدخال اسم المستخدم وكلمة المرور
.فيما يلي نستعرض كود لواجهة تحتوي على نموذج الدخول
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
140
final kHintTextStyle = TextStyle(
color: Colors.white54,
fontFamily: 'OpenSans',
);
void main() {
runApp(MyApp());
}
141
// }
}
void validateAndSave() {
final form = formKey.currentState;
if (form.validate()) {
form.save();
performLogin();
print(_userName + ' - ' + _password);
}
}
void performLogin() {
final snackbar = new SnackBar(
content: new Text("Username : $_userName, password : $_password"),
);
scaffoldKey.currentState.showSnackBar(snackbar);
}
Widget _buildUserNameTF() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Username',
style: kLabelStyle,
),
SizedBox(height: 10.0),
Container(
alignment: Alignment.centerLeft,
decoration: kBoxDecorationStyle,
height: 60.0,
child: TextFormField(
keyboardType: TextInputType.text,
autovalidate: false,
style: TextStyle(
color: Colors.white,
fontFamily: 'OpenSans',
142
),
decoration: InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.account_circle,
color: Colors.white,
),
hintText: 'Enter your Username',
hintStyle: kHintTextStyle,
),
validator: (value) {
return value.isEmpty ? 'Username is Required.' : null;
},
onSaved: (value) {
return _userName = value;
},
),
),
],
);
}
Widget _buildPasswordTF() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Password',
style: kLabelStyle,
),
SizedBox(height: 10.0),
Container(
alignment: Alignment.centerLeft,
decoration: kBoxDecorationStyle,
height: 60.0,
child: TextFormField(
obscureText: true,
autovalidate: false,
style: TextStyle(
color: Colors.white,
fontFamily: 'OpenSans',
),
decoration: InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.lock,
143
color: Colors.white,
),
hintText: 'Enter your Password',
hintStyle: kHintTextStyle,
),
validator: (String value) {
if (value.isEmpty) {
return 'Password is Required.';
}
if (value.length < 6) {
return 'Password too short.';
}
return null;
// return value.isEmpty ? 'Password is Required.' : null;
// || value.length < 6 ? 'Password too short' : null;
},
onSaved: (String value) {
return _password = value;
},
// validator: (val) =>
// val.length < 6 ? 'Password too short' : null,
// onSaved: (val) => _password = val,
),
),
],
);
}
Widget _buildLoginBtn() {
return Container(
padding: EdgeInsets.symmetric(vertical: 25.0),
width: double.infinity,
child: Form(
child: RaisedButton(
elevation: 5.0,
onPressed: () {
validateAndSave();
},
// => print('Login Button Pressed'),
padding: EdgeInsets.all(15.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
color: Colors.white,
child: Text(
'LOGIN',
style: TextStyle(
color: Color(0xFF527DAA),
144
letterSpacing: 1.5,
fontSize: 18.0,
fontWeight: FontWeight.bold,
fontFamily: 'OpenSans',
),
),
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
body: AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.light,
child: GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: Stack(
children: <Widget>[
Container(
height: double.infinity,
width: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color(0xFF73AEF5),
Color(0xFF61A4F1),
Color(0xFF478DE0),
Color(0xFF398AE5),
],
stops: [0.1, 0.4, 0.7, 0.9],
),
),
),
Container(
height: double.infinity,
child: SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
padding: EdgeInsets.symmetric(
horizontal: 40.0,
vertical: 120.0,
),
child: Form(
key: formKey,
145
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Sign In',
style: TextStyle(
color: Colors.white,
fontFamily: 'OpenSans',
fontSize: 30.0,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 30.0),
_buildUserNameTF(),
SizedBox(
height: 30.0,
),
_buildPasswordTF(),
_buildLoginBtn(),
],
),
),
),
)
],
),
),
),
);
}
}
146
2.11.1مثال 2واجهة تسجيل الدخول LoginScreen
;'import 'package:flutter/material.dart
{ )(void main
147
runApp(MyApp());
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Sample App: Login Screen'),
),
body: Padding(
padding: EdgeInsets.all(10),
child: Column(
children: <Widget>[
Container(
alignment: Alignment.center,
padding: EdgeInsets.all(10),
child: Text(
'Flutter Book',
style: TextStyle(
color: Colors.blue,
fontWeight: FontWeight.w500,
148
fontSize: 30),
)),
Container(
alignment: Alignment.center,
padding: EdgeInsets.all(10),
child: Text(
'Sign in',
style: TextStyle(fontSize: 20),
)),
Container(
padding: EdgeInsets.all(10),
child: TextField(
controller: nameController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Username',
),
),
),
Container(
padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
child: TextField(
obscureText: true,
controller: passwordController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
),
),
),
FlatButton(
onPressed: () {
//forgot password screen
},
textColor: Colors.blue,
child: Text('Forgot Password'),
),
Container(
height: 50,
width: double.infinity,
padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
child: RaisedButton(
textColor: Colors.white,
color: Colors.blue,
child: Text('Login'),
onPressed: () {
print(nameController.text);
print(passwordController.text);
149
},
)),
Container(
child: Row(
children: <Widget>[
Text('Does not have account?'),
FlatButton(
textColor: Colors.blue,
child: Text(
'Sign in',
style: TextStyle(fontSize: 20),
),
onPressed: () {
//signup screen
},
)
],
mainAxisAlignment: MainAxisAlignment.center,
),
),
],
),
),
);
}
}
150
CheckboxGroup and RadioButtonGroup Widgets 2.12
dependencies:
grouped_buttons: ^1.0.4
import 'package:flutter/material.dart';
import 'package:grouped_buttons/grouped_buttons.dart';
151
),
Text(
'Select Your Pizza Size :',
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
),
RadioButtonGroup(
labelStyle: TextStyle(fontSize: 20.0),
labels: <String>[
"Small",
"Medium",
"Large",
],
onSelected: (String selected) => print(selected),
),
],
),
),
),
);
}
}
152
Radio Widget زر الراديو2.12
.يستعمل زر الراديو مثال في الخيارات المتعددة بحيث يستطيع المستخدم أن يختار اإلجابة الصحيحة للسؤال
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
Widget makeRadios() {
List<Widget> list = List<Widget>();
153
for (int i = 0; i < 3; i++) {
list.add(Radio(
value: i,
groupValue: _value1,
onChanged: _setValue1,
));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Radio buttons'),
),
body: Container(
padding: EdgeInsets.all(32.0),
child: Center(
child: Column(
children: <Widget>[
Text(
'${_value1}',
style: new TextStyle(
color: new Color.fromARGB(255, 117, 117, 117),
fontSize: 25.0,
fontWeight: FontWeight.bold),
),
makeRadios(),
],
),
)),
);
}
}
154
loop for أضفنا ثالث أزرار راديو باستعمال التكرار،في هذا المثال
1 أو2 أو5 : يستعرض لنا رقم الترتيب،وفي كل مرة نضغط على زر معين
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
_MyHomePage2State createState() => _MyHomePage2State();
}
155
class _MyHomePage2State extends State<MyHomePage2> {
int _value2 = 0;
Widget makeRadioTiles() {
List<Widget> list = List<Widget>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Radio buttons'),
),
body: Container(
padding: EdgeInsets.all(32.0),
child: Center(
child: Column(
children: <Widget>[
Text(
'${_value2}',
style: new TextStyle(
color: new Color.fromARGB(255, 117, 117, 117),
fontSize: 25.0,
fontWeight: FontWeight.bold),
),
makeRadioTiles(),
],
),
156
)),
);
}
}
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
157
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Switch Button'),
),
body: Container(
padding: const EdgeInsets.all(32.0),
child: Center(
child: Column(
children: <Widget>[
Text(
'${_value1}',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.blue),
),
Switch(
value: _value1,
onChanged: (bool value) => setState(() => _value1 = value),
activeTrackColor: Colors.lightGreenAccent,
activeColor: Colors.green,
),
Divider(
color: Colors.teal.shade100,
thickness: 3.0,
),
Text(
'${_value2}',
style: TextStyle(
158
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.blue),
),
SwitchListTile(
value: _value2,
onChanged: _onChanged2,
title: Text(
'Are you student?',
style: TextStyle(
fontWeight: FontWeight.bold, color: Colors.blue),
),
)
],
),
)),
);
}
}
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
159
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Slider'),
),
body: Container(
padding: const EdgeInsets.all(32.0),
child: Center(
child: Column(
children: <Widget>[
Text(
'Value: ${(_value * 100).round()}',
style: TextStyle(
fontSize: 20.0,
color: Colors.black87,
),
),
Slider(
value: _value,
onChanged: (double newvalue) =>
160
setState(() => _value = newvalue),
//Slider(value: _value, onChanged: _setvalue),
),
],
),
),
),
);
}
}
SliderTheme(
data: SliderTheme.of(context).copyWith(
activeTrackColor: Colors.red[700],
inactiveTrackColor: Colors.red[100],
trackShape: RectangularSliderTrackShape(),
trackHeight: 4.0,
thumbColor: Colors.redAccent,
thumbShape: RoundSliderThumbShape(enabledThumbRadius: 12.0),
overlayColor: Colors.red.withAlpha(32),
overlayShape: RoundSliderOverlayShape(overlayRadius: 28.0),
),
child: Slider(
value: _value,
onChanged: (value) {
setState(() {
_value = value;
});
},
),
),
161
:وتعديل آخر
SliderTheme(
data: SliderTheme.of(context).copyWith(
activeTrackColor: Colors.red[700],
inactiveTrackColor: Colors.red[100],
trackShape: RoundedRectSliderTrackShape(),
trackHeight: 4.0,
thumbShape: RoundSliderThumbShape(enabledThumbRadius: 12.0),
thumbColor: Colors.redAccent,
overlayColor: Colors.red.withAlpha(32),
overlayShape: RoundSliderOverlayShape(overlayRadius: 28.0),
tickMarkShape: RoundSliderTickMarkShape(),
activeTickMarkColor: Colors.red[700],
inactiveTickMarkColor: Colors.red[100],
valueIndicatorShape: PaddleSliderValueIndicatorShape(),
valueIndicatorColor: Colors.redAccent,
valueIndicatorTextStyle: TextStyle(
color: Colors.white,
),
),
child: Slider(
value: _value,
min: 0,
max: 100,
divisions: 10,
label: '$_value',
onChanged: (value) {
setState(
() {
_value = value;
},
);
},
),
),
162
DatePicker تحديد التاريخ2.12
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
163
appBar: AppBar(
title: Text('Date Picker'),
),
body: Container(
padding: EdgeInsets.all(32.0),
child: Center(
child: Column(
children: <Widget>[
Text(
_value,
style: TextStyle(
fontSize: 20.0,
color: Colors.black87,
),
),
RaisedButton(
onPressed: _selectDate,
child: new Text('Show DatePicker'),
)
],
),
),
),
);
}
}
164
TimePicker تحديد الوقت2.12
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
165
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
166
appBar: AppBar(
title: Text('Date Picker'),
),
body: Container(
padding: EdgeInsets.all(32.0),
child: Center(
child: Column(
children: <Widget>[
Text(
("Current Time: ${selectedTime.format(context)}"),
style: TextStyle(
fontSize: 20.0,
color: Colors.black87,
),
),
RaisedButton(
onPressed: _selectDate,
child: new Text('Show TimePicker'),
)
],
),
),
),
);
}
}
167
CupertinoDatePicker 2.12
import 'package:flutter/cupertino.dart';
168
Container(
height: 200,
child: CupertinoDatePicker(
mode: CupertinoDatePickerMode.date,
initialDateTime: DateTime(2020, 1, 1),
onDateTimeChanged: (DateTime newDateTime) {
// Do something
},
),
),
:إضافة الوقت
Container(
height: 200,
child: CupertinoDatePicker(
mode: CupertinoDatePickerMode.dateAndTime,
initialDateTime: DateTime(2020, 1, 1, 10, 33),
onDateTimeChanged: (DateTime newDateTime) {
//Do Some thing
},
use24hFormat: false,
minuteInterval: 1,
),
),
169
flutter_datetime_picker مكتبة2.12.1
dependencies:
flutter:
sdk: flutter
flutter_datetime_picker:
git:
url: https://github.com/ditheshthegreat/flutter_datetime_picker # Repo
ref: patch-1 # Branch name
jiffy: ^3.0.1
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:jiffy/jiffy.dart';
void main() {
runApp(MyApp());
}
170
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Date Picker'),
),
body: Container(
padding: EdgeInsets.all(32.0),
child: Center(
child: Column(
children: <Widget>[
Container(
height: 50,
child: Padding(
padding: const EdgeInsets.only(bottom: 5.0),
child: FlatButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
color: Colors.blueAccent,
textColor: Colors.white,
onPressed: () {
DatePicker.showDateTimePicker(context,
showTitleActions: true,
minTime: DateTime(2020, 1, 1),
maxTime: DateTime(2040, 12, 31),
171
theme: DatePickerTheme(
headerColor: Colors.orange,
backgroundColor: Colors.blue,
itemStyle: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 18),
doneStyle: TextStyle(
color: Colors.white,
fontSize: 16)), onChanged: (date) {
//print('2change $date in time zone ' +
// date.timeZoneOffset.inHours.toString());
}, onConfirm: (date) {
//print('2confirm $date');
setState(() {
dateTime = date;
});
}, currentTime: DateTime.now(), locale: LocaleType.ar);
},
child: Text(
Jiffy(dateTime).yMMMMEEEEdjm,
//style: TextStyle(color: Colors.blue),
)),
),
),
],
),
),
),
);
}
}
172
Bottom Sheet Widget 2.12
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: MyApp()));
173
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Alert Dialog Widget'),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Container(
width: 200,
height: 50,
child: RaisedButton(
color: Colors.blue,
child: Text(
'Bottom Sheet',
style: TextStyle(color: Colors.white, fontSize: 20.0),
),
onPressed: () {
_showModalBottomSheet(context);
},
),
174
),
],
),
],
),
),
),
),
);
}
}
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: MyApp()));
}
175
// This widget is the root of your application.
@override
_MyAppState createState() => _MyAppState();
}
void _sheetBottomSheet() {
setState(() {
_showpersistentSheet = null;
});
_scaffoldkey.currentState
.showBottomSheet((content) {
return Container(
color: Colors.blue,
height: 200,
child: Center(
child: Text(
'Welcome to Flutter course',
style: TextStyle(fontSize: 20, color: Colors.white),
),
),
);
})
.closed
.whenComplete(() {
if (mounted) {
setState(() {
_showpersistentSheet = _sheetBottomSheet;
});
}
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
key: _scaffoldkey,
appBar: AppBar(
title: Text('Persistent Bottom Sheet'),
176
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Container(
width: 200,
height: 50,
child: RaisedButton(
color: Colors.blue,
child: Text(
'Bottom Sheet',
style: TextStyle(color: Colors.white, fontSize: 20.0),
),
onPressed: _showpersistentSheet,
),
),
],
),
SizedBox(
height: 20.0,
),
Row(
children: <Widget>[
Container(
width: 200,
height: 50,
child: RaisedButton(
color: Colors.blue,
child: Text(
'Test Button',
style: TextStyle(color: Colors.white, fontSize: 20.0),
),
onPressed: () {},
),
),
],
),
],
),
),
),
),
);
}
177
}
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: MyApp()));
}
178
@override
_MyAppState createState() => _MyAppState();
}
class MyItem {
MyItem({this.isExpanded: false, this.header, this.body});
bool isExpanded;
final String header;
final String body;
}
179
),
));
}).toList(),
)
],
),
),
),
);
}
}
import 'package:flutter/material.dart';
void main() {
180
runApp(MaterialApp(home: MyApp()));
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text('Snack Bar Widget'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
color: Colors.blue,
child: Text(
'Notification Message',
style: TextStyle(color: Colors.white, fontSize: 20.0),
181
),
onPressed: _showSnackBar,
),
),
),
);
}
}
182
Firebase 2
الموقع2
dependencies:
google_maps_flutter: ^2.0.1
183
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Maps Sample App'),
),
body: GoogleMap(
onMapCreated: _myMapCreated,
initialCameraPosition: CameraPosition(target: _location, zoom: 10.0),
),
),
);
}
}
184
Adding a Google Map Marker 2.1
MapMarkers.dart
import 'package:google_maps_flutter/google_maps_flutter.dart';
main.dart ملف
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'MapMarkers.dart';
185
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Maps Sample App'),
),
body: GoogleMap(
markers: {cnTowerkarker},
onMapCreated: _myMapCreated,
initialCameraPosition: CameraPosition(target: _location, zoom: 10.0),
),
),
);
}
}
186
Google Map Types 2.1
Normal: It is the default value that you get when you run your app in the last time.
Satellite: Displays Google Earth satellite images. Hybrid: Displays a mixture of normal and satellite
views. Terrain: Displays a physical map based on terrain information. None: You will get an empty
map. Only you can see the map markers.
body: GoogleMap(
mapType: MapType.hybrid,
markers: {cnTowerkarker},
onMapCreated: _myMapCreated,
187
initialCameraPosition: CameraPosition(target: _location, zoom: 10.0),
),
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'MapMarkers.dart';
188
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Maps Sample App'),
),
body: GoogleMap(
markers: {cnTowerkarker},
onMapCreated: _myMapCreated,
initialCameraPosition: CameraPosition(target: _location, zoom: 13.0),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: gotoNiagaraFalls,
label: Text('To Niagara Falls!'),
icon: Icon(Icons.directions_boat),
),
),
);
}
dependencies:
geolocator: ^7.0.1
189
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'MapMarkers.dart';
import 'package:geolocator/geolocator.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final LatLng _location = const LatLng(43.6425701, -79.3892455);
late GoogleMapController mapController;
void _myMapCreated(GoogleMapController controller) {
mapController = controller;
}
void getCurrentLocation() async {
final Position position = await Geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
final CameraPosition MyLocation = CameraPosition(
target: LatLng(position.latitude, position.longitude),
bearing: 45.0,
tilt: 50.0,
zoom: 11.0,
);
setState(() async {
final GoogleMapController controller = await mapController;
controller.animateCamera(
CameraUpdate.newCameraPosition(MyLocation),
);
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Maps Sample App'),
),
body: GoogleMap(
markers: {cnTowerkarker},
onMapCreated: _myMapCreated,
initialCameraPosition: CameraPosition(target: _location, zoom:13.0),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: getCurrentLocation,
label: Text('To My Location'),
icon: Icon(Icons.directions_boat),
),
),
);
}
}
190
191