repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/models/modelDailyVerse.dart | class modelDailyVerse{
late int dailyVerseID;
late int weekNo;
late int dayNo;
late String content;
late String content_description;
late String status;
late int max_verse;
late String devo_rhema;
late String devo_commands;
late String devo_warnings;
late String devo_promises;
late String devo_application;
late int completion_rate;
late String createdDt;
late String updateDt;
late String marker;
modelDailyVerse({
required this.dailyVerseID,
required this.weekNo,
required this.dayNo,
required this.content,
required this.content_description,
required this.status,
required this.max_verse,
required this.devo_rhema,
required this.devo_commands,
required this.devo_warnings,
required this.devo_promises,
required this.devo_application,
required this.completion_rate,
required this.createdDt,
required this.updateDt,
required this.marker
});
modelDailyVerse.fromMap(Map<String,dynamic> map) {
dailyVerseID = map['dailyVerseID'];
weekNo = map['weekNo'];
dayNo = map['dayNo'];
content = map['content'];
content_description = map['content_description'];
status = map['status'];
max_verse = map['max_verse'];
devo_rhema = map['devo_rhema'];
devo_commands = map['devo_commands'];
devo_warnings = map['devo_warnings'];
devo_promises = map['devo_promises'];
devo_application = map['devo_application'];
completion_rate = map['completion_rate'];
createdDt = map['createdDt'];
updateDt = map['updateDt'];
marker = map['marker'];
}
factory modelDailyVerse.fromJson(Map<String,dynamic> json) => modelDailyVerse(
dailyVerseID: json['dailyVerseID'],
weekNo: json['weekNo'],
dayNo: json['dayNo'],
content: json['content'],
content_description: json['content_description'],
status: json['status'],
max_verse: json['max_verse'],
devo_rhema: json['devo_rhema'],
devo_commands: json['devo_commands'],
devo_warnings: json['devo_warnings'],
devo_promises: json['devo_promises'],
devo_application: json['devo_application'],
completion_rate: json['completion_rate'],
createdDt: json['createdDt'],
updateDt: json['updateDt'],
marker: json['marker'],
);
Map<String,dynamic> toJson() => {
'dailyVerseID':dailyVerseID,
'weekNo': weekNo,
'dayNo': dayNo,
'content': content,
'content_description': content_description,
'status': status,
'max_verse': max_verse,
'devo_rhema': devo_rhema,
'devo_commands': devo_commands,
'devo_warnings': devo_warnings,
'devo_promises': devo_promises,
'devo_application': devo_application,
'completion_rate': completion_rate,
'createdDt': createdDt,
'updateDt': updateDt,
'marker': marker
};
modelDailyVerse.fromSnapshot(snapshot):
dailyVerseID = snapshot.data()['dailyVerseID'],
weekNo = snapshot.data()['weekNo'],
dayNo = snapshot.data()['dayNo'],
content = snapshot.data()['content'],
content_description = snapshot.data()['content_description'],
status = snapshot.data()['status'],
max_verse = snapshot.data()['max_verse'],
devo_rhema = snapshot.data()['devo_rhema'],
devo_commands = snapshot.data()['devo_commands'],
devo_warnings = snapshot.data()['devo_warnings'],
devo_promises = snapshot.data()['devo_promises'],
devo_application = snapshot.data()['devo_application'],
completion_rate = snapshot.data()['completion_rate'],
createdDt = snapshot.data()['createdDt'],
updateDt = snapshot.data()['updateDt'],
marker = snapshot.data()['marker'];
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/models/ModelPanelWeek.dart | import 'ModelPanelWeekDay.dart';
class ModelPanelWeek{
late String header;
late String coverPhotoPath;
late List<ModelPanelWeekDay> details;
late double completionRate;
late String dateFinished;
late int startIndex;
late bool isExpanded;
late int indexPage;
ModelPanelWeek({required this.header,required this.coverPhotoPath, required this.details,required this.completionRate,required this.dateFinished, required this.startIndex, required this.isExpanded,required this.indexPage});
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/models/modelLesson.dart | class modelLesson{
late int lessonID;
late int weekNo;
late int lessonNo;
late String week_title;
late String lesson_title;
late String answer_1;
late String answer_2;
late String answer_3;
late String answer_4;
late String answer_5;
late String createdDt;
late String updatedDt;
late int maxAnswers;
late int completionRate;
modelLesson({
required this.lessonID,
required this.weekNo,
required this.lessonNo,
required this.week_title,
required this.lesson_title,
required this.answer_1,
required this.answer_2,
required this.answer_3,
required this.answer_4,
required this.answer_5,
required this.createdDt,
required this.updatedDt,
required this.maxAnswers,
required this.completionRate,
});
factory modelLesson.fromJson(Map<String,dynamic> json) => modelLesson(
lessonID: json['lessonID'],
weekNo: json['weekNo'],
lessonNo: json['lessonNo'],
week_title: json['week_title'],
lesson_title: json['lesson_title'],
answer_1: json['answer_1'],
answer_2: json['answer_2'],
answer_3: json['answer_3'],
answer_4: json['answer_4'],
answer_5: json['answer_5'],
createdDt: json['createdDt'],
updatedDt: json['updatedDt'],
maxAnswers: json['maxAnswers'],
completionRate: json['completionRate'],
);
Map<String,dynamic> toJson() => {
'lessonID':lessonID,
'weekNo': weekNo,
'lessonNo': lessonNo,
'week_title': week_title,
'lesson_title':lesson_title,
'answer_1': answer_1,
'answer_2': answer_2,
'answer_3': answer_3,
'answer_4': answer_4,
'answer_5': answer_5,
'createdDt':createdDt,
'updatedDt':updatedDt,
'completionRate':completionRate,
};
modelLesson.fromMap(Map<String,dynamic> map) {
lessonID = map['lessonID'];
weekNo = map['weekNo'];
lessonNo = map['lessonNo'];
week_title = map['week_title'];
lesson_title = map['lesson_title'];
answer_1 = map['answer_1'];
answer_2 = map['answer_2'];
answer_3 = map['answer_3'];
answer_4 = map['answer_4'];
answer_5 = map['answer_5'];
createdDt = map['createdDt'];
updatedDt = map['updatedDt'];
maxAnswers = map['maxAnswers'];
completionRate = map['completionRate'];
}
modelLesson.fromSnapshot(snapshot):
lessonID = snapshot.data()['lessonID'],
weekNo = snapshot.data()['weekNo'],
lessonNo = snapshot.data()['lessonNo'],
week_title = snapshot.data()['week_title'],
lesson_title = snapshot.data()['lesson_title'],
answer_1 = snapshot.data()['answer_1'],
answer_2 = snapshot.data()['answer_2'],
answer_3 = snapshot.data()['answer_3'],
answer_4 = snapshot.data()['answer_4'],
answer_5 = snapshot.data()['answer_5'],
createdDt = snapshot.data()['createdDt'],
updatedDt = snapshot.data()['updatedDt'],
maxAnswers = snapshot.data()['maxAnswers'],
completionRate = snapshot.data()['completionRate'];
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/models/VerseHighlighted.dart | class VerseHighlighted{
late String long_name;
late int book_num;
late int chapter;
late int verse;
late String text;
late String color;
VerseHighlighted({required this.long_name,required this.book_num,required this.chapter,required this.verse,required this.text,required this.color});
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/classes/clsThemeColor.dart | class clsThemeColor{
late String title;
late String groupValue;
clsThemeColor({required this.title,required this.groupValue});
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/classes/clsListItemAttributes.dart | class clsListItemAttributes{
late String leftIdentifier;
late String content;
late double fontSize;
clsListItemAttributes({required this.leftIdentifier,required this.content,required this.fontSize});
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/classes/clsNavBarPanel.dart | import 'package:flutter/material.dart';
class clsNavBarPanel{
static const Color drawerItemColor = Colors.blueGrey;
static final Color? drawerItemSelectedColor = Colors.red[700];
static final drawerItemText = [
'Content',
'Settings',
'Exit'
];
static final drawerItemIcon = [
Icons.book,
Icons.settings,
Icons.exit_to_app
];
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/classes/clsExpansionPanel.dart |
class clsExpansionPanel{
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/classes/clsRichTextFormatter.dart | import 'dart:ui';
class clsRichTextFormatter{
late String content;
late FontStyle fontStyle;
late FontWeight fontWeight;
late String bColor;
late String color;
late double fontSize;
late bool isDarkMode;
clsRichTextFormatter({
this.content='',
this.fontStyle=FontStyle.normal,
this.fontWeight=FontWeight.normal,
this.bColor='',
this.color='',
this.fontSize=12,
required this.isDarkMode});
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/classes/clsListItemTextSpanAttributes.dart | import 'package:lifeclass/classes/clsRichTextFormatter.dart';
class clsListItemTextSpanAttributes{
late String leftIdentifier;
late List<clsRichTextFormatter> content;
late double fontSize;
late bool isDarkMode;
clsListItemTextSpanAttributes({required this.leftIdentifier,required this.content,required this.fontSize,required this.isDarkMode});
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/classes/clsSetting.dart | class clsSetting{
late String icon;
late String title;
late String rightBox;
late String color;
clsSetting({required this.icon,required this.title,required this.rightBox, required this.color});
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/classes/clsAttributes.dart | class clsAttributes{
late String title_one;
late String title_two;
late String scriptures;
late String lessonNo;
late double fontSize;
clsAttributes({required this.title_one,required this.title_two,required this.scriptures, required this.lessonNo,required this.fontSize});
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/classes/clsApp.dart | class clsApp{
static final DEFAULT_APP_MODE = 'full';
static final bool displayRealAds = false;
static final String defaultColorThemes = "Teal";
static final String defaultDB = 'lifeclassDataV7.db';
static final String bibleNIVDB = 'holyBibleNiv.db';
static final String bibleASNDDB = 'holyBibleAsnd.db';
static final String bibleRCPVDB = 'holyBibleRcpv.db';
static final String defaultBibleVersion = 'NIV';
static final int defaultFontSize = 16;
static final int defaultAppOpenCounter = 5;
static final String defaultLanguage = 'English';
var lifetime_subscription = '';
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/classes/Themes.dart | import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class myThemes{
static Future<String> loadThemeColor() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
String? data = await prefs.getString('colorThemes') ?? 'Blue';
return data;
}
static Color getColor(String colorType){
Color cColor = Colors.red;
switch(colorType){
case 'Indigo':
cColor = Colors.indigo;
break;
case 'Gray':
cColor = Colors.grey;
break;
case 'Black':
cColor = Colors.black;
break;
case 'Green':
cColor = Colors.green;
break;
case 'Blue':
cColor = Colors.blue;
break;
case 'Orange':
cColor = Colors.orange;
break;
case 'Pink':
cColor = Colors.pink;
break;
case 'Red':
cColor = Colors.red;
break;
case 'Purple':
cColor = Colors.purple;
break;
case 'Teal':
cColor = Colors.teal;
break;
case 'Amber':
cColor = Colors.amber;
break;
case 'Cyan':
cColor = Colors.cyanAccent;
break;
case 'Lime':
cColor = Colors.lime;
break;
}
return cColor;
}
static Color getShadeColor(String colorType){
Color cColor = Colors.red;
switch(colorType){
case 'Indigo':
cColor = Colors.indigo.shade100;
break;
case 'Gray':
cColor = Colors.grey.shade100;
break;
case 'Black':
cColor = Colors.grey;
break;
case 'Green':
cColor = Colors.green.shade100;
break;
case 'Blue':
cColor = Colors.blue.shade100;
break;
case 'Orange':
cColor = Colors.orange.shade100;
break;
case 'Pink':
cColor = Colors.pink.shade100;
break;
case 'Red':
cColor = Colors.red.shade100;
break;
case 'Purple':
cColor = Colors.purple.shade100;
break;
case 'Teal':
cColor = Colors.teal.shade100;
break;
case 'Amber':
cColor = Colors.amber.shade100;
break;
case 'Cyan':
cColor = Colors.cyanAccent.shade100;
break;
case 'Lime':
cColor = Colors.lime.shade100;
break;
}
return cColor;
}
static Color? getLightColor(String colorType){
Color? cColor = Colors.red[300];
switch(colorType){
case 'Indigo':
cColor = Colors.indigo[400];
break;
case 'Gray':
cColor = Colors.grey[400];
break;
case 'Black':
cColor = Colors.grey[800];
break;
case 'Green':
cColor = Colors.green[300];
break;
case 'Blue':
cColor = Colors.blue[300];
break;
case 'Orange':
cColor = Colors.orange[300];
break;
case 'Pink':
cColor = Colors.pink[300];
break;
case 'Red':
cColor = Colors.red[300];
break;
case 'Purple':
cColor = Colors.purple[300];
break;
case 'Teal':
cColor = Colors.teal[300];
break;
case 'Amber':
cColor = Colors.amber[400];
break;
case 'Cyan':
cColor = Colors.cyanAccent[400];
break;
case 'Lime':
cColor = Colors.lime[400];
break;
case 'Yellow':
cColor = Colors.amberAccent[200];
break;
default:
cColor = Colors.transparent;
break;
}
return cColor;
}
static Color? getTabColor(String colorType){
Color? cColor = Colors.red[400];
switch(colorType){
case 'Indigo':
cColor = Colors.indigo[400];
break;
case 'Gray':
cColor = Colors.grey[400];
break;
case 'Black':
cColor = Colors.grey[700];
break;
case 'Green':
cColor = Colors.green[400];
break;
case 'Blue':
cColor = Colors.blue[400];
break;
case 'Orange':
cColor = Colors.orange[400];
break;
case 'Pink':
cColor = Colors.pink[400];
break;
case 'Red':
cColor = Colors.red[400];
break;
case 'Purple':
cColor = Colors.purple[400];
break;
case 'Teal':
cColor = Colors.teal[400];
break;
case 'Amber':
cColor = Colors.amber[400];
break;
case 'Cyan':
cColor = Colors.cyanAccent[400];
break;
case 'Lime':
cColor = Colors.lime[400];
break;
default:
cColor = Colors.transparent;
break;
}
return cColor;
}
static Color? getShade100Color(String colorType){
Color? cColor = Colors.red.shade100;
switch(colorType){
case 'Indigo':
cColor = Colors.indigo.shade100;
break;
case 'Gray':
cColor = Colors.grey.shade100;
break;
case 'Black':
cColor = Colors.grey.shade100;
break;
case 'Green':
cColor = Colors.green.shade100;
break;
case 'Blue':
cColor = Colors.blue.shade100;
break;
case 'Orange':
cColor = Colors.orange.shade100;
break;
case 'Pink':
cColor = Colors.pink.shade100;
break;
case 'Red':
cColor = Colors.red.shade100;
break;
case 'Purple':
cColor = Colors.purple.shade100;
break;
case 'Teal':
cColor = Colors.teal.shade100;
break;
case 'Amber':
cColor = Colors.amber.shade100;
break;
case 'Cyan':
cColor = Colors.cyanAccent.shade100;
break;
case 'Lime':
cColor = Colors.lime.shade100;
break;
case 'Yellow':
cColor = Colors.amberAccent.shade100;
break;
default:
cColor = Colors.transparent;
break;
}
return cColor;
}
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/classes/clsNetwork.dart | import 'dart:io';
class clsNetwork{
static Future<bool> hasNetwork() async {
try {
final result = await InternetAddress.lookup('example.com');
return result.isNotEmpty && result[0].rawAddress.isNotEmpty;
} on SocketException catch (_) {
return false;
}
}
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/classes/clsDailyVerseOutline.dart | class clsDailyVerseOutline{
late int day;
late String status;
late List<String> content;
static List<String> get_daily_verse_outline(int week, int day){
late List<String> data=[];
switch(week){
case 1:
switch(day){
case 1:
data = ['Genesis 1','Genesis 2','Titus 1','Titus 2','Titus 3'];
break;
case 2:
data = ['Genesis 3','Genesis 4','Genesis 5','Mathew 1'];
break;
case 3:
data = ['Genesis 6','Genesis 7','Genesis 8','Mathew 2','Mathew 3'];
break;
case 4:
data = ['Genesis 9','Genesis 10','Genesis 11','Mathew 4'];
break;
case 5:
data = ['Genesis 12','Mathew 5','Mathew 6'];
break;
case 6:
data = ['Genesis 13','Genesis 14','Genesis 15','Mathew 7'];
break;
case 7:
data = ['Genesis 16','Genesis 17','Genesis 18','Mathew 8'];
break;
}
}
return data;
}
} | 0 |
mirrored_repositories/lifeclass/lib | mirrored_repositories/lifeclass/lib/classes/lesson.dart | class Lesson{
late String lessonNo;
late String title;
late String subTitle;
late String color;
late int completionRate;
Lesson({required this.lessonNo,required this.title,required this.subTitle, required this.color,required this.completionRate});
}
| 0 |
mirrored_repositories/lifeclass/lib/classes | mirrored_repositories/lifeclass/lib/classes/sql/clsSqlLesson.dart | class clsSqlLesson{
late int lessonID;
late int weekNo;
late int lessonNo;
late String week_title;
late String lesson_title;
late String answer_1;
late String answer_2;
late String answer_3;
late String answer_4;
late String answer_5;
late String createdDt;
late String updatedDt;
late int maxAnswers;
late int completionRate;
late int score;
late int totalScore;
clsSqlLesson({
required this.lessonID,
required this.weekNo,
required this.lessonNo,
required this.week_title,
required this.lesson_title,
required this.answer_1,
required this.answer_2,
required this.answer_3,
required this.answer_4,
required this.answer_5,
required this.createdDt,
required this.updatedDt,
required this.maxAnswers,
required this.completionRate,
required this.score,
required this.totalScore,
});
factory clsSqlLesson.fromJson(Map<String,dynamic> json) => clsSqlLesson(
lessonID: json['lessonID'],
weekNo: json['weekNo'],
lessonNo: json['lessonNo'],
week_title: json['week_title'],
lesson_title: json['lesson_title'],
answer_1: json['answer_1'],
answer_2: json['answer_2'],
answer_3: json['answer_3'],
answer_4: json['answer_4'],
answer_5: json['answer_5'],
createdDt: json['createdDt'],
updatedDt: json['updatedDt'],
maxAnswers: json['maxAnswers'],
completionRate: json['completionRate'],
score: json['score'],
totalScore: json['totalScore'],
);
Map<String,dynamic> toJson() => {
'lessonID':lessonID,
'weekNo': weekNo,
'lessonNo': lessonNo,
'week_title': week_title,
'lesson_title': lesson_title,
'answer_1': answer_1,
'answer_2': answer_2,
'answer_3': answer_3,
'answer_4': answer_4,
'answer_5': answer_5,
'createdDt':createdDt,
'updatedDt':updatedDt,
'completionRate':completionRate,
'score': score,
'totalScore': totalScore,
};
clsSqlLesson.fromMap(Map<String,dynamic> map) {
lessonID = map['lessonID'];
weekNo = map['weekNo'];
lessonNo = map['lessonNo'];
week_title = map['week_title'];
lesson_title = map['lesson_title'];
answer_1 = map['answer_1'];
answer_2 = map['answer_2'];
answer_3 = map['answer_3'];
answer_4 = map['answer_4'];
answer_5 = map['answer_5'];
createdDt = map['createdDt'];
updatedDt = map['updatedDt'];
maxAnswers = map['maxAnswers'];
completionRate = map['completionRate'];
score = map['score'];
totalScore = map['totalScore'];
}
clsSqlLesson.fromSnapshot(snapshot):
lessonID = snapshot.data()['lessonID'],
weekNo = snapshot.data()['weekNo'],
lessonNo = snapshot.data()['lessonNo'],
week_title = snapshot.data()['week_title'],
lesson_title = snapshot.data()['lesson_title'],
answer_1 = snapshot.data()['answer_1'],
answer_2 = snapshot.data()['answer_2'],
answer_3 = snapshot.data()['answer_3'],
answer_4 = snapshot.data()['answer_4'],
answer_5 = snapshot.data()['answer_5'],
createdDt = snapshot.data()['createdDt'],
updatedDt = snapshot.data()['updatedDt'],
maxAnswers = snapshot.data()['maxAnswers'],
completionRate = snapshot.data()['completionRate'],
score = snapshot.data()['score'],
totalScore = snapshot.data()['totalScore'];
} | 0 |
mirrored_repositories/lifeclass/lib/classes | mirrored_repositories/lifeclass/lib/classes/sql/sqlHelper.dart | import 'dart:io';
import 'package:flutter/services.dart';
import 'package:lifeclass/models/modelBibleVerse.dart';
import 'package:lifeclass/models/modelDailyVerse.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart' as sql;
import 'package:path/path.dart';
import 'package:lifeclass/classes/clsApp.dart';
import 'package:sqflite/sqflite.dart';
import 'package:lifeclass/models/modelBibleBook.dart';
import '../../models/VerseHighlighted.dart';
import '../../models/modelLesson.dart';
import 'package:lifeclass/classes/sql/clsSqlLesson.dart';
class sqlHelper{
static String getCurrentTimeStamp(){
DateTime _now = DateTime.now();
return '${_now.year}-${_now.month}-${_now.day} ${_now.hour}:${_now.minute}:${_now.second}';
}
static Future<void> createLessonTables(sql.Database database) async{
await database.execute("""CREATE TABLE sol_lesson(
lessonID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
lessonNo INTEGER,
bookType TEXT,
answer_1 TEXT,
answer_2 TEXT,
answer_3 TEXT,
answer_4 TEXT,
answer_5 TEXT,
answer_6 TEXT,
answer_7 TEXT,
answer_8 TEXT,
answer_9 TEXT,
answer_10 TEXT,
createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updatedAt TIMESTAMP)
""");
}
static Future<void> createDailyVerseTables(sql.Database database) async{
await database.execute("""CREATE TABLE sol_daily_verse(
dailyVerseId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
lessonID INTEGER,
weekNo INTEGER,
dayNo INTEGER,
check_1 INTEGER NOT NULL DEFAULT 0,
check_2 INTEGER NOT NULL DEFAULT 0,
check_3 INTEGER NOT NULL DEFAULT 0,
check_4 INTEGER NOT NULL DEFAULT 0,
check_5 INTEGER NOT NULL DEFAULT 0,
createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updatedAt TIMESTAMP)
""");
}
static Future<Database> get initDefaultDB async {
final dbPath = await sql.getDatabasesPath();
final path = join(dbPath,clsApp.defaultDB);
final exist = await sql.databaseExists(path);
if(exist)
{
// print('db already existed');
}
else{
// print('creating a copy from assets');
try{
await Directory(dirname(path)).create(recursive: true);
}catch(err){
// print('there was error on creating db: $err');
}
ByteData data = await rootBundle.load(join("assets",clsApp.defaultDB));
List<int> bytes = data.buffer.asInt8List(data.offsetInBytes,data.lengthInBytes);
await File(path).writeAsBytes(bytes,flush: true);
// print('db copied!');
}
return await sql.openDatabase(path);
}
static Future<Database> get initNivDB async {
final dbPath = await sql.getDatabasesPath();
final SharedPreferences prefs = await SharedPreferences.getInstance();
String selectorBibleVersion = prefs.getString('bibleVersion') ?? clsApp.defaultBibleVersion;
late String currentBibleVersion = clsApp.bibleNIVDB;
if(selectorBibleVersion=='ASND') currentBibleVersion = clsApp.bibleASNDDB;
if(selectorBibleVersion=='RCPV') currentBibleVersion = clsApp.bibleRCPVDB;
final path = join(dbPath,currentBibleVersion);
final exist = await sql.databaseExists(path);
if(exist)
{
// print('db already existed' + currentBibleVersion);
}
else{
// print('creating a copy from assets');
try{
await Directory(dirname(path)).create(recursive: true);
}catch(err){
// print('there was error on creating db: $err');
}
ByteData data = await rootBundle.load(join("assets",currentBibleVersion));
List<int> bytes = data.buffer.asInt8List(data.offsetInBytes,data.lengthInBytes);
await File(path).writeAsBytes(bytes,flush: true);
// print('db copied!');
}
return await sql.openDatabase(path);
}
static Future<Database> get initAsndDB async {
final dbPath = await sql.getDatabasesPath();
final path = join(dbPath,clsApp.bibleASNDDB);
final exist = await sql.databaseExists(path);
if(exist)
{
// print('db already existed');
}
else{
// print('creating a copy from assets');
try{
await Directory(dirname(path)).create(recursive: true);
}catch(err){
// print('there was error on creating db: $err');
}
ByteData data = await rootBundle.load(join("assets",clsApp.bibleASNDDB));
List<int> bytes = data.buffer.asInt8List(data.offsetInBytes,data.lengthInBytes);
await File(path).writeAsBytes(bytes,flush: true);
// print('db copied!');
}
return await sql.openDatabase(path);
}
static Future<Database> get initRcpvDB async {
final dbPath = await sql.getDatabasesPath();
final path = join(dbPath,clsApp.bibleRCPVDB);
final exist = await sql.databaseExists(path);
if(exist)
{
// print('db already existed');
}
else{
// print('creating a copy from assets');
try{
await Directory(dirname(path)).create(recursive: true);
}catch(err){
// print('there was error on creating db: $err');
}
ByteData data = await rootBundle.load(join("assets",clsApp.bibleRCPVDB));
List<int> bytes = data.buffer.asInt8List(data.offsetInBytes,data.lengthInBytes);
await File(path).writeAsBytes(bytes,flush: true);
// print('db copied!');
}
return await sql.openDatabase(path);
}
//INSERT TABLE
static Future<int> addLesson(modelLesson lessonData) async{
final db = await initDefaultDB;
final data = {
'lessonNo' : lessonData.lessonNo,
'weekNo' : lessonData.weekNo,
'answer_1' : lessonData.answer_1,
'answer_2' : lessonData.answer_2,
'answer_3' : lessonData.answer_3,
'answer_4' : lessonData.answer_4,
'answer_5' : lessonData.answer_5,
'updatedAt': DateTime.now().toString()
};
final id = await db.insert('sol_lesson', data,
conflictAlgorithm: sql.ConflictAlgorithm.replace);
return id;
}
static Future<int> updateCheckReadStatus(int dailyVerseID, String status, double totalEarnedPoints, String createdDt) async{
final db = await initDefaultDB;
late Map<String, dynamic> row;
// row to update
if(createdDt.trim()!=''){
row = {
'status' : status,
'completion_rate' : totalEarnedPoints.toStringAsFixed(0),
'updateDt': DateTime.now().toString()
};
}else{
row = {
'status' : status,
'completion_rate' : totalEarnedPoints.toStringAsFixed(0),
'updateDt': DateTime.now().toString(),
'createdDt': DateTime.now().toString()
};
}
return await db.update('tbl_daily_verse', row, where: "dailyVerseID = ?", whereArgs: [dailyVerseID]);
}
static Future<int> updateDevotionalStatus(int dailyVerseID,String rhema,String commands,String warnings,String promises,String application, double totalEarnedPoints, String createdDt) async{
final db = await initDefaultDB;
late Map<String, dynamic> row;
// row to update
if(createdDt.trim()!=''){
row = {
'devo_rhema': rhema,
'devo_commands' : commands,
'devo_warnings' : warnings,
'devo_promises' : promises,
'devo_application' : application,
'completion_rate' : totalEarnedPoints.toStringAsFixed(0),
'updateDt': DateTime.now().toString()
};
}else{
row = {
'devo_rhema': rhema,
'devo_commands' : commands,
'devo_warnings' : warnings,
'devo_promises' : promises,
'devo_application' : application,
'completion_rate' : totalEarnedPoints.toStringAsFixed(0),
'createdDt' : DateTime.now().toString(),
'updateDt': DateTime.now().toString()
};
}
return await db.update('tbl_daily_verse', row, where: "dailyVerseID = ?", whereArgs: [dailyVerseID]);
}
static Future<int> updateLesson(int LessonID, String answer_1,String answer_2,String answer_3,String answer_4,String answer_5, int maxAnswers, int completionRate,String createdDt) async{
final db = await initDefaultDB;
late Map<String, dynamic> row;
// row to update
if(createdDt.trim()!=''){
row = {
'answer_1': answer_1,
'answer_2': answer_2,
'answer_3': answer_3,
'answer_4': answer_4,
'answer_5': answer_5,
'completionRate' : completionRate.toString(),
'updatedDt': DateTime.now().toString()
};
}else{
row = {
'answer_1': answer_1,
'answer_2': answer_2,
'answer_3': answer_3,
'answer_4': answer_4,
'answer_5': answer_5,
'completionRate' : completionRate.toString(),
'updatedDt': DateTime.now().toString(),
'createdDt': DateTime.now().toString()
};
}
return await db.update('tbl_my_lesson', row, where: "lessonID = ?", whereArgs: [LessonID]);
}
static Future<int> updateMarker(String dailyVerseID, List<VerseHighlighted> coloredVerse) async{
final db = await initDefaultDB;
late String marker='';
for(int i=0;i<coloredVerse.length;i++){
if(i==0)
marker = coloredVerse[i].long_name + ","
+ coloredVerse[i].book_num.toString() + ","
+ coloredVerse[i].chapter.toString() + ","
+ coloredVerse[i].verse.toString() + ","
+ coloredVerse[i].color;
else marker += ";" +
coloredVerse[i].long_name + ","
+ coloredVerse[i].book_num.toString() + ","
+ coloredVerse[i].chapter.toString() + ","
+ coloredVerse[i].verse.toString() + ","
+ coloredVerse[i].color;
}
late Map<String, dynamic> row; row = {'marker' : marker};
return await db.update('tbl_daily_verse', row, where: "dailyVerseID = ?", whereArgs: [int.parse(dailyVerseID)]);
}
static Future<int> importLessons(int lessonID,Map<String, dynamic> row) async{
final db = await initDefaultDB;
return await db.update('tbl_my_lesson', row, where: "lessonID = ?", whereArgs: [lessonID]);
}
static Future<int> importDailyVerse(int dailyVerseID,Map<String, dynamic> row) async{
final db = await initDefaultDB;
return await db.update('tbl_daily_verse', row, where: "dailyVerseID = ?", whereArgs: [dailyVerseID]);
}
static Future<int> resetLesson() async{
final db = await initDefaultDB;
Map<String, dynamic> row = {
'answer_1' : '',
'answer_2' : '',
'answer_3' : '',
'answer_4' : '',
'answer_5' : '',
'createdAt' : '',
'updatedAt': '',
'completionRate': 0
};
return await db.update('tbl_my_lesson', row);
}
static Future<int> resetDailyVerse() async{
final db = await initDefaultDB;
Map<String, dynamic> row = {
'status' : 'n,n,n,n,n,n,n,n,n',
'devo_rhema' : '',
'devo_commands' : '',
'devo_warnings' : '',
'devo_promises' : '',
'devo_application' : '',
'completion_rate' : 0,
'createdDt' : '',
'updateDt' : '',
'marker':'',
};
return await db.update('tbl_daily_verse', row);
}
//https://www.youtube.com/watch?v=9kbt4SBKhm0
//SOURCE CODE FROM THAT VIDEO TO LEARN MORE...//
static getBibleName(int book_number) async{
final db = await initNivDB;
final result = await db.rawQuery('''SELECT * from books where book_number=?''',[book_number]);
return modelBibleBook.fromMap(result.first);
}
static getBibleVerse(int book_number, int chapter) async{
List<modelBibleVerse> bibleVerse = [];
final db = await initNivDB;
final result = await db.rawQuery('''SELECT * from verses where book_number=? and chapter=?''',[book_number,chapter]);
for(var dailyVerseMap in result){
modelBibleVerse rows =
modelBibleVerse(
book_number: int.parse(dailyVerseMap['book_number'].toString()),
chapter: int.parse(dailyVerseMap['chapter'].toString()),
verse: int.parse(dailyVerseMap['verse'].toString()),
text: dailyVerseMap['text'].toString());
bibleVerse.add(rows);
}
return bibleVerse;
}
static getLessonByID(int id) async{
final db = await initDefaultDB;
final result = await db.rawQuery('''SELECT * from tbl_my_lesson where lessonID=?''',[id]);
return clsSqlLesson.fromJson(result.first);
}
Future<List<modelDailyVerse>> getAllDailyVerseOnlySelectedID(String whereStringArguments, List<int> whereValue) async{
List<modelDailyVerse> dailyverse = [];
final db = await initDefaultDB;
List<Map<String,dynamic>> mapValues = await db.rawQuery('''SELECT * from tbl_daily_verse where $whereStringArguments''',whereValue);
for(var dailyverseMap in mapValues){
modelDailyVerse rows = modelDailyVerse.fromMap(dailyverseMap);
dailyverse.add(rows);
}
return dailyverse;
}
Future<List<modelLesson>> getAllLessonsOnlySelectedID(String whereStringArguments, List<int> whereValue) async{
List<modelLesson> lesson = [];
final db = await initDefaultDB;
List<Map<String,dynamic>> mapValues = await db.rawQuery('''SELECT * from tbl_my_lesson where $whereStringArguments''',whereValue);
for(var lessonMap in mapValues){
modelLesson rows = modelLesson.fromMap(lessonMap);
lesson.add(rows);
}
return lesson;
}
static getDailyVerseByID(int id) async{
final db = await initDefaultDB;
final result = await db.rawQuery('''SELECT * from tbl_daily_verse where dailyVerseID=?''',[id]);
return modelDailyVerse.fromMap(result.first);
}
Future<List<modelDailyVerse>> getAllDailyVerse() async{
List<modelDailyVerse> dailyverse = [];
final db = await initDefaultDB;
List<Map<String,dynamic>> mapValues = await db.query('tbl_daily_verse',orderBy: 'dailyVerseID');
for(var dailyVerseMap in mapValues){
modelDailyVerse rows = modelDailyVerse.fromMap(dailyVerseMap);
dailyverse.add(rows);
}
return dailyverse;
}
Future<List<modelLesson>> getAllLessons() async {
List<modelLesson> lessons = [];
final db = await initDefaultDB;
final mapValues = await db.rawQuery('''SELECT * from tbl_my_lesson order by lessonID''');
for(var lessonMap in mapValues){
modelLesson rows = modelLesson.fromMap(lessonMap);
print('lessons->' + rows.toString());
lessons.add(rows);
}
return lessons;
}
//DELETE RECORD
static Future<void> deleteLesson(int id) async{
final db = await initDefaultDB;
try{
await db.delete('sol_lesson', where: "lessonID=?", whereArgs: [id]);
}catch(err){
// print("Something went wrong when deleting an item: $err");
}
}
} | 0 |
mirrored_repositories/password_field_example | mirrored_repositories/password_field_example/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:password_field_example/widget/button_widget.dart';
import 'package:password_field_example/widget/email_field_widget.dart';
import 'package:password_field_example/widget/password_field_widget.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
static final String title = 'Password Field';
@override
Widget build(BuildContext context) => MaterialApp(
debugShowCheckedModeBanner: false,
title: title,
theme: ThemeData(primarySwatch: Colors.blue),
home: MainPage(),
);
}
class MainPage extends StatefulWidget {
@override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
final formKey = GlobalKey<FormState>();
final emailController = TextEditingController();
final passwordController = TextEditingController();
@override
void dispose() {
emailController.dispose();
passwordController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: Text(MyApp.title),
centerTitle: true,
),
body: Center(
child: Form(
key: formKey,
child: SingleChildScrollView(
padding: EdgeInsets.all(16),
child: AutofillGroup(
child: Column(
children: [
EmailFieldWidget(controller: emailController),
const SizedBox(height: 16),
PasswordFieldWidget(controller: passwordController),
buildForgotPassword(),
const SizedBox(height: 16),
buildButton(),
buildNoAccount(),
],
),
),
),
),
),
);
Widget buildButton() => ButtonWidget(
text: 'LOGIN',
onClicked: login,
);
void login() {
final form = formKey.currentState!;
if (form.validate()) {
TextInput.finishAutofillContext();
final email = emailController.text;
ScaffoldMessenger.of(context)
..removeCurrentSnackBar()
..showSnackBar(SnackBar(
content: Text('Your email is $email'),
));
}
}
Widget buildNoAccount() => Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Don\'t have an account?'),
TextButton(
child: Text('SIGN UP'),
onPressed: () {},
),
],
);
Widget buildForgotPassword() => Container(
alignment: Alignment.centerRight,
child: TextButton(
child: Text('Forgotten Password?'),
onPressed: () {},
),
);
}
| 0 |
mirrored_repositories/password_field_example/lib | mirrored_repositories/password_field_example/lib/widget/button_widget.dart | import 'package:flutter/material.dart';
class ButtonWidget extends StatelessWidget {
final String text;
final VoidCallback onClicked;
const ButtonWidget({
Key? key,
required this.text,
required this.onClicked,
}) : super(key: key);
@override
Widget build(BuildContext context) => ElevatedButton(
style: ElevatedButton.styleFrom(
minimumSize: Size.fromHeight(50),
shape: StadiumBorder(),
),
child: FittedBox(
child: Text(
text,
style: TextStyle(fontSize: 20, color: Colors.white),
),
),
onPressed: onClicked,
);
}
| 0 |
mirrored_repositories/password_field_example/lib | mirrored_repositories/password_field_example/lib/widget/password_field_widget.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class PasswordFieldWidget extends StatefulWidget {
final TextEditingController controller;
const PasswordFieldWidget({
Key? key,
required this.controller,
}) : super(key: key);
@override
_PasswordFieldWidgetState createState() => _PasswordFieldWidgetState();
}
class _PasswordFieldWidgetState extends State<PasswordFieldWidget> {
bool isHidden = false;
@override
Widget build(BuildContext context) => TextFormField(
controller: widget.controller,
obscureText: isHidden,
decoration: InputDecoration(
hintText: 'Password',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
prefixIcon: Icon(Icons.lock),
suffixIcon: IconButton(
icon:
isHidden ? Icon(Icons.visibility_off) : Icon(Icons.visibility),
onPressed: togglePasswordVisibility,
),
),
keyboardType: TextInputType.visiblePassword,
autofillHints: [AutofillHints.password],
onEditingComplete: () => TextInput.finishAutofillContext(),
validator: (password) => password != null && password.length < 5
? 'Enter min. 5 characters'
: null,
);
void togglePasswordVisibility() => setState(() => isHidden = !isHidden);
}
| 0 |
mirrored_repositories/password_field_example/lib | mirrored_repositories/password_field_example/lib/widget/email_field_widget.dart | import 'package:email_validator/email_validator.dart';
import 'package:flutter/material.dart';
class EmailFieldWidget extends StatefulWidget {
final TextEditingController controller;
const EmailFieldWidget({
Key? key,
required this.controller,
}) : super(key: key);
@override
_EmailFieldWidgetState createState() => _EmailFieldWidgetState();
}
class _EmailFieldWidgetState extends State<EmailFieldWidget> {
@override
void initState() {
super.initState();
widget.controller.addListener(onListen);
}
@override
void dispose() {
widget.controller.removeListener(onListen);
super.dispose();
}
void onListen() => setState(() {});
@override
Widget build(BuildContext context) => TextFormField(
controller: widget.controller,
decoration: InputDecoration(
hintText: 'Email',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
prefixIcon: Icon(Icons.mail),
suffixIcon: widget.controller.text.isEmpty
? Container(width: 0)
: IconButton(
icon: Icon(Icons.close),
onPressed: () => widget.controller.clear(),
),
),
keyboardType: TextInputType.emailAddress,
autofillHints: [AutofillHints.email],
autofocus: true,
validator: (email) => email != null && !EmailValidator.validate(email)
? 'Enter a valid email'
: null,
);
}
| 0 |
mirrored_repositories/Covicare | mirrored_repositories/Covicare/lib/main.dart | import 'package:covicare_app/pages/editinfo.dart';
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:covicare_app/pages/apmt.dart';
import 'package:covicare_app/pages/care.dart';
import 'package:covicare_app/pages/loader.dart';
import 'package:covicare_app/pages/login.dart';
import 'package:covicare_app/pages/pinfo.dart';
import 'package:covicare_app/pages/register.dart';
import 'package:covicare_app/pages/report.dart';
import 'package:covicare_app/pages/stats.dart';
import 'package:covicare_app/pages/symp.dart';
// global variables
String currentPh="default phone";
String currentName="default name";
String currentPass="default pass";
String currentDob="default dob";
List<List> reports=new List();
//global function
Future<void> getReports() async
{
final DBRef = FirebaseDatabase.instance.reference();
await DBRef.child("rpt").once().then((DataSnapshot dataSnapShot){
var newdata = dataSnapShot.value;
newdata.forEach((key,values){
if((values['phone'])==currentPh){
List<String> temp=[key,values['url']];
print(key+" "+values['url']);
reports.add(temp);
}
});
});
}
void clearAll(){
currentPh="default phone";
currentName="default name";
currentPass="default pass";
currentDob="default dob";
reports=new List();
}
void main() {
// version compliance
WidgetsFlutterBinding.ensureInitialized();
runApp(MaterialApp(
// initialRoute: '/login',
routes: {
'/': (context) => LoadingP(),
'/home': (context) => HomeP(),
'/care': (context) => CareP(),
'/login': (context) => LoginP(),
'/stats': (context) => StatsP(),
'/register': (context) => RegisterP(),
'/info': (context) => PinfoP(),
'/report': (context) => ReportP(),
'/symp': (context) => SympP(),
'/apmt': (context) => ApmtP(),
'/editinfo': (context) => EditinfoP(),
},
));
}
class HomeP extends StatelessWidget {
// database reference string
final DBRef = FirebaseDatabase.instance.reference();
void linkop (work) async{
if (await canLaunch(work)){
await launch(work);
}
else{
print('Whoops!');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false,
appBar: AppBar(
elevation: 24,
title: Text(
"Covicare",
style: TextStyle(
fontSize: 28,
fontFamily: 'Wind',
color: Colors.white,
),
),
centerTitle: true,
backgroundColor: Color(0xff4A7C59),
),
body: Container(
padding: EdgeInsets.fromLTRB(20, 70, 20, 30),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xffFAF3DD),
Color(0xffC8D5B9),
],
begin: Alignment.topCenter,
end: Alignment.bottomRight,
),
),
alignment: Alignment.center,
child: Column(
children: [
RaisedButton(
elevation: 24,
padding: EdgeInsets.fromLTRB(32, 12, 32, 12),
child: SizedBox(
height: 28,
width: 260,
child: Text(
"Statistics",
style: TextStyle(
fontSize: 25,
fontFamily: 'Nexa',
color: Colors.white,
// fontWeight: FontWeight.bold
),
textAlign: TextAlign.center,
),
),
onPressed: (){
Navigator.pushNamed(context, '/stats');
},
color: Color(0xff4A7C59),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0),
),
),
SizedBox(
height: 40,
),
RaisedButton(
elevation: 24,
padding: EdgeInsets.fromLTRB(32, 12, 32, 12),
child: SizedBox(
// height: 54,
width: 260,
child: Text(
"Check symptoms",
style: TextStyle(
fontSize: 25,
fontFamily: 'Nexa',
color: Colors.white,
// fontWeight: FontWeight.bold
),
textAlign: TextAlign.center,
),
),
onPressed: (){Navigator.pushNamed(context, '/symp');},
color: Color(0xff4A7C59),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0),
),
),
SizedBox(
height: 40,
),
RaisedButton(
elevation: 24,
padding: EdgeInsets.fromLTRB(32, 12, 32, 12),
child: SizedBox(
// height: 54,
width: 260,
child: Text(
"Book appointment",
style: TextStyle(
fontSize: 25,
fontFamily: 'Nexa',
color: Colors.white,
// fontWeight: FontWeight.bold
),
textAlign: TextAlign.center,
),
),
onPressed: (){Navigator.pushNamed(context, '/apmt');},
color: Color(0xff4A7C59),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0),
),
),
SizedBox(
height: 40,
),
RaisedButton(
elevation: 24,
padding: EdgeInsets.fromLTRB(32, 12, 32, 12),
child: SizedBox(
height: 28,
width: 260,
child: Text(
"Reports",
style: TextStyle(
fontSize: 25,
fontFamily: 'Nexa',
color: Colors.white,
// fontWeight: FontWeight.bold
),
textAlign: TextAlign.center,
),
),
onPressed: () async{
reports = await new List();
await getReports();
Navigator.pushNamed(context, '/report');
},
color: Color(0xff4A7C59),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0),
),
),
],
),
),
drawer: Container(
width: 150,
padding: EdgeInsets.fromLTRB(10, 42, 10, 36),
alignment: Alignment.topCenter,
color: Color(0xff4A7C59),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
CircleAvatar(
child: Icon(
Icons.person_pin_rounded,
size: 108,
color: Colors.white,
),
radius: 56,
backgroundColor: Color(0x00000000),
),
SizedBox(height: 20,),
SizedBox(
width: 170,
child: Column(
// crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Hello,",
style: TextStyle(
fontSize: 22,
fontFamily: 'Nexa',
color: Colors.white,
// fontWeight: FontWeight.bold
),
textAlign: TextAlign.left,
),
SizedBox(height: 10,),
Text(
currentName,
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Colors.white,
fontWeight: FontWeight.bold
),
textAlign: TextAlign.left,
),
SizedBox(height: 30,),
OutlineButton(
onPressed: (){Navigator.pushNamed(context, '/info');},
child: SizedBox(
width: 140,
child: Text(
"My Info",
style: TextStyle(
fontSize: 18,
fontFamily: 'Nexa',
color: Color(0xffffffff),
// fontWeight: FontWeight.bold
),
textAlign: TextAlign.center,
),
),
borderSide: BorderSide(
color: Colors.white,
width: 1,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0),
),
),
],
),
)
],
),
Column(
children: [
OutlineButton(
onPressed: (){
linkop('mailto:[email protected]');
},
child: SizedBox(
width: 140,
child: Text(
"FEEDBACK",
style: TextStyle(
fontSize: 18,
fontFamily: 'Nexa',
color: Color(0xffffffff),
fontWeight: FontWeight.w600
),
textAlign: TextAlign.center,
),
),
borderSide: BorderSide(
color: Colors.white,
width: 1,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0),
),
),
FlatButton(
onPressed: (){
clearAll();
Navigator.pushReplacementNamed(context, '/login');
},
child: SizedBox(
width: 140,
child: Text(
"LOGOUT",
style: TextStyle(
fontSize: 18,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
fontWeight: FontWeight.w600
),
textAlign: TextAlign.center,
),
),
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0),
),
),
],
),
],
),
),
drawerScrimColor: Color(0x55FAF3DD),
floatingActionButton: Container(
width: 70,
height: 70,
alignment: Alignment.topLeft,
child: FloatingActionButton(
elevation: 100,
onPressed: (){
return showDialog(context: context, barrierDismissible: false, builder: (context){
return AlertDialog(
title: Text(
"About the app",
textAlign: TextAlign.center,
),
titleTextStyle: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 24,
fontWeight: FontWeight.bold,
),
content: SingleChildScrollView(
child: Text(
"This app aims to present a comprehensive platform to provide an all-encompassing pandemic protection solution for people.\nUsers can know about the confirmed, recovered, active and death cases around the world to help them understand the spread of the virus. The care option of the app, which people can use to not only know about potential health risks, symptoms of COVID-19 and measures to be undertaken when facing certain symptoms but also to book appointments and receive their reports directly through the app. Since the system will be keeping a track of daily cases recorded in each country, it also has the option that helps people in deciding for their future travel plans.\nCovicare aims to assist the users in keeping safe and healthy in this pandemic in a hassle-free manner.\n\nDeveloper:\nRitwik Kundu",
style: TextStyle(
fontFamily: 'Nexa',
fontSize: 16,
),
textAlign: TextAlign.justify,
),
),
actions: [
MaterialButton(
onPressed: (){
Navigator.of(context).pop();
},
child: Text(
'Close',
style: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
splashColor: Color(0xff4A7C59),
)
],
backgroundColor: Color(0xffC8D5B9),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
);
});
},
/*database handler*/
// onPressed: (){
// // deleteData();
// // writeData();
// // readData();
// },
backgroundColor: Color(0x004A7C59),
// splashColor: Color(0x004A7C59),
// shape: ,
child: Icon(
Icons.info_sharp,
size: 60,
color: Color(0xff4A7C59),
),
),
),
);
}
/*database handler*/
//
// final DBRef = await FirebaseDatabase.instance.reference();
// void readData(){
// DBRef.child("regn").once().then((DataSnapshot dataSnapShot){
// var newdata = dataSnapShot.value;
// // var key = newdata.keys.elementAt("1234");
// newdata.forEach((key, values){
// print(values['phone']);
// });
// });
// print("data read");
// }
// void writeData(){
//
// DBRef.child("apmt").push().set({
// 'phone': "9685",
// 'type': "Testing",
// 'city': "Kolkata",
// 'date': "26/02/2019",
// 'slot': "12"
// });
// }
//
// void updateData(){
// DBRef.child("1").update({
// 'data':'This is an updated value'
// });
// print("data update");
// }
//
// void deleteData(){
// DBRef.child("regn").remove();
// print("data delete");
// }
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/database/dboperate.dart | import 'package:firebase_database/firebase_database.dart';
class DBOperate{
/*function to read data*/
static bool readData(String phn){
// database reference string
final DBRef = FirebaseDatabase.instance.reference();
bool fl = false;
print("Phone: "+phn);
DBRef.child("regn").once().then((DataSnapshot dataSnapShot){
var newdata = dataSnapShot.value;
// var key = newdata.keys.elementAt("1234");
newdata.forEach((key, values){print(values['phone']);if((values['phone'])==phn){fl = true;}});
return fl;
});
}
/*function to write registration data*/
static void writeRegData(String name, String dob, String phone, String password){
// database reference string
final DBRef = FirebaseDatabase.instance.reference();
DBRef.child("regn").child(phone).set({
'phone': phone,
'name': name,
'dob': dob,
'pass': password
});
print("data created");
}
/*function to update data on edit info*/
static void updateRegData(String name, String dob, String phone, String password){
// database reference string
final DBRef = FirebaseDatabase.instance.reference();
DBRef.child("regn").child(phone).update({
'name': name,
'dob': dob,
'pass': password
});
print("data updated");
}
/*function to delete data on account deletion*/
static void deleteAccData(String phone){
// database reference string
final DBRef = FirebaseDatabase.instance.reference();
DBRef.child("regn").child(phone).remove();
print("data deleted");
}
/*function to write appointment data*/
static void writeApmtData(String phone, String type, String city, String date, String slot){
// database reference string
final DBRef = FirebaseDatabase.instance.reference();
DBRef.child("apmt").push().set({
'phone': phone,
'type': type,
'city': city,
'date': date,
'slot': slot
});
print("data created");
}
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/pages/symp.dart | import 'package:flutter/material.dart';
class SympP extends StatefulWidget {
@override
_SympPState createState() => _SympPState();
}
class _SympPState extends State<SympP> {
bool s01 = false;
bool s02 = false;
bool s03 = false;
bool s04 = false;
bool s05 = false;
bool s06 = false;
bool s07 = false;
bool s08 = false;
bool s09 = false;
bool s10 = false;
int stot = 0;
/*scores for determining seriousness of COVID in symptoms option*/
// 02=fever
// 02=dry cough
// 01=tiredness
// 01=aches and pains
// 01=sore throat
// 01=diarrhoea
// 01=headache
// 10=loss of taste or smell
// 01=a rash on skin, or discolouration of fingers or toes
// 05=difficulty breathing or shortness of breath
//
// if total>=10 then COVID-19
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 24,
title: Text(
"Covicare",
style: TextStyle(
fontSize: 28,
fontFamily: 'Wind',
color: Colors.white,
),
),
centerTitle: true,
backgroundColor: Color(0xff4A7C59),
),
body: Container(
padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xffFAF3DD),
Color(0xffC8D5B9),
],
begin: Alignment.topCenter,
end: Alignment.bottomRight,
),
),
alignment: Alignment.topCenter,
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
SizedBox(height: 20,),
Column(
children: [
CheckboxListTile(
title: Text(
"Fever",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
value: s01,
onChanged: (bool value){
setState(() {
s01=value;
if (s01==true)
stot+=2;
else
stot-=2;
print(stot);
});
},
activeColor: Color(0xff4A7C59),
),
CheckboxListTile(
title: Text(
"Dry cough",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
value: s02,
onChanged: (bool value){
setState(() {
s02=value;
if (s02==true)
stot+=2;
else
stot-=2;
print(stot);
});
},
activeColor: Color(0xff4A7C59),
),
CheckboxListTile(
title: Text(
"Tiredness",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
value: s03,
onChanged: (bool value){
setState(() {
s03=value;
if (s03==true)
stot+=1;
else
stot-=1;
print(stot);
});
},
activeColor: Color(0xff4A7C59),
),
CheckboxListTile(
title: Text(
"Aches and pains",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
value: s04,
onChanged: (bool value){
setState(() {
s04=value;
if (s04==true)
stot+=1;
else
stot-=1;
print(stot);
});
},
activeColor: Color(0xff4A7C59),
),
CheckboxListTile(
title: Text(
"Sore throat",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
value: s05,
onChanged: (bool value){
setState(() {
s05=value;
if (s05==true)
stot+=1;
else
stot-=1;
print(stot);
});
},
activeColor: Color(0xff4A7C59),
),
CheckboxListTile(
title: Text(
"Diarrhoea",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
value: s06,
onChanged: (bool value){
setState(() {
s06=value;
if (s06==true)
stot+=1;
else
stot-=1;
print(stot);
});
},
activeColor: Color(0xff4A7C59),
),
CheckboxListTile(
title: Text(
"Headache",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
value: s07,
onChanged: (bool value){
setState(() {
s07=value;
if (s07==true)
stot+=1;
else
stot-=1;
print(stot);
});
},
activeColor: Color(0xff4A7C59),
),
CheckboxListTile(
title: Text(
"Loss of taste or smell",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
value: s08,
onChanged: (bool value){
setState(() {
s08=value;
if (s08==true)
stot+=10;
else
stot-=10;
print(stot);
});
},
activeColor: Color(0xff4A7C59),
),
CheckboxListTile(
title: Text(
"Skin rash, or discolouration of fingers or toes",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
value: s09,
onChanged: (bool value){
setState(() {
s09=value;
if (s09==true)
stot+=1;
else
stot-=1;
print(stot);
});
},
activeColor: Color(0xff4A7C59),
),
CheckboxListTile(
title: Text(
"Shortness of breath",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
value: s10,
onChanged: (bool value){
setState(() {
s10=value;
if (s10==true)
stot+=1;
else
stot-=1;
print(stot);
});
},
activeColor: Color(0xff4A7C59),
),
],
),
SizedBox(height: 25,),
RaisedButton(
onPressed: (){
if(stot>=10)
return showDialog(context: context, barrierDismissible: false, builder: (context){
return AlertDialog(
title: Text(
"It's better to get tested!",
textAlign: TextAlign.center,
),
titleTextStyle: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 24,
fontWeight: FontWeight.bold,
),
actions: [
MaterialButton(
onPressed: (){
Navigator.of(context).pop();
},
child: Text(
'Close',
style: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
splashColor: Color(0xff4A7C59),
)
],
backgroundColor: Color(0xffFAF3DD),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
);
});
else
return showDialog(context: context, barrierDismissible: false, builder: (context){
return AlertDialog(
title: Text(
"Seems you are fine!",
textAlign: TextAlign.center,
),
titleTextStyle: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 24,
fontWeight: FontWeight.bold,
),
actions: [
MaterialButton(
onPressed: (){
Navigator.of(context).pop();
},
child: Text(
'Close',
style: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
splashColor: Color(0xff4A7C59),
)
],
backgroundColor: Color(0xffFAF3DD),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
);
});
},
child: Text(
"CHECK",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xffFAF3DD),
),
),
elevation: 24,
padding: EdgeInsets.fromLTRB(45, 14, 45, 13),
color: Color(0xff4A7C59),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
),
),
SizedBox(height: 20,)
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/pages/report.dart | import 'package:covicare_app/main.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
class ReportP extends StatefulWidget {
@override
_ReportPState createState() => _ReportPState();
}
class _ReportPState extends State<ReportP> {
void linkop (work) async{
if (await canLaunch(work)){
await launch(work);
}
else{
print('Whoops!');
}
}
Widget ReportCard(rpid, urul){
return Column(
children: [
Card(
color: Color(0xff4A7C59),
shadowColor: Colors.black,
elevation: 24,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0)
),
child: Container(
width: 360,
padding: EdgeInsets.fromLTRB(22, 16, 22, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Report ID:",
style: TextStyle(
fontSize: 20,
fontFamily: 'Nexa',
color: Color(0xffFAF3DD),
)
),
Text(
"CVCR"+(rpid.substring(0,6)).toUpperCase(),
style: TextStyle(
fontSize: 22,
fontFamily: 'Nexa',
color: Color(0xffFAF3DD),
)
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
OutlineButton(
padding: EdgeInsets.fromLTRB(16, 6, 16, 6),
borderSide: BorderSide(
color: Color(0xffFAF3DD),
width: 1,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(1),
),
onPressed: (){
linkop(urul);
},
child: Text(
"View",
style: TextStyle(
fontSize: 20,
fontFamily: 'Nexa',
color: Color(0xffFAF3DD),
)
),
),
],
)
],
),
),
)
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 24,
title: Text(
"Covicare",
style: TextStyle(
fontSize: 28,
fontFamily: 'Wind',
color: Colors.white,
),
),
centerTitle: true,
backgroundColor: Color(0xff4A7C59),
),
body: Container(
padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xffFAF3DD),
Color(0xffC8D5B9),
],
begin: Alignment.topCenter,
end: Alignment.bottomRight,
),
),
alignment: Alignment.topCenter,
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(height: 30,),
Column(
mainAxisAlignment: MainAxisAlignment.start,
children: reports.map((e) => ReportCard(e[0], e[1])).toList(),
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/pages/register.dart | import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:covicare_app/database/dboperate.dart';
class RegisterP extends StatelessWidget {
TextEditingController nm = TextEditingController();
TextEditingController db = TextEditingController();
TextEditingController ph = TextEditingController();
TextEditingController pw = TextEditingController();
//flag is true when no matching phone number in database
bool flag=true;
Future<void> credValid(String phn) async
{
// var lock = new Lock();
// await lock.synchronized(() async {
// // database reference variable
// final DBRef = await FirebaseDatabase.instance.reference();
// await DBRef.child("regn").once().then((DataSnapshot dataSnapShot){
// var newdata = dataSnapShot.value;
// newdata.forEach((key,values){
// // print(values['phone']);
// if((values['phone'])==phn){
// ph.clear();nm.clear();db.clear();pw.clear();
// flag=false;
// }
// });
// });
// await Future.delayed(Duration(seconds:3),(){
// print("Assigned flag = "+flag.toString()+" in line 33");
// });
// });
// database reference variable
final DBRef = await FirebaseDatabase.instance.reference();
await DBRef.child("regn").once().then((DataSnapshot dataSnapShot){
var newdata = dataSnapShot.value;
newdata.forEach((key, values) {
// print(values['phone']);
if ((values['phone']) == phn) {
ph.clear();
nm.clear();
db.clear();
pw.clear();
flag = false;
}
});
});
// await Future.delayed(Duration(seconds:0),(){
// print("Assigned flag = "+flag.toString()+" in line 33");
// });
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},
child: Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(
color: Color(0xff4A7C59)
),
elevation: 24,
title: Text(
"Covicare",
style: TextStyle(
fontSize: 30,
fontFamily: 'Wind',
color: Color(0xff4A7C59),
),
),
centerTitle: true,
backgroundColor: Color(0xffFAF3DD),
),
body: Container(
padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
alignment: Alignment.topCenter,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xff4A7C59),
Color(0xff4A7C59),
// Color(0xffC8D5B9),
],
begin: Alignment.topCenter,
end: Alignment.bottomRight,
),
),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(height: 30,),
Text(
"Welcome!",
style: TextStyle(
fontSize: 48,
fontFamily: 'Nexa',
color: Color(0xffFAF3DD),
),
),
SizedBox(height: 50,),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
TextField(
controller: nm,
// maxLength: 10,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0xffFAF3DD),
filled: true,
hintText: 'Name',
hintStyle: TextStyle(
fontSize: 22,
fontFamily: 'Nexa',
color: Color(0x884A7C59),
),
),
keyboardType: TextInputType.name,
textInputAction: TextInputAction.go,
style: TextStyle(
fontSize: 24,
fontFamily: 'Righteous',
color: Color(0xff4A7C59),
),
),
SizedBox(height: 20,),
TextField(
controller: db,
maxLength: 10,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0xffFAF3DD),
filled: true,
hintText: 'DOB',
hintStyle: TextStyle(
fontSize: 22,
fontFamily: 'Nexa',
color: Color(0x884A7C59),
),
),
keyboardType: TextInputType.datetime,
textInputAction: TextInputAction.go,
style: TextStyle(
fontSize: 24,
fontFamily: 'Righteous',
color: Color(0xff4A7C59),
),
),
TextField(
controller: ph,
maxLength: 10,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0xffFAF3DD),
filled: true,
hintText: 'Phone',
hintStyle: TextStyle(
fontSize: 22,
fontFamily: 'Nexa',
color: Color(0x884A7C59),
),
),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.go,
style: TextStyle(
fontSize: 24,
fontFamily: 'Righteous',
color: Color(0xff4A7C59),
),
),
// SizedBox(height: 20,),
TextField(
controller: pw,
maxLength: 20,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0xffFAF3DD),
filled: true,
hintText: 'Password',
hintStyle: TextStyle(
fontSize: 22,
fontFamily: 'Nexa',
color: Color(0x884A7C59),
),
),
keyboardType: TextInputType.text,
textInputAction: TextInputAction.go,
style: TextStyle(
fontSize: 24,
fontFamily: 'Righteous',
color: Color(0xff4A7C59),
),
obscureText: true,
),
SizedBox(height: 20),
RaisedButton(
onPressed: () async{
if(ph.text.length==10 && pw.text.length >= 4 && db.text.length!=0 && nm.text.length!=0){
await credValid(ph.text);
}
else{
flag = false;
}
// print("Received flag = "+flag.toString()+" in line 199");
if(flag) {
// print("Inside of if");
DBOperate.writeRegData(nm.text,db.text,ph.text,pw.text);
Navigator.pop(context);
return showDialog(context: context, barrierDismissible: false, builder: (context){
return AlertDialog(
title: Text(
"Registration successful!",
textAlign: TextAlign.center,
),
titleTextStyle: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 24,
fontWeight: FontWeight.bold,
),
content: Icon(
Icons.done_outline_outlined,
size: 72,
color: Color(0xff4A7C59),
),
actions: [
MaterialButton(
onPressed: (){
Navigator.of(context).pop();
},
child: Text(
'Close',
style: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
splashColor: Color(0xff4A7C59),
)
],
backgroundColor: Color(0xffFAF3DD),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
);
}
);
}
else {
flag=true;
return showDialog(context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
title: Text(
"Try again!",
textAlign: TextAlign.center,
),
titleTextStyle: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 24,
fontWeight: FontWeight.bold,
),
content: Icon(
Icons.warning_amber_outlined,
size: 72,
color: Color(0xff4A7C59),
),
actions: [
MaterialButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Close',
style: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
splashColor: Color(0xff4A7C59),
)
],
backgroundColor: Color(0xffFAF3DD),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16)),
);
}
);
}
},
child: Text(
"SIGN UP",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
elevation: 24,
padding: EdgeInsets.fromLTRB(45, 14, 45, 13),
color: Color(0xffFAF3DD),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
),
)
],
),
],
),
),
),
),
);
}
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/pages/care.dart | import 'package:flutter/material.dart';
class CareP extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 24,
title: Text(
"Covicare",
style: TextStyle(
fontSize: 28,
fontFamily: 'Wind',
color: Colors.white,
),
),
centerTitle: true,
backgroundColor: Color(0xff4A7C59),
),
body: Container(
padding: EdgeInsets.fromLTRB(20, 70, 20, 30),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xffFAF3DD),
Color(0xffC8D5B9),
],
begin: Alignment.topCenter,
end: Alignment.bottomRight,
),
),
alignment: Alignment.center,
child: Column(
children: [
RaisedButton(
elevation: 24,
padding: EdgeInsets.fromLTRB(32, 12, 32, 12),
child: SizedBox(
// height: 54,
width: 260,
child: Text(
"Symptom analysis",
style: TextStyle(
fontSize: 28,
fontFamily: 'Nexa',
color: Colors.white,
// fontWeight: FontWeight.bold
),
textAlign: TextAlign.center,
),
),
onPressed: (){Navigator.pushNamed(context, '/symp');},
color: Color(0xff4A7C59),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
SizedBox(
height: 40,
),
RaisedButton(
elevation: 24,
padding: EdgeInsets.fromLTRB(32, 12, 32, 12),
child: SizedBox(
// height: 54,
width: 260,
child: Text(
"Book appointment",
style: TextStyle(
fontSize: 28,
fontFamily: 'Nexa',
color: Colors.white,
// fontWeight: FontWeight.bold
),
textAlign: TextAlign.center,
),
),
onPressed: (){Navigator.pushNamed(context, '/apmt');},
color: Color(0xff4A7C59),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
SizedBox(
height: 40,
),
RaisedButton(
elevation: 24,
padding: EdgeInsets.fromLTRB(32, 12, 32, 12),
child: SizedBox(
height: 28,
width: 260,
child: Text(
"Report",
style: TextStyle(
fontSize: 28,
fontFamily: 'Nexa',
color: Colors.white,
// fontWeight: FontWeight.bold
),
textAlign: TextAlign.center,
),
),
onPressed: (){Navigator.pushNamed(context, '/report');},
color: Color(0xff4A7C59),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/pages/stats.dart | import 'package:covicare_app/screens/country.dart';
import 'package:covicare_app/screens/global.dart';
import 'package:flutter/material.dart';
class StatsP extends StatefulWidget {
@override
_StatsPState createState() => _StatsPState();
}
class _StatsPState extends State<StatsP> {
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
initialIndex: 0,
child: Scaffold(
appBar: AppBar(
elevation: 24,
title: Text(
"Covicare",
style: TextStyle(
fontSize: 28,
fontFamily: 'Wind',
color: Colors.white,
),
),
centerTitle: true,
backgroundColor: Color(0xff4A7C59),
bottom: TabBar(
indicatorColor: Colors.white,
tabs: [
Tab(icon: Icon(Icons.blur_circular, color: Colors.white,),),
Tab(icon: Icon(Icons.flag, color: Colors.white,),),
],
),
),
body: Container(
padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xffFAF3DD),
Color(0xffC8D5B9),
],
begin: Alignment.topCenter,
end: Alignment.bottomRight,
),
),
alignment: Alignment.center,
child: TabBarView(
children: [
Global(),
Country(),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/pages/loader.dart | import 'package:flutter/material.dart';
class LoadingP extends StatefulWidget {
@override
_LoadingPState createState() => _LoadingPState();
}
class _LoadingPState extends State<LoadingP> {
String redirectTrix() {
Future.delayed(Duration(seconds: 2), (){
Navigator.pushReplacementNamed(context, '/login');
});
return 'Covicare';
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: Container(
// padding: EdgeInsets.fromLTRB(32, 280, 32, 96),
// alignment: Alignment.center,
color: Color(0xff4A7C59),
child: Center(
child: Text(
redirectTrix(),
style: TextStyle(
fontSize: 56,
fontFamily: 'Wind',
color: Color(0xffFAF3DD),
),
),
),
),
);
}
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/pages/login.dart | import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:covicare_app/main.dart';
class LoginP extends StatelessWidget {
TextEditingController id = TextEditingController();
TextEditingController pw = TextEditingController();
//flag is true when no matching phone number in database
bool loginFlag=false;
Future<void> credValid(String ids, String pws) async
{
final DBRef = await FirebaseDatabase.instance.reference();
await DBRef.child("regn").once().then((DataSnapshot dataSnapShot){
var newdata = dataSnapShot.value;
newdata.forEach((key,values){
print(values['phone']);
if((values['phone'])==ids && (values['pass'])==pws){
currentPh = values['phone'];
currentName = values['name'];
currentPass = values['pass'];
currentDob = values['dob'];
loginFlag=true;
}
});
id.clear();pw.clear();
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},
child: Scaffold(
body: Container(
padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
alignment: Alignment.topCenter,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xffFAF3DD),
Color(0xffC8D5B9),
],
begin: Alignment.topCenter,
end: Alignment.bottomRight,
),
),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(height: 120,),
Text(
"Covicare",
// style: GoogleFonts.pacifico(),
style: TextStyle(
fontSize: 65,
fontFamily: 'Wind',
color: Color(0xff4A7C59),
),
),
SizedBox(height: 2,),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(height: 75,),
TextField(
controller: id,
maxLength: 10,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0x99ffffff),
filled: true,
hintText: 'Phone',
hintStyle: TextStyle(
fontSize: 22,
fontFamily: 'Nexa',
color: Color(0x884A7C59),
),
),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.go,
style: TextStyle(
fontSize: 24,
fontFamily: 'Righteous',
color: Color(0xff4A7C59),
),
cursorColor: Color(0xff4A7C59),
),
// SizedBox(height: 20,),
TextField(
controller: pw,
maxLength: 20,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0x99ffffff),
filled: true,
hintText: 'Password',
hintStyle: TextStyle(
fontSize: 22,
fontFamily: 'Nexa',
color: Color(0x884A7C59),
),
),
keyboardType: TextInputType.text,
textInputAction: TextInputAction.go,
style: TextStyle(
fontSize: 24,
fontFamily: 'Righteous',
color: Color(0xff4A7C59),
),
obscureText: true,
cursorColor: Color(0xff4A7C59),
),
SizedBox(height: 50,),
RaisedButton(
onPressed: () async{
await credValid(id.text,pw.text);
if(loginFlag) {
Navigator.pushReplacementNamed(context, '/home');
}
else
return showDialog(context: context, barrierDismissible: false, builder: (context){
return AlertDialog(
title: Text(
"Invalid Credentials!",
textAlign: TextAlign.center,
),
titleTextStyle: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 24,
fontWeight: FontWeight.bold,
),
content: Icon(
Icons.warning_amber_rounded,
size: 72,
color: Color(0xff4A7C59),
),
actions: [
MaterialButton(
onPressed: (){
Navigator.of(context).pop();
},
child: Text(
'Close',
style: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
splashColor: Color(0xff4A7C59),
)
],
backgroundColor: Color(0xffFAF3DD),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
);
});
},
child: Text(
"LOGIN",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xffFAF3DD),
),
),
elevation: 24,
padding: EdgeInsets.fromLTRB(65, 14, 65, 13),
color: Color(0xff4A7C59),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
),
),
],
),
// SizedBox(height: 0,),
SizedBox(height: 30,),
FlatButton(
onPressed: (){
Navigator.pushNamed(context, '/register');
id.clear();pw.clear();
},
child: Text(
"Sign up",
style: TextStyle(
fontSize: 20,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
)
)
),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/pages/apmt.dart | import 'package:covicare_app/database/dboperate.dart';
import 'package:covicare_app/main.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class ApmtP extends StatefulWidget {
@override
_ApmtPState createState() => _ApmtPState();
}
class _ApmtPState extends State<ApmtP> {
String cityChoice;
String slotChoice;
String typeChoice;
String dateChoice = "Date";
DateTime dtTom = DateTime.now().add(const Duration(days: 1));
DateTime dtPicked = DateTime.now();
List typeList = ["Consultation", "Testing",];
List cityList = ["Delhi", "Pune", "Mumbai", "Bangalore", "Chennai", "Kolkata", "Thane", "Nagpur",];
List slotList = ["10 AM - 11 AM", "11 AM - 12 PM", "12 PM - 1 PM", "1 PM - 2 PM", "2 PM - 3 PM", "3 PM - 4 PM", "4 PM - 5 PM", "5 PM - 6 PM", "6 PM - 7 PM", "7 PM - 8 PM", "8 PM - 9 PM",];
bool flag = true;
Future<void> credValid(String typ, String cty, String dtt, String slt) async
{
final DBRef = await FirebaseDatabase.instance.reference();
await DBRef.child("apmt").once().then((DataSnapshot dataSnapShot){
var newdata = dataSnapShot.value;
newdata.forEach((key,values){
if((values['type'])==typ && (values['city'])==cty && (values['date'])==dtt && (values['slot'])==slt){
flag=false;
}
});
});
}
void bookApmt(String typ, String cty, String dtt, String slt){
DBOperate.writeApmtData(currentPh, typ, cty, dtt, slt);
print(cityChoice + " " + dateChoice + " " + slotChoice);
}
Future<Null> selectTimPicker(BuildContext context) async {
dtPicked = await showDatePicker(
context: context,
initialDate: dtTom,
firstDate: dtTom,
lastDate: DateTime(2030),
builder: (BuildContext context, Widget child) {
return Theme(
data: ThemeData.light().copyWith(
colorScheme: ColorScheme.light().copyWith(
primary: Color(0xff4A7C59), //head bar
onPrimary: Color(0xffFAF3DD), //heading text
onSurface: Color(0xff4A7C59), //content text
),
),
child: child,
);
}
);
if (dtPicked!=null)
{
setState(() {
String dd, mm, yyyy;
dd = dtPicked.day.toString().length<2? "0"+dtPicked.day.toString() : dtPicked.day.toString();
mm = dtPicked.month.toString().length<2? "0"+dtPicked.month.toString() : dtPicked.month.toString();
yyyy = dtPicked.year.toString().length<2? "0"+dtPicked.year.toString() : dtPicked.year.toString();
dateChoice = dd+"-"+mm+"-"+yyyy;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
elevation: 24,
title: Text(
"Covicare",
style: TextStyle(
fontSize: 28,
fontFamily: 'Wind',
color: Colors.white,
),
),
centerTitle: true,
backgroundColor: Color(0xff4A7C59),
),
body: Container(
padding: EdgeInsets.fromLTRB(20, 50, 20, 30),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xffFAF3DD),
Color(0xffC8D5B9),
],
begin: Alignment.topCenter,
end: Alignment.bottomRight,
),
),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
// Text(
// "Appointments",
// style: TextStyle(
// fontSize: 48,
// fontFamily: 'Wind',
// color: Color(0xff4A7C59),
// ),
// ),
// SizedBox(
// // height: 88,
// ),
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
decoration: BoxDecoration(
color: Color(0xffFAF3DD),
borderRadius: BorderRadius.circular(0),
),
child: DropdownButton(
hint: Container(
width: 260,
child: Text(
"Type",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
),
icon: Icon(Icons.arrow_drop_down_sharp),
iconSize: 36,
iconEnabledColor: Color(0xff4A7C59),
dropdownColor: Color(0xffFAF3DD),
value: typeChoice,
onChanged: (slotNew){
setState(() {
typeChoice = slotNew;
});
},
items: typeList.map((typeName){
return DropdownMenuItem(
value: typeName,
child: Text(
typeName,
style: TextStyle(
fontSize: 26,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
)
);
}).toList(),
),
),
SizedBox(
height: 32,
),
Container(
padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
decoration: BoxDecoration(
color: Color(0xffFAF3DD),
borderRadius: BorderRadius.circular(0),
),
child: DropdownButton(
hint: Container(
width: 260,
child: Text(
"City",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
),
icon: Icon(Icons.arrow_drop_down_sharp),
iconSize: 36,
iconEnabledColor: Color(0xff4A7C59),
dropdownColor: Color(0xffFAF3DD),
value: cityChoice,
onChanged: (cityNew){
setState(() {
cityChoice = cityNew;
});
},
items: cityList.map((cityName){
return DropdownMenuItem(
value: cityName,
child: Text(
cityName,
style: TextStyle(
fontSize: 26,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
)
);
}).toList(),
),
),
SizedBox(
height: 32,
),
Container(
padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
decoration: BoxDecoration(
color: Color(0xffFAF3DD),
borderRadius: BorderRadius.circular(0),
),
child: InkWell(
onTap: (){
onTap: selectTimPicker(context);
},
child: Container(
padding: EdgeInsets.fromLTRB(0, 0, 8, 0),
alignment: Alignment.center,
height: 54,
width: 298,
// width: MediaQuery.of(context).size.width,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
dateChoice,
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
Icon(
Icons.calendar_today_sharp,
size: 22,
color: Color(0xff4A7C59),
)
],
),
),
)
),
SizedBox(
height: 32,
),
Container(
padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
decoration: BoxDecoration(
color: Color(0xffFAF3DD),
borderRadius: BorderRadius.circular(0),
),
child: DropdownButton(
hint: Container(
width: 260,
child: Text(
"Slot",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
),
icon: Icon(Icons.arrow_drop_down_sharp),
iconSize: 36,
iconEnabledColor: Color(0xff4A7C59),
dropdownColor: Color(0xffFAF3DD),
value: slotChoice,
onChanged: (slotNew){
setState(() {
slotChoice = slotNew;
});
},
items: slotList.map((slotName){
return DropdownMenuItem(
value: slotName,
child: Text(
slotName,
style: TextStyle(
fontSize: 26,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
)
);
}).toList(),
),
),
],
),
SizedBox(
// height: 96,
),
RaisedButton(
onPressed: () async{
await credValid(typeChoice, cityChoice, dateChoice, slotChoice);
if(flag) {
bookApmt(typeChoice, cityChoice, dateChoice, slotChoice);
return showDialog(context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
title: Text(
"Booking successful!",
textAlign: TextAlign.center,
),
titleTextStyle: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 24,
fontWeight: FontWeight.bold,
),
content: Icon(
Icons.done_outline_outlined,
size: 72,
color: Color(0xff4A7C59),
),
actions: [
MaterialButton(
onPressed: () {
Navigator.of(context).pop();
Navigator.of(context).pop();
},
child: Text(
'Close',
style: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
splashColor: Color(0xff4A7C59),
)
],
backgroundColor: Color(0xffFAF3DD),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16)),
);
});
}
else
return showDialog(context: context, barrierDismissible: false, builder: (context){
return AlertDialog(
title: Text(
"Try another slot!",
textAlign: TextAlign.center,
),
titleTextStyle: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 24,
fontWeight: FontWeight.bold,
),
content: Icon(
Icons.warning_amber_outlined,
size: 72,
color: Color(0xff4A7C59),
),
actions: [
MaterialButton(
onPressed: (){
Navigator.of(context).pop();
},
child: Text(
'Close',
style: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
splashColor: Color(0xff4A7C59),
)
],
backgroundColor: Color(0xffFAF3DD),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
);
});
},
child: Text(
"BOOK",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xffFAF3DD),
),
),
elevation: 24,
padding: EdgeInsets.fromLTRB(45, 14, 45, 13),
color: Color(0xff4A7C59),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/pages/editinfo.dart | import 'package:covicare_app/database/dboperate.dart';
import 'package:covicare_app/main.dart';
import 'package:flutter/material.dart';
import 'dart:math';
class EditinfoP extends StatefulWidget {
@override
_EditinfoPState createState() => _EditinfoPState();
}
class _EditinfoPState extends State<EditinfoP> {
TextEditingController nm = TextEditingController();
TextEditingController db = TextEditingController();
TextEditingController pw = TextEditingController();
TextEditingController pw2 = TextEditingController();
bool credValid(String psw, String psw2)
{
if (psw.length>=4 && psw==psw2)
{
// ph.clear();
// pw.clear();
return true;
}
else
{
pw.clear();
pw2.clear();
return false;
}
}
void updtAc(){
DBOperate.updateRegData(nm.text,db.text,currentPh,pw.text);
print("Updating account");
}
void dltAc(){
DBOperate.deleteAccData(currentPh);
print("Deleted account");
Navigator.pop(context);
Navigator.pop(context);
Navigator.pop(context);
Navigator.pushReplacementNamed(context, '/login');
}
void insertText(String insert, TextEditingController controller) {
final int cursorPos = controller.selection.base.offset;
controller.value = controller.value.copyWith(
text: controller.text.replaceRange(max(cursorPos, 0), max(cursorPos, 0), insert),
selection: TextSelection.fromPosition(TextPosition(offset: max(cursorPos, 0) + insert.length))
);
}
@override
void initState() {
super.initState();
insertText(currentName, nm);
insertText(currentDob, db);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},
child: Scaffold(
// resizeToAvoidBottomInset: false,
appBar: AppBar(
iconTheme: IconThemeData(
color: Color(0xff4A7C59)
),
elevation: 24,
title: Text(
"Covicare",
style: TextStyle(
fontSize: 30,
fontFamily: 'Wind',
color: Color(0xff4A7C59),
),
),
centerTitle: true,
backgroundColor: Color(0xffFAF3DD),
),
body: Container(
padding: EdgeInsets.fromLTRB(20, 0, 20, 20),
alignment: Alignment.center,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xff4A7C59),
Color(0xff4A7C59),
// Color(0xffC8D5B9),
],
begin: Alignment.topCenter,
end: Alignment.bottomRight,
),
),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// SizedBox(height: 10,),
Text(
"Edit info",
style: TextStyle(
fontSize: 46,
fontFamily: 'Nexa',
color: Color(0xffFAF3DD),
),
),
SizedBox(height: 30,),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
TextField(
cursorColor: Color(0x884A7C59),
controller: nm,
// maxLength: 10,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0xffFAF3DD),
filled: true,
hintText: 'Name',
hintStyle: TextStyle(
fontSize: 22,
fontFamily: 'Nexa',
color: Color(0x884A7C59),
),
),
keyboardType: TextInputType.name,
textInputAction: TextInputAction.go,
style: TextStyle(
fontSize: 24,
fontFamily: 'Righteous',
color: Color(0xff4A7C59),
),
),
SizedBox(height: 20,),
TextField(
cursorColor: Color(0x884A7C59),
controller: db,
maxLength: 10,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0xffFAF3DD),
filled: true,
hintText: 'DOB',
hintStyle: TextStyle(
fontSize: 22,
fontFamily: 'Nexa',
color: Color(0x884A7C59),
),
),
keyboardType: TextInputType.datetime,
textInputAction: TextInputAction.go,
style: TextStyle(
fontSize: 24,
fontFamily: 'Righteous',
color: Color(0xff4A7C59),
),
),
TextField(
cursorColor: Color(0x884A7C59),
obscureText: true,
controller: pw,
maxLength: 20,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0xffFAF3DD),
filled: true,
hintText: 'New password',
hintStyle: TextStyle(
fontSize: 22,
fontFamily: 'Nexa',
color: Color(0x884A7C59),
),
),
keyboardType: TextInputType.text,
textInputAction: TextInputAction.go,
style: TextStyle(
fontSize: 24,
fontFamily: 'Righteous',
color: Color(0xff4A7C59),
),
),
TextField(
cursorColor: Color(0x884A7C59),
obscureText: true,
controller: pw2,
maxLength: 20,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0xffFAF3DD),
filled: true,
hintText: 'Confirm password',
hintStyle: TextStyle(
fontSize: 22,
fontFamily: 'Nexa',
color: Color(0x884A7C59),
),
),
keyboardType: TextInputType.text,
textInputAction: TextInputAction.go,
style: TextStyle(
fontSize: 24,
fontFamily: 'Righteous',
color: Color(0xff4A7C59),
),
),
SizedBox(height: 30,),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
OutlineButton(
onPressed: (){
return showDialog(context: context, barrierDismissible: false, builder: (context){
return AlertDialog(
title: Text(
"Are you sure you want to delete your account?",
textAlign: TextAlign.center,
),
titleTextStyle: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 24,
fontWeight: FontWeight.bold,
),
content: Icon(
Icons.warning_amber_outlined,
size: 72,
color: Color(0xff4A7C59),
),
actions: [
SizedBox(
width: MediaQuery.of(context).size.width,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
MaterialButton(
onPressed: (){
Navigator.of(context).pop();
},
child: Text(
'Cancel',
style: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
splashColor: Color(0xff4A7C59),
),
MaterialButton(
onPressed: null,
child: Text(
' ',
style: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
splashColor: Color(0xff4A7C59),
),
MaterialButton(
onPressed: (){
dltAc();
showDialog(context: context, barrierDismissible: false, builder: (context){
return AlertDialog(
title: Text(
"Sorry, to see you go!",
textAlign: TextAlign.center,
),
titleTextStyle: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 24,
fontWeight: FontWeight.bold,
),
content: Icon(
Icons.warning_amber_outlined,
size: 72,
color: Color(0xff4A7C59),
),
actions: [
SizedBox(
width: MediaQuery.of(context).size.width,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
MaterialButton(
onPressed: (){
Navigator.of(context).pop();
},
child: Text(
'Close',
style: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
splashColor: Color(0xff4A7C59),
),
]
),
),
],
backgroundColor: Color(0xffFAF3DD),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
);
});
// Navigator.of(context).pop();
},
child: Text(
'Confirm',
style: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
splashColor: Color(0xff4A7C59),
),
]
),
),
],
backgroundColor: Color(0xffFAF3DD),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
);
}
);
},
child: Text(
"DELETE",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xffFAF3DD),
),
),
// elevation: 24,
padding: EdgeInsets.fromLTRB(32, 14, 32, 13),
// color: Color(0xffFAF3DD),
borderSide: BorderSide(
color: Color(0xff4A7C59),
width: 1,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
),
),
FlatButton(
onPressed: (){
if(credValid(pw.text, pw2.text)) {
updtAc();
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.pushReplacementNamed(context, '/login');
return showDialog(context: context, barrierDismissible: false, builder: (context) {
return AlertDialog(
title: Text(
"Update successfull!",
textAlign: TextAlign.center,
),
titleTextStyle: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 24,
fontWeight: FontWeight.bold,
),
content: Icon(
Icons.done_outline_sharp,
size: 72,
color: Color(0xff4A7C59),
),
actions: [
MaterialButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Close',
style: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
splashColor: Color(0xff4A7C59),
),
],
backgroundColor: Color(0xffFAF3DD),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16)),
);
}
);
}
else
{
return showDialog(context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
title: Text(
"Try again!",
textAlign: TextAlign.center,
),
titleTextStyle: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 24,
fontWeight: FontWeight.bold,
),
content: Icon(
Icons.warning_amber_outlined,
size: 72,
color: Color(0xff4A7C59),
),
actions: [
MaterialButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Close',
style: TextStyle(
color: Color(0xff4A7C59),
fontFamily: 'Nexa',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
splashColor: Color(0xff4A7C59),
),
],
backgroundColor: Color(0xffFAF3DD),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16)),
);
}
);
}
},
child: Text(
"UPDATE",
style: TextStyle(
fontSize: 24,
fontFamily: 'Nexa',
color: Color(0xff4A7C59),
),
),
// elevation: 24,
padding: EdgeInsets.fromLTRB(32, 14, 32, 13),
color: Color(0xffFAF3DD),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
),
),
],
),
SizedBox(height: 10,),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/pages/pinfo.dart | import 'package:flutter/material.dart';
import 'package:covicare_app/main.dart';
class PinfoP extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(
color: Color(0xff4A7C59)
),
elevation: 24,
title: Text(
"Covicare",
style: TextStyle(
fontSize: 30,
fontFamily: 'Wind',
color: Color(0xff4A7C59),
),
),
centerTitle: true,
backgroundColor: Color(0xffFAF3DD),
),
body: Container(
padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
alignment: Alignment.topCenter,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xff4A7C59),
Color(0xff4A7C59),
// Color(0xffC8D5B9),
],
begin: Alignment.topCenter,
end: Alignment.bottomRight,
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// SizedBox(height: 30,),
// Text(
// "My info",
// style: TextStyle(
// fontSize: 48,
// fontFamily: 'Wind',
// color: Color(0xffFAF3DD),
// ),
// ),
SizedBox(height: 30,),
CircleAvatar(
child: Icon(
Icons.person_pin_sharp,
size: 162,
color: Color(0xffFAF3DD),
),
radius: 81,
backgroundColor: Color(0x00000000),
),
SizedBox(height: 60,),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(width: 2000,),
Text(
"Name",
style: TextStyle(
fontSize: 20,
fontFamily: 'Righteous',
color: Color(0xffFAF3DD),
)
),
Text(
currentName,
style: TextStyle(
fontSize: 36,
fontFamily: 'Nexa',
color: Color(0xffFAF3DD),
)
),
SizedBox(height: 20,),
Text(
"DOB",
style: TextStyle(
fontSize: 20,
fontFamily: 'Righteous',
color: Color(0xffFAF3DD),
)
),
Text(
currentDob,
style: TextStyle(
fontSize: 36,
fontFamily: 'Nexa',
color: Color(0xffFAF3DD),
)
),
SizedBox(height: 20,),
Text(
"Phone",
style: TextStyle(
fontSize: 20,
fontFamily: 'Righteous',
color: Color(0xffFAF3DD),
)
),
Text(
currentPh,
style: TextStyle(
fontSize: 36,
fontFamily: 'Nexa',
color: Color(0xffFAF3DD),
)
),
],
),
SizedBox(height: 0,),
SizedBox(height: 0,),
],
),
),
floatingActionButton: Container(
width: 70,
height: 70,
alignment: Alignment.topLeft,
child: FloatingActionButton(
elevation: 6,
onPressed: (){
Navigator.pushNamed(context, "/editinfo");
},
backgroundColor: Color(0xffFAF3DD),
child: Icon(Icons.edit, color: Color(0xff4A7C59),),
),
),
);
}
}
| 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/models/country.dart | class CountryModel{
final String country;
final String slug;
final String iso2;
CountryModel(this.country, this.slug, this.iso2);
factory CountryModel.fromJson(Map<String, dynamic> json){
return CountryModel(
json["Country"],
json["Slug"],
json["ISO2"],
);
}
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/models/global_summary.dart | class GlobalSummaryModel{
final int newConfirmed;
final int totalConfirmed;
final int newDeaths;
final int totalDeaths;
final int newRecovered;
final int totalRecovered;
final DateTime date;
GlobalSummaryModel(this.newConfirmed, this.totalConfirmed, this.newDeaths, this.totalDeaths, this.newRecovered, this.totalRecovered, this.date);
factory GlobalSummaryModel.fromJson(Map<String, dynamic> json){
return GlobalSummaryModel(
json["Global"]["NewConfirmed"],
json["Global"]["TotalConfirmed"],
json["Global"]["NewDeaths"],
json["Global"]["TotalDeaths"],
json["Global"]["NewRecovered"],
json["Global"]["TotalRecovered"],
DateTime.parse(json["Date"]),
);
}
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/models/country_summary.dart | class CountrySummaryModel{
final String country;
final int confirmed;
final int death;
final int recovered;
final int active;
final DateTime date;
CountrySummaryModel(this.country, this.confirmed, this.death, this.recovered, this.active, this.date);
factory CountrySummaryModel.fromJson(Map<String, dynamic> json){
return CountrySummaryModel(
json["Country"],
json["Confirmed"],
json["Deaths"],
json["Recovered"],
json["Active"],
DateTime.parse(json["Date"]),
);
}
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/models/time_series_cases.dart | class TimeSeriesCases {
final DateTime time;
final int cases;
TimeSeriesCases(this.time, this.cases);
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/utils/constants.dart | import 'package:flutter/material.dart';
Color kPrimaryColor = Color(0xFF166DE0);
Color kConfirmedColor = Color(0xFFFF1242);
Color kActiveColor = Color(0xFF017BFF);
Color kRecoveredColor = Color(0xFF29A746);
Color kDeathColor = Color(0xFF6D757D);
LinearGradient kGradientShimmer = LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [
Color(0xfff3ebd8),
Color(0xfff3ebd8),
],
);
RegExp reg = new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
Function mathFunc = (Match match) => '${match[1]}.'; | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/services/covid_service.dart | import 'package:http/http.dart' as http;
import 'dart:convert';
import '../models/global_summary.dart';
import '../models/country_summary.dart';
import '../models/country.dart';
class CovidService{
Future<GlobalSummaryModel> getGlobalSummary() async{
final data = await http.Client().get("https://api.covid19api.com/summary");
if(data.statusCode != 200)
throw Exception();
GlobalSummaryModel summary = new GlobalSummaryModel.fromJson(json.decode(data.body));
return summary;
}
Future<List<CountrySummaryModel>> getCountrySummary(String slug) async{
final data = await http.Client().get("https://api.covid19api.com/total/dayone/country/" + slug);
if(data.statusCode != 200)
throw Exception();
List<CountrySummaryModel> summaryList = (json.decode(data.body) as List).map((item) => new CountrySummaryModel.fromJson(item)).toList();
return summaryList;
}
Future<List<CountryModel>> getCountryList() async{
final data = await http.Client().get("https://api.covid19api.com/countries");
if(data.statusCode != 200)
throw Exception();
List<CountryModel> countries = (json.decode(data.body) as List).map((item) => new CountryModel.fromJson(item)).toList();
return countries;
}
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/screens/country.dart | import 'package:flutter/material.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
import '../screens/country_statistics.dart';
import '../screens/country_loading.dart';
import '../services/covid_service.dart';
import '../models/country_summary.dart';
import '../models/country.dart';
CovidService covidService = CovidService();
class Country extends StatefulWidget {
@override
_CountryState createState() => _CountryState();
}
class _CountryState extends State<Country> {
final TextEditingController _typeAheadController = TextEditingController();
Future<List<CountryModel>> countryList;
Future<List<CountrySummaryModel>> summaryList;
@override
initState() {
super.initState();
countryList = covidService.getCountryList();
this._typeAheadController.text = "India";
summaryList = covidService.getCountrySummary("india");
}
List<String> _getSuggestions(List<CountryModel> list, String query) {
List<String> matches = List();
for (var item in list) {
matches.add(item.country);
}
matches.retainWhere((s) => s.toLowerCase().contains(query.toLowerCase()));
return matches;
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},
child: SingleChildScrollView(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Padding(
padding: EdgeInsets.symmetric(horizontal: 4, vertical: 6),
child: Text(
"Country Cases",
style: TextStyle(
color: Color(0xffC8D5B9),
fontWeight: FontWeight.bold,
fontSize: 14,
),
),
),
GestureDetector(
onTap: () {
setState(() {
summaryList = covidService.getCountrySummary("india");
});
},
child: Icon(
Icons.refresh,
color: Color(0xffC8D5B9),
),
),
],
),
FutureBuilder(
future: countryList,
builder: (context, snapshot) {
if (snapshot.hasError)
return Center(child: Text("Error"),);
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return CountryLoading(
inputTextLoading: true
);
default:
return !snapshot.hasData
? Center(child: Text("Empty"),)
: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
// Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// Padding(
// padding: EdgeInsets.symmetric(horizontal: 4, vertical: 6),
// child: Text(
// "Country Cases",
// style: TextStyle(
// color: Color(0xffC8D5B9),
// fontWeight: FontWeight.bold,
// fontSize: 14,
// ),
// ),
// ),
// GestureDetector(
// onTap: () {
// setState(() {
// summaryList = covidService.getCountrySummary("india");
// });
// },
// child: Icon(
// Icons.refresh,
// color: Color(0xffC8D5B9),
// ),
// ),
// ],
// ),
TypeAheadFormField(
textFieldConfiguration: TextFieldConfiguration(
controller: this._typeAheadController,
decoration: InputDecoration(
hintText: 'Type name of country',
hintStyle: TextStyle(fontSize: 16),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: BorderSide(
width: 0,
style: BorderStyle.none,
),
),
filled: true,
fillColor: Colors.grey[200],
contentPadding: EdgeInsets.all(20),
prefixIcon: Padding(
padding: EdgeInsets.only(left: 24.0, right: 16.0),
child: Icon(
Icons.search,
color: Colors.black,
size: 28,
),
),
),
),
suggestionsCallback: (pattern) {
return _getSuggestions(snapshot.data, pattern);
},
itemBuilder: (context, suggestion) {
return ListTile(
title: Text(suggestion),
);
},
transitionBuilder: (context, suggestionsBox, controller) {
return suggestionsBox;
},
onSuggestionSelected: (suggestion) {
this._typeAheadController.text = suggestion;
setState(() {
summaryList = covidService.getCountrySummary(
snapshot.data.firstWhere((element) => element.country == suggestion).slug);
});
},
),
SizedBox(
height: 8,
),
FutureBuilder(
future: summaryList,
builder: (context, snapshot) {
if (snapshot.hasError)
return Center(child: Text("Error"),);
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return CountryLoading(
inputTextLoading: false
);
default:
return !snapshot.hasData
? Center(child: Text("Empty"),)
: CountryStatistics(
summaryList: snapshot.data,
);
}
},
),
],
);
}
},
),
],
),
),
);
}
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/screens/country_statistics.dart | import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'chart.dart';
import '../utils/constants.dart';
import '../models/country_summary.dart';
import '../models/time_series_cases.dart';
class CountryStatistics extends StatelessWidget {
final List<CountrySummaryModel> summaryList;
CountryStatistics({@required this.summaryList});
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
buildCard(
"CONFIRMED",
summaryList[summaryList.length - 1].confirmed,
kConfirmedColor,
"ACTIVE",
summaryList[summaryList.length - 1].active,
kActiveColor,
),
buildCard(
"RECOVERED",
summaryList[summaryList.length - 1].recovered,
kRecoveredColor,
"DEATH",
summaryList[summaryList.length - 1].death,
kDeathColor,
),
buildCardChart(summaryList),
],
);
}
Widget buildCard(String leftTitle, int leftValue, Color leftColor, String rightTitle, int rightValue, Color rightColor){
return Card(
elevation: 1,
child: Container(
height: 100,
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
leftTitle,
style: TextStyle(
color: Colors.grey,
fontWeight: FontWeight.bold,
fontSize: 14,
),
),
Expanded(
child: Container(),
),
Text(
"Total",
style: TextStyle(
color: leftColor,
fontWeight: FontWeight.bold,
fontSize: 12,
),
),
Text(
leftValue.toString().replaceAllMapped(reg, mathFunc),
style: TextStyle(
color: leftColor,
fontWeight: FontWeight.bold,
fontSize: 28,
),
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Text(
rightTitle,
style: TextStyle(
color: Colors.grey,
fontWeight: FontWeight.bold,
fontSize: 14,
),
),
Expanded(
child: Container(),
),
Text(
"Total",
style: TextStyle(
color: rightColor,
fontWeight: FontWeight.bold,
fontSize: 12,
),
),
Text(
rightValue.toString().replaceAllMapped(reg, mathFunc),
style: TextStyle(
color: rightColor,
fontWeight: FontWeight.bold,
fontSize: 28,
),
),
],
),
],
),
),
);
}
Widget buildCardChart(List<CountrySummaryModel> summaryList){
return Card(
elevation: 1,
child: Container(
height: 190,
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Chart(
_createData(summaryList),
animate: false,
),
),
);
}
static List<charts.Series<TimeSeriesCases, DateTime>> _createData(List<CountrySummaryModel> summaryList) {
List<TimeSeriesCases> confirmedData = [];
List<TimeSeriesCases> activeData = [];
List<TimeSeriesCases> recoveredData = [];
List<TimeSeriesCases> deathData = [];
for (var item in summaryList) {
confirmedData.add(TimeSeriesCases(item.date, item.confirmed));
activeData.add(TimeSeriesCases(item.date, item.active));
recoveredData.add(TimeSeriesCases(item.date, item.recovered));
deathData.add(TimeSeriesCases(item.date, item.death));
}
return [
new charts.Series<TimeSeriesCases, DateTime>(
id: 'Confirmed',
colorFn: (_, __) => charts.ColorUtil.fromDartColor(kConfirmedColor),
domainFn: (TimeSeriesCases cases, _) => cases.time,
measureFn: (TimeSeriesCases cases, _) => cases.cases,
data: confirmedData,
),
new charts.Series<TimeSeriesCases, DateTime>(
id: 'Active',
colorFn: (_, __) => charts.ColorUtil.fromDartColor(kActiveColor),
domainFn: (TimeSeriesCases cases, _) => cases.time,
measureFn: (TimeSeriesCases cases, _) => cases.cases,
data: activeData,
),
new charts.Series<TimeSeriesCases, DateTime>(
id: 'Recovered',
colorFn: (_, __) => charts.ColorUtil.fromDartColor(kRecoveredColor),
domainFn: (TimeSeriesCases cases, _) => cases.time,
measureFn: (TimeSeriesCases cases, _) => cases.cases,
data: recoveredData,
),
new charts.Series<TimeSeriesCases, DateTime>(
id: 'Death',
colorFn: (_, __) => charts.ColorUtil.fromDartColor(kDeathColor),
domainFn: (TimeSeriesCases cases, _) => cases.time,
measureFn: (TimeSeriesCases cases, _) => cases.cases,
data: deathData,
),
];
}
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/screens/global_statistics.dart | import 'package:flutter/material.dart';
import 'package:timeago/timeago.dart' as timeago;
import '../utils/constants.dart';
import '../models/global_summary.dart';
class GlobalStatistics extends StatelessWidget {
final GlobalSummaryModel summary;
GlobalStatistics({@required this.summary});
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
buildCard(
"CONFIRMED",
summary.totalConfirmed,
summary.newConfirmed,
kConfirmedColor
),
buildCard(
"ACTIVE",
summary.totalConfirmed - summary.totalRecovered - summary.totalDeaths,
summary.newConfirmed - summary.newRecovered - summary.newDeaths,
kActiveColor
),
buildCard(
"RECOVERED",
summary.totalRecovered,
summary.newRecovered,
kRecoveredColor
),
buildCard(
"DEATH",
summary.totalDeaths,
summary.newDeaths,
kDeathColor
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 4, vertical: 6),
child: Text(
"Statistics updated " + timeago.format(summary.date),
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 14,
),
),
),
],
);
}
Widget buildCard(String title, int totalCount, int todayCount, Color color){
return Card(
elevation: 1,
child: Container(
height: 100,
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Column(
children: <Widget>[
Text(
title,
style: TextStyle(
color: Colors.grey,
fontWeight: FontWeight.bold,
fontSize: 14,
),
),
Expanded(
child: Container(),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Total",
style: TextStyle(
color: color,
fontWeight: FontWeight.bold,
fontSize: 12,
),
),
Text(
totalCount.toString().replaceAllMapped(reg, mathFunc),
style: TextStyle(
color: color,
fontWeight: FontWeight.bold,
fontSize: 28,
),
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Text(
"Today",
style: TextStyle(
color: color,
fontWeight: FontWeight.bold,
fontSize: 12,
),
),
Text(
todayCount.toString().replaceAllMapped(reg, mathFunc),
style: TextStyle(
color: color,
fontWeight: FontWeight.bold,
fontSize: 28,
),
),
],
),
],
),
],
),
),
);
}
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/screens/global.dart | import 'package:flutter/material.dart';
import '../screens/global_statistics.dart';
import '../screens/global_loading.dart';
import '../services/covid_service.dart';
import '../models/global_summary.dart';
CovidService covidService = CovidService();
class Global extends StatefulWidget {
@override
_GlobalState createState() => _GlobalState();
}
class _GlobalState extends State<Global> {
Future<GlobalSummaryModel> summary;
@override
void initState() {
super.initState();
summary = covidService.getGlobalSummary();
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.symmetric(horizontal: 4, vertical: 6),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Global Cases",
style: TextStyle(
color: Color(0xffC8D5B9),
fontWeight: FontWeight.bold,
fontSize: 14,
),
),
GestureDetector(
onTap: () {
setState(() {
summary = covidService.getGlobalSummary();
});
},
child: Icon(
Icons.refresh,
color: Color(0xffC8D5B9),
),
),
],
),
),
FutureBuilder(
future: summary,
builder: (context, snapshot) {
if (snapshot.hasError)
return Center(child: Text("Error"),);
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return GlobalLoading();
default:
return !snapshot.hasData
? Center(child: Text("Empty"),)
: GlobalStatistics(
summary: snapshot.data,
);
}
},
),
],
),
);
}
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/screens/global_loading.dart | import 'package:flutter/material.dart';
import 'package:shimmer/shimmer.dart';
class GlobalLoading extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
loadingCard(),
loadingCard(),
loadingCard(),
loadingCard(),
loadingLabel(),
],
);
}
Widget loadingCard(){
return Card(
elevation: 1,
child: Container(
height: 100,
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Shimmer.fromColors(
baseColor: Colors.grey[300],
highlightColor: Colors.grey[100],
child: Column(
children: <Widget>[
Container(
width: 100,
height: 20,
color: Colors.white,
),
Expanded(
child: Container(),
),
Container(
width: double.infinity,
height: 15,
color: Colors.white,
),
SizedBox(
height: 5,
),
Container(
width: double.infinity,
height: 30,
color: Colors.white,
),
],
),
),
),
);
}
Widget loadingLabel(){
return Container(
margin: EdgeInsets.symmetric(vertical: 8),
child: Shimmer.fromColors(
baseColor: Colors.blue[300],
highlightColor: Colors.blue[600],
child: Column(
children: <Widget>[
Container(
width: 200,
height: 16,
color: Colors.white,
),
],
),
),
);
}
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/screens/navigation_option.dart | import 'package:flutter/material.dart';
import 'package:covicare_app/utils/constants.dart';
class NavigationOption extends StatelessWidget {
final String title;
final bool selected;
final Function() onSelected;
NavigationOption({@required this.title, @required this.selected, @required this.onSelected});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
onSelected();
},
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
title,
style: TextStyle(
color: selected ? kPrimaryColor : Colors.grey[400],
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
selected
? Column(
children: <Widget>[
SizedBox(
height: 12,
),
Container(
width: 8,
height: 8,
decoration: BoxDecoration(
color: kPrimaryColor,
shape: BoxShape.circle,
),
),
],
)
: Container(),
],
),
);
}
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/screens/chart.dart | import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import '../models/time_series_cases.dart';
class Chart extends StatelessWidget {
final List<charts.Series<TimeSeriesCases, DateTime>> seriesList;
final bool animate;
Chart(this.seriesList, {this.animate});
@override
Widget build(BuildContext context) {
return charts.TimeSeriesChart(
seriesList,
animate: animate,
domainAxis: charts.EndPointsTimeAxisSpec(),
);
}
} | 0 |
mirrored_repositories/Covicare/lib | mirrored_repositories/Covicare/lib/screens/country_loading.dart | import 'package:flutter/material.dart';
import 'package:shimmer/shimmer.dart';
class CountryLoading extends StatelessWidget {
final bool inputTextLoading;
CountryLoading({@required this.inputTextLoading});
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
inputTextLoading ? loadingInputCard() : Container(),
loadingCard(),
loadingCard(),
loadingChartCard(),
],
);
}
Widget loadingCard(){
return Card(
elevation: 1,
child: Container(
height: 100,
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Shimmer.fromColors(
baseColor: Colors.grey[300],
highlightColor: Colors.grey[100],
child: Column(
children: <Widget>[
Container(
width: 100,
height: 20,
color: Colors.white,
),
Expanded(
child: Container(),
),
Container(
width: double.infinity,
height: 15,
color: Colors.white,
),
SizedBox(
height: 5,
),
Container(
width: double.infinity,
height: 30,
color: Colors.white,
),
],
),
),
),
);
}
Widget loadingInputCard(){
return Card(
elevation: 1,
child: Container(
height: 105,
padding: EdgeInsets.all(24),
child: Shimmer.fromColors(
baseColor: Colors.grey[300],
highlightColor: Colors.grey[100],
child: Container(
width: double.infinity,
height: 57,
color: Colors.white,
),
),
),
);
}
Widget loadingChartCard(){
return Card(
elevation: 1,
child: Container(
height: 180,
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Shimmer.fromColors(
baseColor: Colors.grey[300],
highlightColor: Colors.grey[100],
child: Column(
children: <Widget>[
Expanded(
child: Container(
color: Colors.white,
),
),
],
),
),
),
);
}
} | 0 |
mirrored_repositories/LoginResponsive | mirrored_repositories/LoginResponsive/lib/app_colors.dart | import 'package:flutter/material.dart';
class AppColors{
static const Color backColor = Color(0xffF6F6F6);
static const Color mainBlueColor = Color(0xff005BE0);
static const Color blueDarkColor = Color(0xff252B5C);
static const Color textColor = Color(0xff53587A);
static const Color greyColor = Color(0xffAAAAAA);
static const Color whiteColor = Color(0xffFFFFFF);
} | 0 |
mirrored_repositories/LoginResponsive | mirrored_repositories/LoginResponsive/lib/app_styles.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
TextStyle ralewayStyle = GoogleFonts.raleway(
textStyle: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w500,
),
); | 0 |
mirrored_repositories/LoginResponsive | mirrored_repositories/LoginResponsive/lib/login_screen.dart | import 'package:flutter/material.dart';
import 'package:responsive_login/responsive_widget.dart';
import 'app_colors.dart';
import 'app_styles.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width= MediaQuery.of(context).size.width;
return Scaffold(
backgroundColor: AppColors.backColor,
body: SizedBox(
height: height,
width: width,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
ResponsiveWidget.isSmallScreen(context) ? SizedBox() : Expanded(
child: Container(
height: height,
color: AppColors.mainBlueColor,
child: Center(
child: Text('Rayitos' ,
style: ralewayStyle.copyWith(
fontSize: 48.0,
color: AppColors.whiteColor ,
fontWeight: FontWeight.w800
),),
),
)
) ,
//SizedBox(width: width * 0.1) ,
Expanded(
child: Container(
height: height,
margin: EdgeInsets.symmetric(horizontal: ResponsiveWidget.isSmallScreen(context)? height * 0.032 : height * 0.12),
color: AppColors.backColor,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start ,
children: [
SizedBox(height: height * 0.145) ,
RichText(text: TextSpan(
children: [
TextSpan(
// text: 'Vamos a ' ,
style: ralewayStyle.copyWith(
fontSize: 25.0,
color: AppColors.textColor ,
fontWeight: FontWeight.normal,
),
),
TextSpan(
text: 'Iniciar Sesión' ,
style: ralewayStyle.copyWith(
fontSize: 25.0,
color: AppColors.blueDarkColor ,
fontWeight: FontWeight.w800,
),
)
] ))
, SizedBox(height: height * 0.02) ,
Text(
'Ingresa tus datos para continuar',
style: ralewayStyle.copyWith(
fontSize: 18.0,
color: AppColors.textColor ,
fontWeight: FontWeight.w400,
),
),
SizedBox(height: height * 0.064) ,
Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Text('Correo Electronico',
style: ralewayStyle.copyWith(
fontSize: 12.0,
color: AppColors.blueDarkColor,
fontWeight: FontWeight.w700,
),
),
),
const SizedBox(height: 6.0),
Container(
height: 50.0,
width: width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16.0),
color: AppColors.whiteColor,
),
child: TextFormField(
style: ralewayStyle.copyWith(
fontWeight: FontWeight.w400,
color: AppColors.blueDarkColor,
fontSize: 12.0,
),
decoration: InputDecoration(
border: InputBorder.none,
prefixIcon: IconButton(
onPressed: (){},
icon: Icon(Icons.email),
),
contentPadding: const EdgeInsets.only(top: 16.0),
hintText: 'Enter Email',
hintStyle: ralewayStyle.copyWith(
fontWeight: FontWeight.w400,
color: AppColors.blueDarkColor.withOpacity(0.5),
fontSize: 12.0,
),
),
),
),
SizedBox(height: height * 0.014),
Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Text('Password',
style: ralewayStyle.copyWith(
fontSize: 12.0,
color: AppColors.blueDarkColor,
fontWeight: FontWeight.w700,
),
),
),
const SizedBox(height: 6.0),
Container(
height: 50.0,
width: width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16.0),
color: AppColors.whiteColor,
),
child: TextFormField(
style: ralewayStyle.copyWith(
fontWeight: FontWeight.w400,
color: AppColors.blueDarkColor,
fontSize: 12.0,
),
obscureText: true,
decoration: InputDecoration(
border: InputBorder.none,
suffixIcon: IconButton(
onPressed: (){},
icon: Icon(Icons.visibility_off),
),
prefixIcon: IconButton(
onPressed: (){},
icon: Icon(Icons.lock),
),
contentPadding: const EdgeInsets.only(top: 16.0),
hintText: 'Enter Password',
hintStyle: ralewayStyle.copyWith(
fontWeight: FontWeight.w400,
color: AppColors.blueDarkColor.withOpacity(0.5),
fontSize: 12.0,
),
),
),
),
SizedBox(height: height * 0.03),
Align(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: (){},
child: Text('Olvidaste la contraseña ?',
style: ralewayStyle.copyWith(
fontSize: 16.0,
color: AppColors.mainBlueColor,
fontWeight: FontWeight.w700,
),
),
),
),
SizedBox(height: height * 0.05),
Material(
color: Colors.transparent,
child: InkWell(
onTap: (){
print('Ancho $width');
print('Largo $height');
},
borderRadius: BorderRadius.circular(16.0),
child: Ink(
padding: const EdgeInsets.symmetric(horizontal: 70.0, vertical: 18.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16.0),
color: AppColors.mainBlueColor,
),
child: Text('Iniciar Sesión' ,
style: ralewayStyle.copyWith(
fontSize: 16.0,
color: AppColors.whiteColor,
fontWeight: FontWeight.w700,
),),
),
),
)
],
)
)
)
],
),
)
);
}
} | 0 |
mirrored_repositories/LoginResponsive | mirrored_repositories/LoginResponsive/lib/main.dart | import 'package:flutter/material.dart';
import 'package:responsive_login/login_screen.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const LoginScreen(),
);
}
}
| 0 |
mirrored_repositories/LoginResponsive | mirrored_repositories/LoginResponsive/lib/responsive_widget.dart | import 'package:flutter/material.dart';
class ResponsiveWidget extends StatelessWidget {
final Widget largeScreen;
final Widget? mediumScreen;
final Widget? smallScreen;
const ResponsiveWidget({
Key? key,
required this.largeScreen,
this.mediumScreen,
this.smallScreen,
}) : super(key: key);
static bool isSmallScreen(BuildContext context) {
return MediaQuery.of(context).size.width < 600;
}
static bool isLargeScreen(BuildContext context) {
return MediaQuery.of(context).size.width > 1200;
}
static bool isMediumScreen(BuildContext context) {
return MediaQuery.of(context).size.width >= 600 &&
MediaQuery.of(context).size.width <= 1200;
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth > 1200) {
return largeScreen;
} else if (constraints.maxWidth <= 1200 &&
constraints.maxWidth >= 600) {
return mediumScreen ?? largeScreen;
} else {
return smallScreen ?? largeScreen;
}
},
);
}
} | 0 |
mirrored_repositories/LoginResponsive | mirrored_repositories/LoginResponsive/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:responsive_login/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/SpotFinder/spotfinder | mirrored_repositories/SpotFinder/spotfinder/lib/main.dart | import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter UI',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
// Background Image
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/Car Park shot.jpg'),
fit: BoxFit.cover,
),
),
),
// Header and Caption
Align(
alignment: Alignment.bottomLeft,
child: Padding(
padding: EdgeInsets.only(left: 16, bottom: 50),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
'Welcome to 👋🏻',
style: TextStyle(
fontSize: 45,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
Text(
'SpotFinder',
style: TextStyle(
fontSize: 64,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 5),
Text(
'Your hassle-free parking solution, powered by real-time data and intuitive maps.',
style: TextStyle(
fontSize: 15,
color: Colors.white,
),
),
],
),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/SpotFinder/spotfinder | mirrored_repositories/SpotFinder/spotfinder/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:spotfinder/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/airadio | mirrored_repositories/airadio/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:airadio/pages/home_page.dart';
void main() {
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
));
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
fontFamily: GoogleFonts.poppins().fontFamily,
),
debugShowCheckedModeBanner: false,
home: const HomePage(),
);
}
}
| 0 |
mirrored_repositories/airadio/lib | mirrored_repositories/airadio/lib/pages/home_page.dart | // ignore_for_file: prefer_const_constructors, unused_field, prefer_final_fields
import 'package:airadio/model/radio.dart';
import 'package:airadio/utils/ai_util.dart';
import 'package:alan_voice/alan_voice.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:velocity_x/velocity_x.dart';
import 'package:audioplayers/audioplayers.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<MyRadio>? radios;
late MyRadio _selectedRadio;
Color? _selectedColor;
bool _isPlaying = false;
final sugg = [
"Play",
"Stop",
"Play rock music",
"Play 98.3 FM",
"Play next",
"Pause",
"Play previous",
"Play pop music"
];
final AudioPlayer _audioPlayer = AudioPlayer();
@override
void initState() {
super.initState();
setupAlan();
fetchRadios();
_audioPlayer.onPlayerStateChanged.listen((event) {
if (event == PlayerState.PLAYING) {
_isPlaying = true;
} else {
_isPlaying = false;
}
setState(() {});
});
}
setupAlan() {
AlanVoice.addButton(
"6831dd17ee544b57fa41d0b3f1d6660e2e956eca572e1d8b807a3e2338fdd0dc/stage",
buttonAlign: AlanVoice.BUTTON_ALIGN_RIGHT);
AlanVoice.callbacks.add((command) => _handleCommand(command.data));
}
_handleCommand(Map<String, dynamic> response) {
switch (response["command"]) {
case "play":
_playMusic(_selectedRadio.url);
break;
case "play_channel":
final id = response["id"];
//_audioPlayer.pause();
MyRadio newRadio = radios!.firstWhere((element) => element.id == id);
radios!.remove(newRadio);
radios!.insert(0, newRadio);
_playMusic(newRadio.url);
break;
case "stop":
_audioPlayer.stop();
break;
case "next":
final index = _selectedRadio.id;
MyRadio newRadio;
if (index + 1 > radios!.length) {
newRadio = radios!.firstWhere((element) => element.id == 1);
radios!.remove(newRadio);
radios!.insert(0, newRadio);
} else {
newRadio = radios!.firstWhere((element) => element.id == index + 1);
radios!.remove(newRadio);
radios!.insert(0, newRadio);
}
_playMusic(newRadio.url);
break;
case "prev":
final index = _selectedRadio.id;
MyRadio newRadio;
if (index - 1 <= 0) {
newRadio = radios!.firstWhere((element) => element.id == 1);
radios!.remove(newRadio);
radios!.insert(0, newRadio);
} else {
newRadio = radios!.firstWhere((element) => element.id == index - 1);
radios!.remove(newRadio);
radios!.insert(0, newRadio);
}
_playMusic(newRadio.url);
break;
default:
// ignore: avoid_print
print("Command was ${response["command"]}");
break;
}
}
fetchRadios() async {
final radioJson = await rootBundle.loadString("assets/radio.json");
radios = MyRadioList.fromJson(radioJson).radios;
_selectedRadio = radios![0];
_selectedColor = Color(int.parse(_selectedRadio.color));
print(radios);
setState(() {});
}
_playMusic(String url) {
_audioPlayer.play(url);
_selectedRadio = radios!.firstWhere((element) => element.url == url);
print(_selectedRadio.name);
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(
child: Container(
color: _selectedColor ?? AIColors.primaryColor2,
child: radios != null
? [
100.heightBox,
"All Channels".text.xl.white.semiBold.make().px16(),
20.heightBox,
ListView(
padding: Vx.m0,
shrinkWrap: true,
children: radios!
.map((e) => ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(e.icon),
),
title: "${e.name} FM".text.white.make(),
subtitle: e.tagline.text.white.make(),
))
.toList(),
).expand()
].vStack(crossAlignment: CrossAxisAlignment.start)
: const Offstage(),
),
),
body: Stack(
children: [
VxAnimatedBox()
.size(context.screenWidth, context.screenHeight)
.withGradient(
LinearGradient(
colors: [
AIColors.primaryColor2,
_selectedColor ?? AIColors.primaryColor1,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
)
.make(),
[
AppBar(
title: "AI Radio".text.xl4.bold.white.make().shimmer(
primaryColor: Vx.purple300,
secondaryColor: Colors.white,
),
backgroundColor: Colors.transparent,
elevation: 0.0,
//centerTitle: true, // for android only , in ios by default
).h(100.0).p16(),
"Start with - Hey Alan 👇".text.italic.semiBold.white.make(),
10.heightBox,
VxSwiper.builder(
itemCount: sugg.length,
height: 50.0,
viewportFraction: 0.35,
autoPlay: true,
autoPlayAnimationDuration: 3.seconds,
autoPlayCurve: Curves.linear,
enableInfiniteScroll: true,
itemBuilder: (context, index) {
final s = sugg[index];
return Chip(
label: s.text.make(),
backgroundColor: Vx.randomColor,
);
},
)
].vStack(alignment: MainAxisAlignment.start),
30.heightBox,
radios != null
? VxSwiper.builder(
itemCount: radios!.length,
aspectRatio: 1.0,
enlargeCenterPage: true,
onPageChanged: (index) {
_selectedRadio = radios![index];
final colorHex = radios![index].color;
_selectedColor = Color(int.parse(colorHex));
setState(() {});
},
itemBuilder: (context, index) {
final rad = radios![index];
return VxBox(
child: ZStack(
[
Positioned(
top: 0.0,
right: 0.0,
child: VxBox(
child: rad.category.text.uppercase.white
.make()
.px16())
.height(40)
.black
.alignCenter
.withRounded(value: 10.0)
.make(),
),
Align(
alignment: Alignment.bottomCenter,
child: VStack(
[
rad.name.text.xl3.white.bold.make(),
5.heightBox,
rad.tagline.text.sm.white.semiBold.make(),
],
crossAlignment: CrossAxisAlignment.center,
),
),
Align(
alignment: Alignment.center,
child: [
Icon(
CupertinoIcons.play_circle,
color: Colors.white,
),
10.heightBox,
"Double tap to play".text.gray300.make(),
].vStack())
],
))
.clip(Clip.antiAlias)
.bgImage(
DecorationImage(
image: NetworkImage(rad.image),
fit: BoxFit.cover,
colorFilter: ColorFilter.mode(
Colors.black.withOpacity(0.3),
BlendMode.darken),
),
)
.withRounded(value: 60.0)
.border(color: Colors.black, width: 5.0)
.make()
.onInkDoubleTap(() {
_playMusic(rad.url);
}).p16();
},
).centered()
: Center(
child:
CircularProgressIndicator(backgroundColor: Colors.white),
),
Align(
alignment: Alignment.bottomCenter,
child: [
if (_isPlaying)
"Playing Now - ${_selectedRadio.name} FM"
.text
.white
.makeCentered(),
Icon(
_isPlaying
? CupertinoIcons.stop_circle
: CupertinoIcons.play_circle,
color: Colors.white,
size: 50.0)
.onInkTap(() {
if (_isPlaying) {
_audioPlayer.stop();
} else {
_playMusic(_selectedRadio.url);
}
})
].vStack(),
).pOnly(bottom: context.percentHeight * 12),
],
fit: StackFit.expand,
clipBehavior: Clip.antiAlias,
),
);
}
}
| 0 |
mirrored_repositories/airadio/lib | mirrored_repositories/airadio/lib/model/radio.dart | // ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:convert';
import 'package:flutter/foundation.dart';
class MyRadioList {
final List<MyRadio> radios;
MyRadioList({
required this.radios,
});
MyRadioList copyWith({
required List<MyRadio> radios,
}) {
return MyRadioList(
radios: radios,
);
}
Map<String, dynamic> toMap() {
return {
'radios': radios.map((x) => x.toMap()).toList(),
};
}
factory MyRadioList.fromMap(Map<String, dynamic> map) {
// ignore: unnecessary_null_comparison
//if (map == null) return null;
return MyRadioList(
radios: List<MyRadio>.from(map['radios']?.map((x) => MyRadio.fromMap(x))),
);
}
String toJson() => json.encode(toMap());
factory MyRadioList.fromJson(String source) =>
MyRadioList.fromMap(json.decode(source));
@override
String toString() => 'MyRadioList(radios: $radios)';
@override
// ignore: avoid_renaming_method_parameters
bool operator ==(Object o) {
if (identical(this, o)) return true;
return o is MyRadioList && listEquals(o.radios, radios);
}
@override
int get hashCode => radios.hashCode;
}
class MyRadio {
final int id;
final int order;
final String name;
final String tagline;
final String color;
final String desc;
final String url;
final String category;
final String icon;
final String image;
final String lang;
MyRadio({
required this.id,
required this.order,
required this.name,
required this.tagline,
required this.color,
required this.desc,
required this.url,
required this.category,
required this.icon,
required this.image,
required this.lang,
});
MyRadio copyWith({
int? id,
int? order,
String? name,
String? tagline,
String? color,
String? desc,
String? url,
String? category,
String? icon,
String? image,
String? lang,
}) {
return MyRadio(
id: id ?? this.id,
order: order ?? this.order,
name: name ?? this.name,
tagline: tagline ?? this.tagline,
color: color ?? this.color,
desc: desc ?? this.desc,
url: url ?? this.url,
category: category ?? this.category,
icon: icon ?? this.icon,
image: image ?? this.image,
lang: lang ?? this.lang,
);
}
Map<String, dynamic> toMap() {
return <String, dynamic>{
'id': id,
'order': order,
'name': name,
'tagline': tagline,
'color': color,
'desc': desc,
'url': url,
'category': category,
'icon': icon,
'image': image,
'lang': lang,
};
}
factory MyRadio.fromMap(Map<String, dynamic> map) {
return MyRadio(
id: map['id'] as int,
order: map['order'] as int,
name: map['name'] as String,
tagline: map['tagline'] as String,
color: map['color'] as String,
desc: map['desc'] as String,
url: map['url'] as String,
category: map['category'] as String,
icon: map['icon'] as String,
image: map['image'] as String,
lang: map['lang'] as String,
);
}
String toJson() => json.encode(toMap());
factory MyRadio.fromJson(String source) =>
MyRadio.fromMap(json.decode(source) as Map<String, dynamic>);
@override
String toString() {
return 'MyRadio(id: $id, order: $order, name: $name, tagline: $tagline, color: $color, desc: $desc, url: $url, category: $category, icon: $icon, image: $image, lang: $lang)';
}
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is MyRadio &&
other.id == id &&
other.order == order &&
other.name == name &&
other.tagline == tagline &&
other.color == color &&
other.desc == desc &&
other.url == url &&
other.category == category &&
other.icon == icon &&
other.image == image &&
other.lang == lang;
}
@override
int get hashCode {
return id.hashCode ^
order.hashCode ^
name.hashCode ^
tagline.hashCode ^
color.hashCode ^
desc.hashCode ^
url.hashCode ^
category.hashCode ^
icon.hashCode ^
image.hashCode ^
lang.hashCode;
}
}
| 0 |
mirrored_repositories/airadio/lib | mirrored_repositories/airadio/lib/utils/ai_util.dart | import 'package:flutter/material.dart';
import 'package:velocity_x/velocity_x.dart';
mixin AIColors {
static Color primaryColor1 = Vx.orange400;
static Color primaryColor2 = Vx.purple500;
}
| 0 |
mirrored_repositories/airadio | mirrored_repositories/airadio/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:airadio/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/Noted | mirrored_repositories/Noted/lib/main.dart | import 'package:flutter/material.dart';
import 'package:noted/services/sharedPref.dart';
import 'screens/homeScreen.dart';
import 'data/theme.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
// This widget is the root of your application.
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
ThemeData theme = appThemeLight;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: theme,
home: MyHomePage(title: 'Home',),
);
}
} | 0 |
mirrored_repositories/Noted/lib | mirrored_repositories/Noted/lib/components/faderoute.dart | import 'package:flutter/material.dart';
class FadeRoute extends PageRouteBuilder {
final Widget page;
FadeRoute({required this.page})
: super(
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) =>
page,
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
FadeTransition(
opacity: animation,
child: child,
),
);
}
| 0 |
mirrored_repositories/Noted/lib | mirrored_repositories/Noted/lib/components/cards.dart | import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../data/models.dart';
List<Color> colorList = [
Colors.blue,
Colors.green,
Colors.indigo,
Colors.red,
Colors.cyan,
Colors.teal,
Colors.amber.shade900,
Colors.deepOrange
];
class NoteCardComponent extends StatelessWidget {
const NoteCardComponent({
required this.noteData,
required this.onTapAction,
Key? key,
}) : super(key: key);
final NotesModel noteData;
final Function(NotesModel noteData) onTapAction;
@override
Widget build(BuildContext context) {
String neatDate = DateFormat.yMd().add_jm().format(noteData.date);
Color color = colorList.elementAt(noteData.title.length % colorList.length);
return Container(
margin: EdgeInsets.fromLTRB(10, 8, 10, 8),
height: 110,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
boxShadow: [buildBoxShadow(color, context)],
),
child: Material(
borderRadius: BorderRadius.circular(16),
clipBehavior: Clip.antiAlias,
color: Theme.of(context).dialogBackgroundColor,
child: InkWell(
borderRadius: BorderRadius.circular(16),
onTap: () {
onTapAction(noteData);
},
splashColor: color.withAlpha(20),
highlightColor: color.withAlpha(10),
child: Container(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'${noteData.title.trim().length <= 20 ? noteData.title.trim() : noteData.title.trim().substring(0, 20) + '...'}',
style: TextStyle(
fontFamily: 'ZillaSlab',
fontSize: 20,
fontWeight: noteData.isImportant
? FontWeight.w800
: FontWeight.normal),
),
Container(
margin: EdgeInsets.only(top: 8),
child: Text(
'${noteData.content.trim().split('\n').first.length <= 30 ? noteData.content.trim().split('\n').first : noteData.content.trim().split('\n').first.substring(0, 30) + '...'}',
style:
TextStyle(fontSize: 14, color: Colors.grey.shade400),
),
),
Container(
margin: EdgeInsets.only(top: 14),
alignment: Alignment.centerRight,
child: Row(
children: <Widget>[
Icon(Icons.flag,
size: 16,
color: noteData.isImportant
? color
: Colors.transparent),
Spacer(),
Text(
'$neatDate',
textAlign: TextAlign.right,
style: TextStyle(
fontSize: 12,
color: Colors.grey.shade300,
fontWeight: FontWeight.w500),
),
],
),
)
],
),
),
),
));
}
BoxShadow buildBoxShadow(Color color, BuildContext context) {
if (Theme.of(context).brightness == Brightness.dark) {
return BoxShadow(
color: noteData.isImportant == true
? Colors.black.withAlpha(100)
: Colors.black.withAlpha(10),
blurRadius: 8,
offset: Offset(0, 8));
}
return BoxShadow(
color: noteData.isImportant == true
? color.withAlpha(60)
: color.withAlpha(25),
blurRadius: 8,
offset: Offset(0, 8));
}
}
class AddNoteCardComponent extends StatelessWidget {
const AddNoteCardComponent({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.fromLTRB(10, 8, 10, 8),
height: 110,
decoration: BoxDecoration(
border: Border.all(color: Theme.of(context).primaryColor, width: 2),
borderRadius: BorderRadius.circular(16),
),
child: Material(
borderRadius: BorderRadius.circular(16),
clipBehavior: Clip.antiAlias,
child: Container(
padding: EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.add,
color: Theme.of(context).primaryColor,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Add new note',
style: TextStyle(
fontFamily: 'ZillaSlab',
color: Theme.of(context).primaryColor,
fontSize: 20),
))
],
),
)
],
),
),
));
}
}
| 0 |
mirrored_repositories/Noted/lib | mirrored_repositories/Noted/lib/data/theme.dart | import 'package:flutter/material.dart';
Color primaryColor =Color(0xFF3366FF);
Color reallyLightGrey = Colors.grey.withAlpha(25);
ThemeData appThemeLight =
ThemeData.light().copyWith(primaryColor: primaryColor);
ThemeData appThemeDark = ThemeData.dark().copyWith(
primaryColor: Colors.white,
toggleableActiveColor: primaryColor,
accentColor: primaryColor,
buttonColor: primaryColor,
textSelectionColor: primaryColor,
textSelectionHandleColor: primaryColor);
| 0 |
mirrored_repositories/Noted/lib | mirrored_repositories/Noted/lib/data/models.dart | import 'dart:math';
class NotesModel {
late int id;
late String title;
late String content;
late bool isImportant;
late DateTime date;
NotesModel({required this.id,required this.title,required this.content,required this.isImportant,required this.date});
NotesModel.fromMap(Map<dynamic, dynamic> map) {
this.id = map['_id'];
this.title = map['title'];
this.content = map['content'];
this.date = DateTime.parse(map['date']);
this.isImportant = map['isImportant'] == 1 ? true : false;
}
Map<String, dynamic> toMap() {
return <String, dynamic>{
'_id': this.id,
'title': this.title,
'content': this.content,
'isImportant': this.isImportant == true ? 1 : 0,
'date': this.date.toIso8601String()
};
}
NotesModel.random() {
this.id = Random(10).nextInt(1000) + 1;
this.title = 'Lorem Ipsum ' * (Random().nextInt(4) + 1);
this.content = 'Lorem Ipsum ' * (Random().nextInt(4) + 1);
this.isImportant = Random().nextBool();
this.date = DateTime.now().add(Duration(hours: Random().nextInt(100)));
}
}
| 0 |
mirrored_repositories/Noted/lib | mirrored_repositories/Noted/lib/services/database.dart | import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import '../data/models.dart';
class NotesDatabaseService {
late String path;
NotesDatabaseService._();
static NotesDatabaseService db = NotesDatabaseService._();
late Database? _database;
Future<Database> get database async {
if (_database != null) return _database!;
_database = await init();
return _database!;
}
init() async {
String path = await getDatabasesPath();
path = join(path, 'notes.db');
print("Entered path $path");
return await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute(
'CREATE TABLE Notes (_id INTEGER PRIMARY KEY, title TEXT, content TEXT, date TEXT, isImportant INTEGER);');
print('New table created at $path');
});
}
Future<List<NotesModel>> getNotesFromDB() async {
final db =await database;
List<NotesModel> notesList = [];
List<Map> maps = await db.query('Notes',
columns: ['_id', 'title', 'content', 'date', 'isImportant']);
if (maps.length > 0) {
maps.forEach((map) {
notesList.add(NotesModel.fromMap(map));
});
}
return notesList;
}
updateNoteInDB(NotesModel updatedNote) async {
final db = await database;
await db.update('Notes', updatedNote.toMap(),
where: '_id = ?', whereArgs: [updatedNote.id]);
print('Note updated: ${updatedNote.title} ${updatedNote.content}');
}
deleteNoteInDB(NotesModel noteToDelete) async {
final db = await database;
await db.delete('Notes', where: '_id = ?', whereArgs: [noteToDelete.id]);
print('Note deleted');
}
Future<NotesModel> addNoteInDB(NotesModel newNote) async {
final db = await database;
if (newNote.title.trim().isEmpty) newNote.title = 'Untitled Note';
final int id = await db.transaction((transaction) {
return transaction.rawInsert(
'INSERT into Notes(title, content, date, isImportant) VALUES ("${newNote.title}", "${newNote.content}", "${newNote.date.toIso8601String()}", ${newNote.isImportant == true ? 1 : 0});');
});
newNote.id = id;
print('Note added: ${newNote.title} ${newNote.content}');
return newNote;
}
}
| 0 |
mirrored_repositories/Noted/lib | mirrored_repositories/Noted/lib/services/sharedPref.dart | import 'package:shared_preferences/shared_preferences.dart';
Future<String> getThemeFromSharedPref() async {
SharedPreferences sharedPref = await SharedPreferences.getInstance();
return sharedPref.getString('theme')!;
}
void setThemeinSharedPref(String val) async {
SharedPreferences sharedPref = await SharedPreferences.getInstance();
sharedPref.setString('theme', val);
}
| 0 |
mirrored_repositories/Noted/lib | mirrored_repositories/Noted/lib/screens/editNoteScreen.dart | import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/painting.dart' as prefix0;
import 'package:flutter/widgets.dart';
import 'package:noted/data/models.dart';
import 'package:noted/services/database.dart';
class EditNotePage extends StatefulWidget {
late Function() triggerRefetch;
NotesModel? existingNote;
EditNotePage({Key? key,required Function() triggerRefetch,required NotesModel existingNote})
: super(key: key) {
this.triggerRefetch = triggerRefetch;
this.existingNote = existingNote;
}
@override
_EditNotePageState createState() => _EditNotePageState();
}
class _EditNotePageState extends State<EditNotePage> {
bool isDirty = false;
bool isNoteNew = true;
FocusNode titleFocus = FocusNode();
FocusNode contentFocus = FocusNode();
late NotesModel currentNote;
TextEditingController titleController = TextEditingController();
TextEditingController contentController = TextEditingController();
@override
void initState() {
super.initState();
if (widget.existingNote == null) {
currentNote = NotesModel(
id:0 ,content: '', title: '', date: DateTime.now(), isImportant: false);
isNoteNew = true;
} else {
currentNote = widget.existingNote!;
isNoteNew = false;
}
titleController.text = currentNote.title;
contentController.text = currentNote.content;
}
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.only(top: 50),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
const Color(0xFF3366FF),
const Color(0xFF00CCFF),
],
begin: const FractionalOffset(0.0, 0.0),
end: const FractionalOffset(1.0, 0.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp),
),
child: Scaffold(
backgroundColor: Colors.transparent,
body: Stack(
children: <Widget>[
ListView(
children: <Widget>[
Container(
height:50
),
Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
focusNode: titleFocus,
autofocus: true,
controller: titleController,
keyboardType: TextInputType.multiline,
maxLines: null,
onSubmitted: (text) {
titleFocus.unfocus();
FocusScope.of(context).requestFocus(contentFocus);
},
onChanged: (value) {
markTitleAsDirty(value);
},
textInputAction: TextInputAction.next,
style: TextStyle(
fontFamily: 'ZillaSlab',
fontSize: 32,
fontWeight: FontWeight.w700),
decoration: InputDecoration.collapsed(
hintText: 'Enter a title...',
hintStyle: TextStyle(
color: Colors.white,
fontSize: 32,
fontFamily: 'ZillaSlab',
fontWeight: FontWeight.w700),
border: InputBorder.none,
),
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
focusNode: contentFocus,
controller: contentController,
keyboardType: TextInputType.multiline,
maxLines: null,
onChanged: (value) {
markContentAsDirty(value);
},
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
decoration: InputDecoration.collapsed(
hintText: 'Start typing...',
hintStyle: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w500),
border: InputBorder.none,
),
),
)
],
),
ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
child: Container(
height: 80,
color: Theme.of(context).canvasColor.withOpacity(0.3),
child: Container(
child: Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.arrow_back,color: Colors.white,),
onPressed: handleBack,
),
Spacer(),
IconButton(
tooltip: 'Mark note as important',
icon: Icon(currentNote.isImportant
? Icons.beenhere_rounded
: Icons.beenhere_outlined,color: Colors.white,),
onPressed: titleController.text.trim().isNotEmpty &&
contentController.text.trim().isNotEmpty
? markImportantAsDirty
: null,
),
IconButton(
icon: Icon(Icons.delete_outline, color: Colors.white,),
onPressed: () {
handleDelete();
},
),
AnimatedContainer(
margin: EdgeInsets.only(left: 10),
duration: Duration(milliseconds: 200),
width: isDirty ? 100 : 0,
height: 42,
curve: Curves.decelerate,
child: RaisedButton.icon(
color: Theme.of(context).accentColor,
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(100),
bottomLeft: Radius.circular(100))),
icon: Icon(Icons.done),
label: Text(
'SAVE',
style: TextStyle(letterSpacing: 1),
),
onPressed: handleSave,
),
)
],
),
),
)),
)
],
)));
}
void handleSave() async {
setState(() {
currentNote.title = titleController.text;
currentNote.content = contentController.text;
print('Hey there ${currentNote.content}');
});
if (isNoteNew) {
var latestNote = await NotesDatabaseService.db.addNoteInDB(currentNote);
setState(() {
currentNote = latestNote;
});
} else {
await NotesDatabaseService.db.updateNoteInDB(currentNote);
}
setState(() {
isNoteNew = false;
isDirty = false;
});
widget.triggerRefetch();
titleFocus.unfocus();
contentFocus.unfocus();
}
void markTitleAsDirty(String title) {
setState(() {
isDirty = true;
});
}
void markContentAsDirty(String content) {
setState(() {
isDirty = true;
});
}
void markImportantAsDirty() {
setState(() {
currentNote.isImportant = !currentNote.isImportant;
});
handleSave();
}
void handleDelete() async {
if (isNoteNew) {
Navigator.pop(context);
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)),
title: Text('Delete Note'),
content: Text('This note will be deleted permanently'),
actions: <Widget>[
FlatButton(
child: Text('DELETE',
style: prefix0.TextStyle(
color: Colors.red.shade300,
fontWeight: FontWeight.w500,
letterSpacing: 1)),
onPressed: () async {
await NotesDatabaseService.db.deleteNoteInDB(currentNote);
widget.triggerRefetch();
Navigator.pop(context);
Navigator.pop(context);
},
),
FlatButton(
child: Text('CANCEL',
style: TextStyle(
color: Theme.of(context).primaryColor,
fontWeight: FontWeight.w500,
letterSpacing: 1)),
onPressed: () {
Navigator.pop(context);
},
)
],
);
});
}
}
void handleBack() {
Navigator.pop(context);
}
}
| 0 |
mirrored_repositories/Noted/lib | mirrored_repositories/Noted/lib/screens/viewNote.dart | import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';
import 'package:noted/data/models.dart';
import 'package:noted/screens/editNoteScreen.dart';
import 'package:noted/services/database.dart';
import 'package:share/share.dart';
class ViewNotePage extends StatefulWidget {
late Function() triggerRefetch;
late NotesModel currentNote;
ViewNotePage({Key? key, Function()? triggerRefetch, NotesModel? currentNote})
: super(key: key) {
this.triggerRefetch = triggerRefetch!;
this.currentNote = currentNote!;
}
@override
_ViewNotePageState createState() => _ViewNotePageState();
}
class _ViewNotePageState extends State<ViewNotePage> {
@override
void initState() {
super.initState();
showHeader();
}
void showHeader() async {
Future.delayed(Duration(milliseconds: 100), () {
setState(() {
headerShouldShow = true;
});
});
}
bool headerShouldShow = false;
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.only(top: 50),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
const Color(0xFF3366FF),
const Color(0xFF00CCFF),
],
begin: const FractionalOffset(0.0, 0.0),
end: const FractionalOffset(1.0, 0.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp),
),
child: Scaffold(
backgroundColor: Colors.transparent,
body: Stack(
children: <Widget>[
ListView(
physics: BouncingScrollPhysics(),
children: <Widget>[
Container(
height: 40,
),
Padding(
padding: const EdgeInsets.only(
left: 24.0, right: 24.0, top: 40.0, bottom: 16),
child: AnimatedOpacity(
opacity: headerShouldShow ? 1 : 0,
duration: Duration(milliseconds: 200),
curve: Curves.easeIn,
child: Text(
widget.currentNote.title,
style: TextStyle(
color: Colors.white,
fontFamily: 'ZillaSlab',
fontWeight: FontWeight.w700,
fontSize: 36,
),
overflow: TextOverflow.visible,
softWrap: true,
),
),
),
AnimatedOpacity(
duration: Duration(milliseconds: 500),
opacity: headerShouldShow ? 1 : 0,
child: Padding(
padding: const EdgeInsets.only(left: 24),
child: Text(
DateFormat.yMd().add_jm().format(widget.currentNote.date),
style: TextStyle(
fontWeight: FontWeight.w500, color: Colors.white),
),
),
),
Padding(
padding: const EdgeInsets.only(
left: 24.0, top: 36, bottom: 24, right: 24),
child: Text(
widget.currentNote.content,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
),
)
],
),
ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
child: Container(
height: 80,
color: Theme.of(context).canvasColor.withOpacity(0.3),
child: Container(
child: Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.arrow_back),
onPressed: handleBack,
),
Spacer(),
IconButton(
icon: Icon(widget.currentNote.isImportant
? Icons.beenhere_rounded
: Icons.beenhere_outlined),
onPressed: () {
markImportantAsDirty();
},
),
IconButton(
icon: Icon(Icons.delete_outline),
onPressed: handleDelete,
),
IconButton(
icon: Icon(Icons.share),
onPressed: handleShare,
),
IconButton(
icon: Icon(Icons.edit),
onPressed: handleEdit,
),
],
),
),
)),
)
],
)));
}
void handleSave() async {
await NotesDatabaseService.db.updateNoteInDB(widget.currentNote);
widget.triggerRefetch();
}
void markImportantAsDirty() {
setState(() {
widget.currentNote.isImportant = !widget.currentNote.isImportant;
});
handleSave();
}
void handleEdit() {
Navigator.pop(context);
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) => EditNotePage(
existingNote: widget.currentNote,
triggerRefetch: widget.triggerRefetch,
)));
}
void handleShare() {
Share.share(
'${widget.currentNote.title.trim()}\n(On: ${widget.currentNote.date.toIso8601String().substring(0, 10)})\n\n${widget.currentNote.content}');
}
void handleBack() {
Navigator.pop(context);
}
void handleDelete() async {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
title: Text('Delete Note'),
content: Text('This note will be deleted permanently'),
actions: <Widget>[
FlatButton(
child: Text('DELETE',
style: TextStyle(
color: Colors.red.shade300,
fontWeight: FontWeight.w500,
letterSpacing: 1)),
onPressed: () async {
await NotesDatabaseService.db
.deleteNoteInDB(widget.currentNote);
widget.triggerRefetch();
Navigator.pop(context);
Navigator.pop(context);
},
),
FlatButton(
child: Text('CANCEL',
style: TextStyle(
color: Theme.of(context).primaryColor,
fontWeight: FontWeight.w500,
letterSpacing: 1)),
onPressed: () {
Navigator.pop(context);
},
)
],
);
});
}
}
| 0 |
mirrored_repositories/Noted/lib | mirrored_repositories/Noted/lib/screens/homeScreen.dart | import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:noted/components/faderoute.dart';
import 'package:noted/data/models.dart';
import 'package:noted/screens/editNoteScreen.dart';
import 'package:noted/screens/viewNote.dart';
import 'package:noted/services/database.dart';
import '../components/cards.dart';
class MyHomePage extends StatefulWidget {
MyHomePage(
{Key? key,
required this.title,
} );
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool isFlagOn = false;
bool headerShouldHide = false;
List<NotesModel> notesList = [];
TextEditingController searchController = TextEditingController();
bool isSearchEmpty = true;
@override
void initState() {
super.initState();
NotesDatabaseService.db.init();
setNotesFromDB();
}
setNotesFromDB() async {
print("Entered setNotes");
var fetchedNotes = await NotesDatabaseService.db.getNotesFromDB();
setState(() {
notesList = fetchedNotes;
});
}
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.only(top: 50),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
const Color(0xFF3366FF),
const Color(0xFF00CCFF),
],
begin: const FractionalOffset(0.0, 0.0),
end: const FractionalOffset(1.0, 0.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp),
),
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
elevation: 0,
title: Text(
'Noted !',
style: TextStyle(fontSize: 50, fontFamily: ''),
),
),
floatingActionButton: FloatingActionButton.extended(
backgroundColor: Theme.of(context).primaryColor,
elevation: 20,
onPressed: () {
gotoEditNote();
},
label: Text('Add note'.toUpperCase()),
icon: Icon(Icons.add),
),
body: GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
child: AnimatedContainer(
duration: Duration(milliseconds: 200),
child: ListView(
physics: BouncingScrollPhysics(),
children: <Widget>[
buildButtonRow(),
buildImportantIndicatorText(),
Container(height: 32),
...buildNoteComponentsList(),
GestureDetector(
onTap: gotoEditNote, child: AddNoteCardComponent()),
Container(height: 100)
],
),
margin: EdgeInsets.only(top: 2),
),
),
),
);
}
Widget buildButtonRow() {
return Padding(
padding: const EdgeInsets.only(top: 30, left: 10, right: 10),
child: Row(
children: <Widget>[
GestureDetector(
onTap: () {
setState(() {
isFlagOn = !isFlagOn;
});
},
child: AnimatedContainer(
duration: Duration(milliseconds: 160),
height: 50,
width: 50,
curve: Curves.slowMiddle,
child: Icon(
isFlagOn ? Icons.beenhere_outlined : Icons.beenhere_rounded,
color: isFlagOn ? Colors.white : Colors.white,
),
decoration: BoxDecoration(
color: isFlagOn ? Colors.white : Colors.transparent,
border: Border.all(
width: isFlagOn ? 2 : 1,
color: isFlagOn ? Colors.white : Colors.white,
),
borderRadius: BorderRadius.all(Radius.circular(16))),
),
),
Expanded(
child: Container(
alignment: Alignment.center,
margin: EdgeInsets.only(left: 8),
padding: EdgeInsets.only(left: 16),
height: 50,
decoration: BoxDecoration(
border: Border.all(color: Colors.white),
borderRadius: BorderRadius.all(Radius.circular(16))),
child: Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: TextField(
controller: searchController,
maxLines: 1,
onChanged: (value) {
handleSearch(value);
},
autofocus: false,
keyboardType: TextInputType.text,
style:
TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
textInputAction: TextInputAction.search,
decoration: InputDecoration.collapsed(
hintText: 'Search',
hintStyle: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w500),
border: InputBorder.none,
),
),
),
IconButton(
icon: Icon(isSearchEmpty ? Icons.search : Icons.cancel,
color: Colors.white),
onPressed: cancelSearch,
),
],
),
),
)
],
),
);
}
Widget testListItem(Color color) {
return new NoteCardComponent(
onTapAction: (_) {},
noteData: NotesModel.random(),
);
}
Widget buildImportantIndicatorText() {
return AnimatedCrossFade(
duration: Duration(milliseconds: 200),
firstChild: Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
'Only showing notes marked important'.toUpperCase(),
style: TextStyle(
fontSize: 12, color: Colors.blue, fontWeight: FontWeight.w500),
),
),
secondChild: Container(
height: 2,
),
crossFadeState:
isFlagOn ? CrossFadeState.showFirst : CrossFadeState.showSecond,
);
}
List<Widget> buildNoteComponentsList() {
List<Widget> noteComponentsList = [];
notesList.sort((a, b) {
return b.date.compareTo(a.date);
});
if (searchController.text.isNotEmpty) {
notesList.forEach((note) {
if (note.title
.toLowerCase()
.contains(searchController.text.toLowerCase()) ||
note.content
.toLowerCase()
.contains(searchController.text.toLowerCase()))
noteComponentsList.add(NoteCardComponent(
noteData: note,
onTapAction: openNoteToRead,
));
});
return noteComponentsList;
}
if (isFlagOn) {
notesList.forEach((note) {
if (note.isImportant)
noteComponentsList.add(NoteCardComponent(
noteData: note,
onTapAction: openNoteToRead,
));
});
} else {
notesList.forEach((note) {
noteComponentsList.add(NoteCardComponent(
noteData: note,
onTapAction: openNoteToRead,
));
});
}
return noteComponentsList;
}
void handleSearch(String value) {
if (value.isNotEmpty) {
setState(() {
isSearchEmpty = false;
});
} else {
setState(() {
isSearchEmpty = true;
});
}
}
void gotoEditNote() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EditNotePage(
triggerRefetch: refetchNotesFromDB,
existingNote: NotesModel(
id: 0,
title: '',
content: '',
isImportant: false,
date: DateTime.now()),
)));
}
void refetchNotesFromDB() async {
await setNotesFromDB();
print("Refetched notes");
}
openNoteToRead(NotesModel noteData) async {
setState(() {
headerShouldHide = true;
});
await Future.delayed(Duration(milliseconds: 230), () {});
Navigator.push(
context,
FadeRoute(
page: ViewNotePage(
triggerRefetch: refetchNotesFromDB, currentNote: noteData)));
await Future.delayed(Duration(milliseconds: 300), () {});
setState(() {
headerShouldHide = false;
});
}
void cancelSearch() {
FocusScope.of(context).requestFocus(new FocusNode());
setState(() {
searchController.clear();
isSearchEmpty = true;
});
}
}
| 0 |
mirrored_repositories/Noted/lib | mirrored_repositories/Noted/lib/screens/changeTheme.dart | // import 'package:flutter/cupertino.dart';
// import 'package:flutter/gestures.dart';
// import 'package:flutter/material.dart';
// import 'package:flutter/painting.dart';
// import 'package:flutter/widgets.dart';
// import 'package:noted/services/sharedPref.dart';
// import 'package:url_launcher/url_launcher.dart';
// class SettingsPage extends StatefulWidget {
// late Function(Brightness brightness)? changeTheme;
// SettingsPage({Key? key, Function(Brightness brightness)? changeTheme})
// : super(key: key) {
// this.changeTheme = changeTheme!;
// }
// @override
// _SettingsPageState createState() => _SettingsPageState();
// }
// class _SettingsPageState extends State<SettingsPage> {
// late String selectedTheme;
// @override
// Widget build(BuildContext context) {
// setState(() {
// if (Theme.of(context).brightness == Brightness.dark) {
// selectedTheme = 'dark';
// } else {
// selectedTheme = 'light';
// }
// });
// return Scaffold(
// body: ListView(
// physics: BouncingScrollPhysics(),
// children: <Widget>[
// Container(
// child: Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: <Widget>[
// GestureDetector(
// behavior: HitTestBehavior.opaque,
// onTap: () {
// Navigator.pop(context);
// },
// child: Container(
// padding:
// const EdgeInsets.only(top: 24, left: 24, right: 24),
// child: Icon(Icons.arrow_back)),
// ),
// Padding(
// padding: const EdgeInsets.only(left: 16, top: 36, right: 24),
// child: buildHeaderWidget(context),
// ),
// buildCardWidget(Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: <Widget>[
// Text('App Theme',
// style: TextStyle(fontFamily: 'ZillaSlab', fontSize: 24)),
// Container(
// height: 20,
// ),
// Row(
// children: <Widget>[
// Radio(
// value: 'light',
// groupValue: selectedTheme,
// onChanged: handleThemeSelection,
// ),
// Text(
// 'Light theme',
// style: TextStyle(fontSize: 18),
// )
// ],
// ),
// Row(
// children: <Widget>[
// Radio(
// value: 'dark',
// groupValue: selectedTheme,
// onChanged: handleThemeSelection,
// ),
// Text(
// 'Dark theme',
// style: TextStyle(fontSize: 18),
// )
// ],
// ),
// ],
// )),
// buildCardWidget(Column(
// crossAxisAlignment: CrossAxisAlignment.stretch,
// children: <Widget>[
// Text('About app',
// style: TextStyle(
// fontFamily: 'ZillaSlab',
// fontSize: 24,
// color: Theme.of(context).primaryColor)),
// Container(
// height: 40,
// ),
// Center(
// child: Text('Developed by'.toUpperCase(),
// style: TextStyle(
// color: Colors.grey.shade600,
// fontWeight: FontWeight.w500,
// letterSpacing: 1)),
// ),
// Center(
// child: Padding(
// padding: const EdgeInsets.only(top: 8.0, bottom: 4.0),
// child: Text(
// 'Roshan',
// style: TextStyle(fontFamily: 'ZillaSlab', fontSize: 24),
// ),
// )),
// Container(
// alignment: Alignment.center,
// child: OutlineButton.icon(
// icon: Icon(OMIcons.link),
// label: Text('GITHUB',
// style: TextStyle(
// fontWeight: FontWeight.w500,
// letterSpacing: 1,
// color: Colors.grey.shade500)),
// shape: RoundedRectangleBorder(
// borderRadius: BorderRadius.circular(16)),
// onPressed: openGitHub,
// ),
// ),
// Container(
// height: 30,
// ),
// Center(
// child: Text('Made With'.toUpperCase(),
// style: TextStyle(
// color: Colors.grey.shade600,
// fontWeight: FontWeight.w500,
// letterSpacing: 1)),
// ),
// Padding(
// padding: const EdgeInsets.all(8.0),
// child: Center(
// child: Row(
// mainAxisAlignment: MainAxisAlignment.center,
// children: <Widget>[
// FlutterLogo(
// size: 40,
// ),
// Padding(
// padding: const EdgeInsets.all(8.0),
// child: Text(
// 'Flutter',
// style: TextStyle(
// fontFamily: 'ZillaSlab', fontSize: 24),
// ),
// )
// ],
// ),
// ),
// ),
// ],
// ))
// ],
// ))
// ],
// ),
// );
// }
// Widget buildCardWidget(Widget child) {
// return Container(
// decoration: BoxDecoration(
// color: Theme.of(context).dialogBackgroundColor,
// borderRadius: BorderRadius.circular(16),
// boxShadow: [
// BoxShadow(
// offset: Offset(0, 8),
// color: Colors.black.withAlpha(20),
// blurRadius: 16)
// ]),
// margin: EdgeInsets.all(24),
// padding: EdgeInsets.all(16),
// child: child,
// );
// }
// Widget buildHeaderWidget(BuildContext context) {
// return Container(
// margin: EdgeInsets.only(top: 8, bottom: 16, left: 8),
// child: Text(
// 'Settings',
// style: TextStyle(
// fontFamily: 'ZillaSlab',
// fontWeight: FontWeight.w700,
// fontSize: 36,
// color: Theme.of(context).primaryColor),
// ),
// );
// }
// void handleThemeSelection(String value) {
// setState(() {
// selectedTheme = value;
// });
// if (value == 'light') {
// widget.changeTheme(Brightness.light);
// } else {
// widget.changeTheme(Brightness.dark);
// }
// setThemeinSharedPref(value);
// }
// void openGitHub() {
// launch('https://www.github.com/roshanrahman');
// }
// }
| 0 |
mirrored_repositories/Noted | mirrored_repositories/Noted/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:noted/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/Movies | mirrored_repositories/Movies/lib/firebase_options.dart | // File generated by FlutterFire CLI.
// ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
import 'package:flutter/foundation.dart'
show defaultTargetPlatform, kIsWeb, TargetPlatform;
/// Default [FirebaseOptions] for use with your Firebase apps.
///
/// Example:
/// ```dart
/// import 'firebase_options.dart';
/// // ...
/// await Firebase.initializeApp(
/// options: DefaultFirebaseOptions.currentPlatform,
/// );
/// ```
class DefaultFirebaseOptions {
static FirebaseOptions get currentPlatform {
if (kIsWeb) {
return web;
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return android;
case TargetPlatform.iOS:
return ios;
case TargetPlatform.macOS:
return macos;
case TargetPlatform.windows:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for windows - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.linux:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for linux - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
default:
throw UnsupportedError(
'DefaultFirebaseOptions are not supported for this platform.',
);
}
}
static const FirebaseOptions web = FirebaseOptions(
apiKey: 'AIzaSyC-5ApV4kcA90HUCsdSxKCp7xGXepEZxLg',
appId: '1:832894186541:web:ac8de28c48f13f551fb4a4',
messagingSenderId: '832894186541',
projectId: 'my-movies-app-e8e75',
authDomain: 'my-movies-app-e8e75.firebaseapp.com',
storageBucket: 'my-movies-app-e8e75.appspot.com',
measurementId: 'G-WSS6HN66X0',
);
static const FirebaseOptions android = FirebaseOptions(
apiKey: 'AIzaSyBPC0onrswd6eAkGl1fEk22pRiiu2jNJl4',
appId: '1:832894186541:android:21f92acccd93733e1fb4a4',
messagingSenderId: '832894186541',
projectId: 'my-movies-app-e8e75',
storageBucket: 'my-movies-app-e8e75.appspot.com',
);
static const FirebaseOptions ios = FirebaseOptions(
apiKey: 'AIzaSyA0QsHkff2nGwv-tPTTl5zzdXPQ6N0_DVs',
appId: '1:832894186541:ios:1558bffd06a329c21fb4a4',
messagingSenderId: '832894186541',
projectId: 'my-movies-app-e8e75',
storageBucket: 'my-movies-app-e8e75.appspot.com',
iosClientId: '832894186541-s8igqah3vn5orppsrpp5j5jgsbieeeu9.apps.googleusercontent.com',
iosBundleId: 'com.example.movies',
);
static const FirebaseOptions macos = FirebaseOptions(
apiKey: 'AIzaSyA0QsHkff2nGwv-tPTTl5zzdXPQ6N0_DVs',
appId: '1:832894186541:ios:8ea6e83d08d5fc321fb4a4',
messagingSenderId: '832894186541',
projectId: 'my-movies-app-e8e75',
storageBucket: 'my-movies-app-e8e75.appspot.com',
iosClientId: '832894186541-1kkv1k5itcel8ehj6n2s6tfksq7uqi3n.apps.googleusercontent.com',
iosBundleId: 'com.example.movies.RunnerTests',
);
}
| 0 |
mirrored_repositories/Movies | mirrored_repositories/Movies/lib/main.dart |
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:go_router/go_router.dart';
import 'package:mymoviesapp/Core/Providers/AppConfigProvieder.dart';
import 'package:mymoviesapp/Core/Providers/DataProvider.dart';
import 'package:mymoviesapp/Core/Theme/Theme.dart';
import 'package:mymoviesapp/Domain/Models/User/User.dart';
import 'package:mymoviesapp/Presentation/Home/HomeScreenView.dart';
import 'package:dcdg/dcdg.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Browse/BrowseTabView.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/EditProfileScreen/EditProfileView.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Home/HomeTabView.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/MovieDetails/MovieDetailsView.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Profile/ProfileTabVIew.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Search/SearchTabView.dart';
import 'package:mymoviesapp/Presentation/Intro/IntroScreenView.dart';
import 'package:mymoviesapp/Presentation/Login/LoginView.dart';
import 'package:mymoviesapp/Presentation/Registration/RegistrationView.dart';
import 'package:mymoviesapp/Presentation/ResetPassword/ResetPasswordView.dart';
import 'package:mymoviesapp/Presentation/Welcome/WelcomeScreen.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'firebase_options.dart';
void main() async {
WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
WidgetsFlutterBinding.ensureInitialized();
// Obtain shared preferences.
final SharedPreferences prefs = await SharedPreferences.getInstance();
var uid = prefs.getString('uid');
var isFirstTime = prefs.getBool('introDone');
uid??= '';
isFirstTime??=false;
print(uid);
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(MyApp(uid: uid,isFirstTime: isFirstTime,));
FlutterNativeSplash.remove();
}
final rootNavigatorKey = GlobalKey<NavigatorState>();
final shellNavigatorKey = GlobalKey<NavigatorState>();
class MyApp extends StatelessWidget {
String uid;
bool isFirstTime;
MyApp({required this.uid , required this.isFirstTime});
late var router = GoRouter(
initialLocation: getInitialLocation(),
navigatorKey: rootNavigatorKey,
routes: [
GoRoute(
path: WelcomeScreen.path,
name: WelcomeScreen.routeName,
builder: (context, state) => WelcomeScreen(),
),
GoRoute(
path: IntroScreenView.path,
name: IntroScreenView.routeName,
builder: (context, state) => IntroScreenView(),
),
GoRoute(
path: LoginScreen.path,
name: LoginScreen.routeName,
builder: (context, state) => LoginScreen(),
),
GoRoute(
path: RegistrationScreen.path,
name: RegistrationScreen.routeName,
builder: (context, state) => RegistrationScreen(),
),
GoRoute(
path: ResetPasswordView.path,
name: ResetPasswordView.routeName,
builder: (context, state) => ResetPasswordView(),
),
GoRoute(
path: EditProfileView.path,
name: EditProfileView.routeName,
builder: (context, state) => EditProfileView(
user: state.extra as Users,
),
),
ShellRoute(
builder: (context, state, child) => HomeScreen(tab: child),
routes: [
GoRoute(
path: HomeTabView.path,
name: HomeTabView.routeName,
builder: (context, state) => HomeTabView(),
),
GoRoute(
path: SearchTabView.path,
name: SearchTabView.routeName,
builder: (context, state) => SearchTabView(),
),
GoRoute(
path: BrowseTabView.path,
name: BrowseTabView.routeName,
builder: (context, state) => BrowseTabView(),
),
GoRoute(
path: ProfileTabView.path,
name: ProfileTabView.routeName,
builder: (context, state) => ProfileTabView(),
),
GoRoute(
path: MovieDetailsScreen.path,
name: MovieDetailsScreen.routeName,
builder: (context, state) => MovieDetailsScreen(
movieId: state.extra as num,
),
),
]),
]);
String getInitialLocation(){
if(!isFirstTime){
return IntroScreenView.path;
}
return uid.isEmpty ? WelcomeScreen.path: HomeTabView.path;
}
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => DataProvider()),
ChangeNotifierProvider(create: (context) => AppConfigProvider())
],
child: MaterialApp.router(
debugShowCheckedModeBanner: false,
routerConfig: router,
theme: MyTheme.theme,
),
);
}
}
| 0 |
mirrored_repositories/Movies/lib/Presentation | mirrored_repositories/Movies/lib/Presentation/Registration/RegistrationView.dart | import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Core/DI/di.dart';
import 'package:mymoviesapp/Core/Providers/AppConfigProvieder.dart';
import 'package:mymoviesapp/Core/Theme/Theme.dart';
import 'package:mymoviesapp/Core/utils/DialogUtils.dart';
import 'package:mymoviesapp/Domain/UseCase/signupUseCase.dart';
import 'package:mymoviesapp/Presentation/Global%20Widgets/MyBottomSheet.dart';
import 'package:mymoviesapp/Presentation/Global%20Widgets/MyTextFileds.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Home/HomeTabView.dart';
import 'package:mymoviesapp/Presentation/Login/LoginView.dart';
import 'package:mymoviesapp/Presentation/Registration/RegistrationViewModel.dart';
import 'package:provider/provider.dart';
class RegistrationScreen extends StatefulWidget {
static const String routeName = "registration";
static const String path = "/registration";
@override
State<RegistrationScreen> createState() => _RegistrationScreenState();
}
class _RegistrationScreenState extends State<RegistrationScreen> {
RegistrationViewModel viewModel =
RegistrationViewModel(SignupUseCase(injectUserRepository()));
@override
void initState() {
super.initState();
viewModel.provider = Provider.of<AppConfigProvider>(context, listen: false);
}
@override
void dispose() {
super.dispose();
viewModel.provider = null;
}
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => viewModel,
child: BlocConsumer<RegistrationViewModel, BaseCubitState>(
listener: (context, state) {
if (state is ShowModalBottomSheetAction) {
showMyModalBottomSheet(context);
} else if (state is HideDialog) {
MyDialogUtils.hideDialog(context);
} else if (state is ShowLoadingState) {
MyDialogUtils.showLoadingDialog(context, state.message);
} else if (state is ShowSuccessMessageState) {
MyDialogUtils.showSuccessMessage(
context: context,
message: state.message,
posActionTitle: "Ok",
posAction: viewModel.goToHomeScreen);
} else if (state is ShowErrorMessageState) {
MyDialogUtils.showFailMessage(
context: context,
message: state.message,
posActionTitle: "Try Again");
}else if (state is GoToHomeScreenAction) {
GoRouter.of(context).goNamed(HomeTabView.routeName);
} else if (state is GoToLoginScreenAction) {
GoRouter.of(context).goNamed(LoginScreen.routeName);
} else if (state is InputWaiting) {
context.pop();
}
},
builder: (context, state) => Scaffold(
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 30.0),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Create ",
style: Theme.of(context).textTheme.displayLarge,
),
Image.asset(
"assets/images/Logo.png",
height: 30,
),
Text(
" Account",
style: Theme.of(context).textTheme.displayLarge,
),
],
),
Stack(children: [
Image.asset(
viewModel.image,
width: 150,
),
Positioned(
top: 10,
right: 10,
child: InkWell(
borderRadius: BorderRadius.circular(100),
onTap: viewModel.showModalBottomSheetState,
child: CircleAvatar(
backgroundColor: MyTheme.gold,
child: Icon(
Icons.edit,
color: MyTheme.white,
)),
),
),
]),
Form(
key: viewModel.formKey,
child: Column(
children: [
const SizedBox(
height: 20,
),
MyTextFormField(
"Name",
EvaIcons.person,
viewModel.nameValidation,
viewModel.name,
TextInputType.name),
MyTextFormField(
"Email",
EvaIcons.email,
viewModel.emailValidation,
viewModel.email,
TextInputType.emailAddress),
MyPasswordTextFormField(
"Password",
EvaIcons.lock,
viewModel.passwordValidation,
viewModel.password,
TextInputType.visiblePassword),
MyPasswordTextFormField(
"Re-Password",
EvaIcons.lock,
viewModel.passwordValidation,
viewModel.passwordConfirmation,
TextInputType.visiblePassword),
MyTextFormField(
"Phone Number",
EvaIcons.phone,
viewModel.phoneValidation,
viewModel.phone,
TextInputType.phone),
Container(
width: double.infinity,
margin: const EdgeInsets.all(20),
child: ElevatedButton(
onPressed: viewModel.register,
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(
MyTheme.gold),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
))),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
"Create Account",
style: Theme.of(context)
.textTheme
.displaySmall!
.copyWith(
fontWeight: FontWeight.bold),
),
)),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Already Have Account ?",
style: Theme.of(context).textTheme.displaySmall,
),
TextButton(
onPressed: viewModel.goToLoginScreen,
style: ButtonStyle(
overlayColor: MaterialStateProperty.all(Colors.transparent),
),
child: Text(
"Login",
style: Theme.of(context)
.textTheme
.displaySmall!
.copyWith(
fontWeight: FontWeight.bold),
))
],
)
],
))
],
),
),
),
),
),
);
}
Future<void> showMyModalBottomSheet(BuildContext context) async {
showModalBottomSheet(
context: context,
backgroundColor: Colors.transparent,
isScrollControlled: true,
builder: (context) => Wrap(
children: [
ModalSheetWidget(
viewModel.images, viewModel.image, viewModel.changeSelectedImage),
],
),
);
}
} | 0 |
mirrored_repositories/Movies/lib/Presentation | mirrored_repositories/Movies/lib/Presentation/Registration/RegistrationViewModel.dart | import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Core/Providers/AppConfigProvieder.dart';
import 'package:mymoviesapp/Domain/Exceptions/FirebaseAuthException.dart';
import 'package:mymoviesapp/Domain/Exceptions/FirebaseDatabaseExeption.dart';
import 'package:mymoviesapp/Domain/Exceptions/FirebaseTimeoutException.dart';
import 'package:mymoviesapp/Domain/UseCase/signupUseCase.dart';
class RegistrationViewModel extends Cubit<BaseCubitState>{
SignupUseCase useCase;
RegistrationViewModel(this.useCase):super(InputWaiting());
AppConfigProvider? provider ;
final formKey = GlobalKey<FormState>();
TextEditingController name = TextEditingController();
TextEditingController email = TextEditingController();
TextEditingController password = TextEditingController();
TextEditingController passwordConfirmation = TextEditingController();
TextEditingController phone = TextEditingController();
List<String> images = [
"assets/images/avatar1.png",
"assets/images/avatar2.png",
"assets/images/avatar3.png",
"assets/images/avatar4.png",
"assets/images/avatar5.png",
"assets/images/avatar6.png",
"assets/images/avatar7.png",
"assets/images/avatar8.png",
"assets/images/avatar9.png",
];
String image = "assets/images/avatar1.png";
void showModalBottomSheetState(){
emit(ShowModalBottomSheetAction());
}
void changeSelectedImage(String image){
this.image = image;
emit(InputWaiting());
}
// validate on the name if it is not empty and doesn't contain ant spacial characters
String? nameValidation(String name){
if (name.isEmpty){
return "Name Can't be Empty";
}else if (RegExp(r'[!@#<>?":_`~;[\]\\|=+)(*&^%-]').hasMatch(name)){
return "Invalid Name";
}else {
return null;
}
}
// validate on the email form
String? emailValidation(String input) {
if (input.isEmpty) {
return "The Email Can't Be Empty";
} else if (!RegExp(r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+"
r"@[a-zA-Z0-9](?:[a-zA-Z0-9-]"
r"{0,253}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]"
r"{0,253}[a-zA-Z0-9])?)*$")
.hasMatch(input)) {
return "Please Enter A Valid Email";
}
return null;
}
// validate the password is not less than 8 chars
String? passwordValidation(String input) {
if (input.isEmpty) {
return "The Password Can't Be Empty";
} else if (input.length < 8) {
return "The Password Must be More Than 8 Characters";
}
return null;
}
// validate on phone number
String? phoneValidation(String input) {
if (input.isEmpty) {
return "Please Enter a Phone Number";
} else if (!RegExp(
r'^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$')
.hasMatch(input)) {
return "Please Enter a Valid Phone Number";
}
return null;
}
// registration to validate and send the data to data base
void register()async{
if(password.text == passwordConfirmation.text){
if(formKey.currentState!.validate()){
emit(ShowLoadingState("Creating Your Account"));
try {
var response = await useCase.invoke(
name: name.text,
email: email.text,
password: password.text,
image: image,
phone: phone.text);
emit(HideDialog());
emit(ShowSuccessMessageState("Account Created Successfully"));
provider!.updateUid(response);
}catch (e){
emit(HideDialog());
if(e is FirebaseAuthDataSourceException){
emit(ShowErrorMessageState(e.errorMessage));
}else if (e is FirebaseTimeoutException){
emit(ShowErrorMessageState(e.error));
} else {
emit(ShowErrorMessageState(e.toString()));
}
}
}
}else{
emit(HideDialog());
emit(ShowErrorMessageState("Passwords Doesn't Match"));
}
}
void goToHomeScreen(){
emit(GoToHomeScreenAction());
}
void goToLoginScreen(){
emit(GoToLoginScreenAction());
}
}
class InputWaiting extends BaseCubitState{}
class GoToHomeScreenAction extends BaseCubitState{}
class GoToLoginScreenAction extends BaseCubitState{}
class ShowModalBottomSheetAction extends BaseCubitState{}
| 0 |
mirrored_repositories/Movies/lib/Presentation | mirrored_repositories/Movies/lib/Presentation/Global Widgets/MyBottomSheet.dart | // the widget in the bottom sheet
import 'package:flutter/material.dart';
import 'package:mymoviesapp/Core/Theme/Theme.dart';
class ModalSheetWidget extends StatefulWidget {
ModalSheetWidget(this.images, this.selectedImage, this.changeSelectedImage,
{super.key});
// ScrollController scrollController ;
List<String> images;
String selectedImage;
Function changeSelectedImage;
@override
State<ModalSheetWidget> createState() => _ModalSheetWidgetState();
}
class _ModalSheetWidgetState extends State<ModalSheetWidget> {
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(15),
padding: EdgeInsets.all(20),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20), color: MyTheme.blackTwo),
child: Column(
children: [
Text(
"Pick Avatar",
style: Theme.of(context).textTheme.displayMedium,
),
GridView.builder(
physics: const NeverScrollableScrollPhysics(),
padding: EdgeInsets.symmetric(vertical: 20),
// controller: widget.scrollController,
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 4, childAspectRatio: 1),
itemBuilder: (context, index) => GestureDetector(
onTap: () {
setState(() {
widget.selectedImage = widget.images[index];
});
},
child: Container(
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
color: widget.selectedImage == widget.images[index]
? MyTheme.gray
: MyTheme.blackTwo,
borderRadius: BorderRadius.circular(15),
),
child: Image.asset(widget.images[index], width: 100)),
),
itemCount: widget.images.length,
),
Container(
width: double.infinity,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(MyTheme.gold),
shape: MaterialStateProperty.all(RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
))),
onPressed: () {
widget.changeSelectedImage(widget.selectedImage);
},
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
"Confirm",
style: Theme.of(context)
.textTheme
.displaySmall!
.copyWith(fontWeight: FontWeight.bold),
),
),
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/Movies/lib/Presentation | mirrored_repositories/Movies/lib/Presentation/Global Widgets/MoviesLists.dart | import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:mymoviesapp/Domain/Models/Movies/Movies.dart';
import 'package:mymoviesapp/Presentation/Global%20Widgets/PosterImage.dart';
class Movieslist extends StatelessWidget {
List<Movies> movies;
String type;
Function goToDetailsScreen ;
Movieslist({required this.movies , required this.type , required this.goToDetailsScreen});
@override
Widget build(BuildContext context) {
return SizedBox(
height: 300,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// the title of the genre
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0 , vertical: 10),
child: Text(
type,
textAlign: TextAlign.start,
style: Theme.of(context).textTheme.displayMedium
),
),
// the movies
CarouselSlider(
items: movies.map((movie) => PosterImage(movie: movie , goToDetailsScreen: goToDetailsScreen)).toList(),
options: CarouselOptions(
height: 220,
viewportFraction: 0.32,
disableCenter: true,
initialPage: 1,
enableInfiniteScroll: true,
enlargeCenterPage: true,
autoPlay: false,
enlargeFactor: 0.32,
scrollDirection: Axis.horizontal,
reverse: true,
animateToClosest: true,
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/Movies/lib/Presentation | mirrored_repositories/Movies/lib/Presentation/Global Widgets/MyTextFileds.dart |
import 'package:flutter/material.dart';
import 'package:mymoviesapp/Core/Theme/Theme.dart';
class MyTextFormField extends StatelessWidget {
String hint;
IconData icon ;
Function validation ;
TextEditingController controller;
TextInputType keyboardType;
MyTextFormField(this.hint , this.icon , this.validation, this.controller , this.keyboardType,{super.key});
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding:const EdgeInsets.symmetric(horizontal:20, vertical: 10),
child: TextFormField(
textCapitalization:TextCapitalization.words,
style: Theme.of(context).textTheme.headlineSmall,
validator: (value) => validation(value),
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: controller,
cursorColor: MyTheme.gray,
keyboardType: keyboardType,
decoration: InputDecoration(
contentPadding:const EdgeInsets.all(15),
hintText: hint,
hintStyle: Theme.of(context).textTheme.headlineSmall,
prefixIcon: Icon(
icon,
color: MyTheme.gray,
),
filled: true,
fillColor: MyTheme.blackOne,
errorStyle:const TextStyle(
fontSize: 14,
color: Colors.red
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(width: 2 , color: MyTheme.blackOne)
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(width: 2 , color: MyTheme.red)
),
disabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(width: 2 , color: MyTheme.blackOne)
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(width: 2 , color: MyTheme.red)
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(width: 2 , color: MyTheme.blackOne)
),
),
),
);
}
}
class MyPasswordTextFormField extends StatefulWidget {
String hint;
IconData icon ;
Function validation ;
TextEditingController controller;
TextInputType keyboardType;
MyPasswordTextFormField(this.hint , this.icon , this.validation, this.controller, this.keyboardType ,{super.key});
@override
State<MyPasswordTextFormField> createState() => _MyPasswordTextFormFieldState();
}
class _MyPasswordTextFormFieldState extends State<MyPasswordTextFormField> {
bool showPassword = false ;
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding:const EdgeInsets.symmetric(horizontal: 20 , vertical: 10),
child: TextFormField(
style: Theme.of(context).textTheme.headlineSmall,
validator: (value) => widget.validation(value),
controller: widget.controller,
obscureText: !showPassword,
autovalidateMode: AutovalidateMode.onUserInteraction,
cursorColor: MyTheme.gray,
keyboardType: widget.keyboardType,
decoration: InputDecoration(
contentPadding:const EdgeInsets.all(15),
hintText: widget.hint,
hintStyle: Theme.of(context).textTheme.headlineSmall,
errorStyle:const TextStyle(
fontSize: 14,
color: Colors.red
),
prefixIcon: Icon(
widget.icon,
color: MyTheme.gray,
),
suffixIcon: InkWell(
borderRadius: BorderRadius.circular(100),
onTap: (){
setState(() {
showPassword = !showPassword;
});
},
child:showPassword? const Icon(Icons.visibility , color: MyTheme.gray,):const Icon(Icons.visibility_off , color: MyTheme.gray,),
),
filled: true,
fillColor: MyTheme.blackOne,
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(width: 2 , color: MyTheme.blackOne)
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(width: 2 , color: MyTheme.red)
),
disabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(width: 2 , color: MyTheme.blackOne)
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(width: 2 , color: MyTheme.red)
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(width: 2 , color: MyTheme.blackOne)
),
),
),
);
}
}
| 0 |
mirrored_repositories/Movies/lib/Presentation | mirrored_repositories/Movies/lib/Presentation/Global Widgets/PosterImage.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:mymoviesapp/Core/Theme/Theme.dart';
import 'package:mymoviesapp/Domain/Models/Movies/Movies.dart';
class PosterImage extends StatelessWidget {
Movies movie;
Function goToDetailsScreen;
PosterImage({required this.movie, required this.goToDetailsScreen});
@override
Widget build(BuildContext context) {
// show the image and handel the waiting state and error state
return InkWell(
onTap: () {
goToDetailsScreen(movie.id);
},
child: Stack(
children: [
CachedNetworkImage(
imageUrl: movie.mediumCoverImage!,
imageBuilder: (context, imageProvider) => Stack(children: [
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.network(movie.mediumCoverImage!),
),
]),
placeholder: (context, url) => ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.asset('assets/images/loading.jpg'),
),
errorWidget: (context, url, error) => ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.asset('assets/images/error.png'),
),
),
Positioned(
top: 0,
left: 0,
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
decoration: BoxDecoration(
color: MyTheme.backGroundColor.withOpacity(0.5),
borderRadius: BorderRadius.circular(10)),
padding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
child: Row(
children: [
Text(
movie.rating.toString(),
style: Theme.of(context).textTheme.displaySmall,
),
const SizedBox(width: 5,),
const Icon(
EvaIcons.star,
color: MyTheme.gold,
size: 20,
),
],
),
),
))
],
),
);
}
}
| 0 |
mirrored_repositories/Movies/lib/Presentation | mirrored_repositories/Movies/lib/Presentation/Home/HomeScreenViewModel.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Browse/BrowseTabView.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/EditProfileScreen/EditProfileView.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Home/HomeTabView.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/MovieDetails/MovieDetailsView.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Profile/ProfileTabVIew.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Search/SearchTabView.dart';
class HomeScreenViewModel extends Cubit<BaseCubitState>{
HomeScreenViewModel():super(HomeTabState());
GoRouter? router ;
int selectedIndex = 0;
// change the selected index of the pages in case of the tab is movie details tab will be the last selected index
void setSelectedIndex(int index){
if(index != 9){
selectedIndex = index;
updateState(index);
}
}
// change the state of the code depend on the index from the setSelected state function
void updateState(int index){
if(index == 0){
emit(HomeTabState());
}else if (index == 1){
emit(SearchTabState());
}else if (index == 2){
emit(BrowseTabState());
}else if (index == 3){
emit(ProfileTabState());
}
}
// change the current selected icon depend on the route path
int setCurrentIndex(){
if(router!.location == HomeTabView.path){
selectedIndex = 0;
return 0;
}else if(router!.location == SearchTabView.path){
selectedIndex = 1;
return 1;
}else if(router!.location == BrowseTabView.path){
selectedIndex = 2;
return 2;
}else if(router!.location == ProfileTabView.path){
selectedIndex = 3;
return 3;
}else if(router!.location == MovieDetailsScreen.path){
return selectedIndex;
}else if(router!.location == EditProfileView.path){
return selectedIndex;
}
return 0;
}
}
class HomeTabState extends BaseCubitState{}
class SearchTabState extends BaseCubitState{}
class BrowseTabState extends BaseCubitState{}
class ProfileTabState extends BaseCubitState{}
class BackState extends BaseCubitState{} | 0 |
mirrored_repositories/Movies/lib/Presentation | mirrored_repositories/Movies/lib/Presentation/Home/HomeScreenView.dart | import 'package:dot_navigation_bar/dot_navigation_bar.dart';
import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:line_icons/line_icons.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Core/Theme/Theme.dart';
import 'package:mymoviesapp/Presentation/Home/HomeScreenViewModel.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Browse/BrowseTabView.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Home/HomeTabView.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Profile/ProfileTabVIew.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Search/SearchTabView.dart';
import 'package:unicons/unicons.dart';
class HomeScreen extends StatefulWidget {
static const String routeName = 'Home';
static const String path = '/Home';
Widget tab;
HomeScreen({required this.tab});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
HomeScreenViewModel viewModel = HomeScreenViewModel();
@override
void initState() {
super.initState();
viewModel.setSelectedIndex(0);
}
@override
Widget build(BuildContext context) {
viewModel.router = GoRouter.of(context);
return BlocProvider(
create: (context) => viewModel,
child: BlocConsumer<HomeScreenViewModel , BaseCubitState>(
listener: (context, state) {
if(state is HomeTabState){
context.push(HomeTabView.path);
} else if (state is SearchTabState){
context.push(SearchTabView.path);
} else if (state is BrowseTabState){
context.push(BrowseTabView.path);
} else if (state is ProfileTabState){
context.push(ProfileTabView.path);
}
},
builder:(context, state) => Scaffold(
body: widget.tab,
extendBody: true,
bottomNavigationBar: DotNavigationBar(
boxShadow: const [
BoxShadow(
color: MyTheme.backGroundColor,
offset: Offset(0, 5),
blurRadius: 20,
spreadRadius: 5
),
],
selectedItemColor: MyTheme.gold,
unselectedItemColor: MyTheme.gray,
enablePaddingAnimation: false,
onTap: (value) => viewModel.setSelectedIndex(value),
currentIndex: viewModel.setCurrentIndex(),
borderRadius: 20,
backgroundColor: MyTheme.blackOne,
marginR: const EdgeInsets.all(15),
paddingR:const EdgeInsets.symmetric(vertical: 10),
dotIndicatorColor: Colors.transparent,
items: [
DotNavigationBarItem(icon: const Icon(UniconsLine.estate),),
DotNavigationBarItem(icon: const Icon(EvaIcons.search),),
DotNavigationBarItem(icon: const Icon(EvaIcons.browserOutline),),
DotNavigationBarItem(icon: const Icon(LineIcons.userCircle),),
],
)
),
),
);
}
}
| 0 |
mirrored_repositories/Movies/lib/Presentation/Home/Tabs | mirrored_repositories/Movies/lib/Presentation/Home/Tabs/Search/SearchTabViewModel.dart | import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Domain/Exceptions/ServerException.dart';
import 'package:mymoviesapp/Domain/Models/Movies/Movies.dart';
import 'package:mymoviesapp/Domain/UseCase/getSearchResultsUseCase.dart';
import 'package:mymoviesapp/Presentation/Home/HomeScreenViewModel.dart';
class SearchTabViewModel extends Cubit<BaseCubitState>{
GetSearchResultsUseCase useCase ;
SearchTabViewModel(this.useCase) : super(EmptyListState());
HomeScreenViewModel? homeScreenViewModel;
Future<void> getSearchResults(String keyword)async{
emit(LoadingState());
if(keyword.isNotEmpty){
try{
if(keyword == 'الراجل اللي يابختة'){
keyword = 'iron man';
}
var response = await useCase.getSearchResults(keyword);
if(response == null){
emit(ErrorState("No Movies To Load"));
}else{
emit(MoviesLoadedState(response));
}
}catch(e){
if(e is ServerException){
emit(ErrorState(e.error));
}else {
emit(ErrorState(e.toString()));
}
}
}else{
emit(EmptyListState());
}
}
void goToDetailsScreen(num movie){
emit(MovieDetailsAction(movie));
}
}
class EmptyListState extends BaseCubitState{}
class MoviesLoadedState extends BaseCubitState {
List<Movies> movies ;
MoviesLoadedState(this.movies);
}
| 0 |
mirrored_repositories/Movies/lib/Presentation/Home/Tabs | mirrored_repositories/Movies/lib/Presentation/Home/Tabs/Search/SearchTabView.dart | import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Core/Theme/Theme.dart';
import 'package:mymoviesapp/Domain/UseCase/getSearchResultsUseCase.dart';
import 'package:mymoviesapp/Presentation/Global%20Widgets/PosterImage.dart';
import 'package:mymoviesapp/Presentation/Home/HomeScreenViewModel.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/MovieDetails/MovieDetailsView.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Search/SearchTabViewModel.dart';
import 'package:mymoviesapp/Core/DI/di.dart';
import 'package:provider/provider.dart';
class SearchTabView extends StatefulWidget {
static const String routeName = 'SearchTab';
static const String path = '/SearchTab';
@override
State<SearchTabView> createState() => _SearchTabViewState();
}
class _SearchTabViewState extends State<SearchTabView> {
SearchTabViewModel viewModel = SearchTabViewModel(GetSearchResultsUseCase(injectSearchRepo()));
@override
void initState() {
super.initState();
viewModel.homeScreenViewModel = Provider.of<HomeScreenViewModel>(context, listen: false);
}
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => viewModel,
child: Column(
children: [
AppBar(
backgroundColor: MyTheme.backGroundColor,
elevation: 0,
title:
TextField(
onChanged: (value) {
viewModel.getSearchResults(value);
},
cursorColor: MyTheme.gray,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
),
decoration: InputDecoration(
filled: true,
contentPadding:const EdgeInsets.all(10),
fillColor: MyTheme.blackFour,
hintText: "Search",
hintStyle: const TextStyle(color: MyTheme.gray, fontSize: 18),
prefixIcon: const Icon(
EvaIcons.search,
color: MyTheme.gray,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide:
const BorderSide(color: Colors.transparent, width: 0)),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide:
const BorderSide(color: Colors.transparent, width: 0)),
disabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide:
const BorderSide(color: Colors.transparent, width: 0)),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide:
const BorderSide(color: Colors.transparent, width: 0)),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide:
const BorderSide(color: Colors.transparent, width: 0)),
),
),
toolbarHeight: 80,
),
Expanded(
child: BlocConsumer<SearchTabViewModel, BaseCubitState>(
listener: (context, state) {
if(state is MovieDetailsAction){
GoRouter.of(context).pushNamed( MovieDetailsScreen.routeName , extra: state.movie);
viewModel.homeScreenViewModel!.setSelectedIndex(9);
}
},
buildWhen: (previous, current) {
if(previous is EmptyListState && current is LoadingState){
return true;
}else if (previous is LoadingState && current is EmptyListState){
return true;
}else if (previous is LoadingState && current is MoviesLoadedState){
return true;
}else if (previous is LoadingState && current is ErrorState){
return true;
}else if (previous is MoviesLoadedState && current is LoadingState){
return true;
}else if (previous is ErrorState && current is LoadingState){
return true;
}else {
return false;
}
},
builder: (context, state) {
if (state is EmptyListState) {
return Center(child: Image.asset('assets/images/Empty.png'),);
}else if(state is LoadingState){
return Center(child: CircularProgressIndicator(color: MyTheme.gold,),);
} else if (state is MoviesLoadedState) {
return Column(
children: [
Expanded(
child: GridView.builder(
physics: const BouncingScrollPhysics(),
padding: const EdgeInsets.symmetric(horizontal: 20),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 20 ,
mainAxisSpacing: 20,
childAspectRatio: 0.65
),
itemBuilder: (context, index) => PosterImage(
movie: state.movies[index],
goToDetailsScreen: viewModel.goToDetailsScreen,
),
itemCount: state.movies.length,
)
),
],
);
} else if (state is ErrorState) {
return Center(child: Image.asset('assets/images/Empty.png'),);
} else {
return Container();
}
},
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/Movies/lib/Presentation/Home/Tabs | mirrored_repositories/Movies/lib/Presentation/Home/Tabs/MovieDetails/MovieDetailsView.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:line_icons/line_icons.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Core/DI/di.dart';
import 'package:mymoviesapp/Core/Providers/AppConfigProvieder.dart';
import 'package:mymoviesapp/Core/Providers/DataProvider.dart';
import 'package:mymoviesapp/Core/Theme/Theme.dart';
import 'package:mymoviesapp/Core/utils/DialogUtils.dart';
import 'package:mymoviesapp/Domain/UseCase/addToHistoryUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/addToWishListUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/daleteFromWishListUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/getMovieFullDetailsUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/getRelatedMoviesUseCase.dart';
import 'package:mymoviesapp/Presentation/Global%20Widgets/MoviesLists.dart';
import 'package:mymoviesapp/Presentation/Home/HomeScreenViewModel.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/MovieDetails/MovieDetailsViewModel.dart';
import 'package:provider/provider.dart';
class MovieDetailsScreen extends StatefulWidget {
num? movieId;
MovieDetailsScreen({required this.movieId, Key? key}) : super(key: key);
static const String routeName = 'MovieDetailsScreen';
static const String path = '/MovieDetailsScreen';
@override
State<MovieDetailsScreen> createState() => _MovieDetailsScreenState();
}
class _MovieDetailsScreenState extends State<MovieDetailsScreen> {
MovieDetailsViewModel viewModel = MovieDetailsViewModel(
GetRelatedMoviesUseCase(injectMoviesRepository()),
GetMovieFullDetailsUseCase(injectMoviesRepository()),
AddToHistoryUseCase(injectMoviesRepository()),
AddToWishListUseCase(injectMoviesRepository()),
DeleteFromWishListUseCase(injectMoviesRepository()),
);
@override
void initState() {
viewModel.homeScreenViewModel = Provider.of<HomeScreenViewModel>(context, listen: false);
viewModel.provider = Provider.of<AppConfigProvider>(context , listen: false);
viewModel.dataProvider = Provider.of<DataProvider>(context , listen: false);
viewModel.loadData(widget.movieId);
super.initState();
}
@override
void dispose() {
super.dispose();
viewModel.provider = null;
viewModel.homeScreenViewModel = null;
viewModel.dataProvider = null;
}
@override
Widget build(BuildContext context) {
return BlocProvider<MovieDetailsViewModel>(
create: (context) => viewModel,
child: BlocConsumer<MovieDetailsViewModel, BaseCubitState>(
listener: (context, state) {
if (state is BackAction) {
context.pop(context);
} else if (state is MovieDetailsAction) {
viewModel.homeScreenViewModel!.setSelectedIndex(9);
context.pushNamed(MovieDetailsScreen.routeName, extra: state.movie);
}else if (state is HideDialog) {
MyDialogUtils.hideDialog(context);
}else if (state is ShowLoadingState) {
MyDialogUtils.showLoadingDialog(context, state.message);
}else if (state is ShowSuccessMessageState) {
MyDialogUtils.showSuccessMessage(
context: context,
message: state.message,
posActionTitle: "Ok",);
}else if (state is ShowErrorMessageState) {
MyDialogUtils.showFailMessage(
context: context,
message: state.message,
posActionTitle: "Try Again");
}
},
buildWhen: (previous, current) {
if (current is DataLoadedState && previous is LoadingState) {
return true;
}else if (current is DataLoadedState && previous is ShowSuccessMessageState) {
return true;
} else {
return false;
}
},
builder: (context, state) {
if (state is LoadingState) {
return const Center(
child: CircularProgressIndicator(
color: MyTheme.gold,
),
);
} else if (state is DataLoadedState) {
return Stack(
children: [
SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// the header
Stack(
alignment: Alignment.center,
children: [
// the poster image in the background
Image.asset('assets/images/loading.jpg'),
CachedNetworkImage(
imageUrl: state.movie.largeCoverImage!,
imageBuilder: (context, imageProvider) =>
Image.network(state.movie.largeCoverImage!),
width: MediaQuery.of(context).size.width,
placeholder: (context, url) => Image.asset(
'assets/images/loading.jpg',
),
errorWidget: (context, url, error) =>
Image.asset('assets/images/error.png')),
// the gradient layer in the page
Positioned.fill(
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
MyTheme.backGroundColor.withOpacity(0.3),
MyTheme.backGroundColor.withOpacity(0.1),
MyTheme.backGroundColor.withOpacity(0.7),
MyTheme.backGroundColor.withOpacity(1),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter)),
)),
// the center play button
InkWell(
onTap: () => viewModel.lunchURL(state.movie.url! , state.movie),
child: Center(
child: Container(
height: 60,
width: 60,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(100),
color: MyTheme.gold,
),
child: const Icon(
Icons.play_circle_outline,
color: Colors.white,
size: 60,
),
)),
),
// the movie title nad date
Positioned.fill(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Movie title
Expanded(
child: Text(
state.movie.titleEnglish!,
textAlign: TextAlign.center,
style: Theme.of(context)
.textTheme
.displayLarge!
.copyWith(fontSize: 30),
),
),
],
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0),
child: Text(state.movie.year!.toString(),
style: Theme.of(context)
.textTheme
.headlineSmall),
),
],
),
),
),
],
),
// watch the movie
Container(
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 20),
width: double.infinity,
child: ElevatedButton(
onPressed: () => viewModel.lunchURL(state.movie.url!, state.movie),
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.red),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(10)))),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Text(
"Watch",
style: Theme.of(context).textTheme.displayMedium,
),
),
),
),
// the likes count and the movie duration and the rating
Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Row(
children: [
const SizedBox(
width: 20,
),
info(state.movie.likeCount!.toString(),
EvaIcons.heart),
const SizedBox(
width: 10,
),
info("${state.movie.runtime!.toString()} m",
LineIcons.hourglassHalf),
const SizedBox(
width: 10,
),
info(state.movie.rating!.toString(), EvaIcons.star),
const SizedBox(
width: 20,
),
],
),
),
// the list of related movies
Movieslist(
movies: state.relatedMovies,
type: "Similar",
goToDetailsScreen: viewModel.goToDetailsScreen),
// the Genres of the Movie
title("Genres"),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: GridView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
padding: EdgeInsets.zero,
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
childAspectRatio: 3,
mainAxisSpacing: 10,
crossAxisSpacing: 10),
itemBuilder: (context, index) => Container(
decoration: BoxDecoration(
color: MyTheme.blackFour,
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: Text(
state.movie.genres![index],
style: Theme.of(context)
.textTheme
.headlineSmall!
.copyWith(fontSize: 16),
),
),
),
itemCount: state.movie.genres!.length,
),
),
// the movie summary
const SizedBox(
height: 10,
),
title("Cast"),
state.movie.cast == null ? Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Text("No Cast Available Now" , style: Theme.of(context).textTheme.headlineMedium!.copyWith(fontWeight: FontWeight.normal),),
): ListView.builder(
padding: EdgeInsets.zero,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemBuilder: (context, index) => Container(
decoration: BoxDecoration(
color: MyTheme.blackOne,
borderRadius: BorderRadius.circular(20),
),
margin:const EdgeInsets.symmetric(vertical: 10 , horizontal: 20),
padding: const EdgeInsets.symmetric(vertical: 10 , horizontal: 10),
child: Row(
children: [
state.movie.cast![index].urlSmallImage == null ?ClipRRect(
borderRadius: BorderRadius.circular(15),
child: Image.asset('assets/images/user.png' , width: 70 , fit: BoxFit.cover,),
):
CachedNetworkImage(
imageUrl: state.movie.cast![index].urlSmallImage!,
imageBuilder: (context, imageProvider) =>ClipRRect(
borderRadius: BorderRadius.circular(15),
child: Image.network(state.movie.cast![index].urlSmallImage! , width: 70, fit: BoxFit.cover,),
),
placeholder: (context, url) => Image.asset('assets/images/user.png', width: 70,),
errorWidget: (context, url, error) => Image.asset('assets/images/user.png') , width: 70,),
const SizedBox(width: 20,),
Expanded(child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Name : ${state.movie.cast![index].name}", style: Theme.of(context).textTheme.displaySmall, maxLines: 1, overflow: TextOverflow.ellipsis,),
Text("Character : ${state.movie.cast![index].characterName}", style: Theme.of(context).textTheme.displaySmall, maxLines: 1, overflow: TextOverflow.ellipsis,)
],))
],
),
),
itemCount: state.movie.cast!.length,
),
title("Summary"),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 10),
child: Text(
state.movie.descriptionFull!,
style: Theme.of(context)
.textTheme
.headlineSmall!
.copyWith(
fontWeight: FontWeight.w400, wordSpacing: 1),
),
),
const SizedBox(height: 100,),
],
),
),
// the top bar
Positioned(
top: 0,
child: SafeArea(
child: Container(
padding: const EdgeInsets.all(15),
width: MediaQuery.of(context).size.width,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
onPressed: () {
viewModel.onPressBackAction();
},
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.white,
size: 28,
)),
IconButton(
onPressed: () {
viewModel.changeWishList(state.movie);
},
icon: Icon(
Icons.bookmark_add,
color: state.movie.isInWishList? MyTheme.gold:Colors.white,
size: 30,
))
],
),
),
),
),
],
);
} else if (state is ErrorState) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
state.errorMessage,
style: const TextStyle(color: Colors.white),
),
ElevatedButton(
onPressed: () {
viewModel.setStateToLoading();
viewModel.loadData(widget.movieId);
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(MyTheme.gold),
),
child: const Text("Try Again"))
],
);
} else {
return Container();
}
},
),
);
}
Widget title(String text) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
child: Text(
text,
style: Theme.of(context).textTheme.displayLarge,
),
);
}
Widget info(String title, IconData icon) {
return Expanded(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
// border: Border.all(width: 2, color: MyTheme.gold),
color: MyTheme.blackOne),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Icon(
icon,
color: MyTheme.gold,
size: 30,
),
Expanded(
child: Text(
title,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.displaySmall,
overflow: TextOverflow.ellipsis,
maxLines: 1,
)),
],
),
));
}
}
| 0 |
mirrored_repositories/Movies/lib/Presentation/Home/Tabs | mirrored_repositories/Movies/lib/Presentation/Home/Tabs/MovieDetails/MovieDetailsViewModel.dart | import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Core/Providers/AppConfigProvieder.dart';
import 'package:mymoviesapp/Core/Providers/DataProvider.dart';
import 'package:mymoviesapp/Core/utils/DialogUtils.dart';
import 'package:mymoviesapp/Domain/Exceptions/ServerException.dart';
import 'package:mymoviesapp/Domain/Models/Movies/Movies.dart';
import 'package:mymoviesapp/Domain/Models/MoviesDetails/Movie.dart';
import 'package:mymoviesapp/Domain/UseCase/addToHistoryUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/addToWishListUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/daleteFromWishListUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/getMovieFullDetailsUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/getRelatedMoviesUseCase.dart';
import 'package:mymoviesapp/Presentation/Home/HomeScreenViewModel.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:url_launcher/url_launcher_string.dart';
class MovieDetailsViewModel extends Cubit<BaseCubitState> {
GetRelatedMoviesUseCase getRelatedMoviesUseCase ;
GetMovieFullDetailsUseCase getMovieFullDetailsUseCase ;
AddToHistoryUseCase addToHistoryUseCase;
AddToWishListUseCase addToWishListUseCase;
DeleteFromWishListUseCase deleteFromWishListUseCase;
MovieDetailsViewModel(
this.getRelatedMoviesUseCase ,
this.getMovieFullDetailsUseCase ,
this.addToHistoryUseCase,
this.addToWishListUseCase,
this.deleteFromWishListUseCase
):super(LoadingState());
AppConfigProvider? provider;
DataProvider? dataProvider;
HomeScreenViewModel?homeScreenViewModel;
void loadData(num? movieId)async{
try{
var movies =await getRelatedMoviesUseCase.invoke(movieId.toString());
dataProvider!.relatedMovies = movies!;
var uid = await provider!.getUid();
var movie =await getMovieFullDetailsUseCase.invoke(movieId , uid);
emit(DataLoadedState( movie ,movies)) ;
}catch(e){
if(e is ServerException){
emit(ErrorState(e.error));
}else {
emit(ErrorState(e.toString()));
}
}
}
void setStateToLoading(){
emit(LoadingState());
}
void onPressBackAction(){
emit(BackAction());
}
void goToDetailsScreen(num movie){
emit(MovieDetailsAction(movie));
}
Future<void> lunchURL(String link , Movie movie)async{
try{
var url = Uri.parse(link);
!await launchUrl(url , mode: LaunchMode.externalApplication,
webViewConfiguration: const WebViewConfiguration(
headers: <String, String>{'my_header_key': 'my_header_value'}));
var uid = await provider!.getUid();
var response =await addToHistoryUseCase.invoke(uid, movie.id!, movie.mediumCoverImage!, movie.largeCoverImage!, movie.rating! , movie.isWatched);
dataProvider!.addMoviesToWatchHistory(Movies(
id: movie.id!,
mediumCoverImage: movie.mediumCoverImage!,
rating: movie.rating!,
largeCoverImage: movie.largeCoverImage!
) , movie.isWatched);
movie.isWatched = true;
}catch(e){
if(e is ServerException){
emit(ErrorState(e.error));
}else {
emit(ErrorState(e.toString()));
}
}
}
Future<void> changeWishList(Movie movie)async{
emit(ShowLoadingState("adding To WishList"));
try{
String uid = await provider!.getUid();
if(movie.isInWishList){
var response = await deleteFromWishListUseCase.invoke(uid, movie.id!);
dataProvider!.deleteFromWishList(Movies(
id: movie.id!,
rating: movie.rating!,
mediumCoverImage: movie.mediumCoverImage!,
largeCoverImage: movie.largeCoverImage!
));
emit(HideDialog());
emit(ShowSuccessMessageState(response));
}else{
var response = await addToWishListUseCase.invoke(uid, movie.id!, movie.mediumCoverImage!, movie.largeCoverImage!, movie.rating!);
dataProvider!.addToWishList(Movies(
id: movie.id!,
rating: movie.rating!,
mediumCoverImage: movie.mediumCoverImage!,
largeCoverImage: movie.largeCoverImage!
));
emit(HideDialog());
emit(ShowSuccessMessageState(response));
}
movie.isInWishList = !movie.isInWishList;
emit(DataLoadedState(movie, dataProvider!.relatedMovies));
}catch(e){
emit(HideDialog());
emit(ErrorState(e.toString()));
}
}
}
class DataLoadedState extends BaseCubitState{
Movie movie ;
List<Movies> relatedMovies;
DataLoadedState(this.movie ,this.relatedMovies);
}
class BackAction extends BaseCubitState{}
| 0 |
mirrored_repositories/Movies/lib/Presentation/Home/Tabs | mirrored_repositories/Movies/lib/Presentation/Home/Tabs/EditProfileScreen/EditProfileViewModel.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Core/Providers/AppConfigProvieder.dart';
import 'package:mymoviesapp/Domain/Exceptions/FirebaseAuthException.dart';
import 'package:mymoviesapp/Domain/Exceptions/FirebaseTimeoutException.dart';
import 'package:mymoviesapp/Domain/Models/User/User.dart';
import 'package:mymoviesapp/Domain/UseCase/resetPasswordUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/updateUserDataUseCase.dart';
class EditProfileViewModel extends Cubit<BaseCubitState>{
UpdateUserDataUseCase updateUserDataUseCase;
ResetPasswordUseCase resetPasswordUseCase;
EditProfileViewModel(this.user , this.updateUserDataUseCase , this.resetPasswordUseCase):super(InputWaiting());
final formKey = GlobalKey<FormState>();
TextEditingController name = TextEditingController();
TextEditingController phone = TextEditingController();
Users user;
List<String> images = [
"assets/images/avatar1.png",
"assets/images/avatar2.png",
"assets/images/avatar3.png",
"assets/images/avatar4.png",
"assets/images/avatar5.png",
"assets/images/avatar6.png",
"assets/images/avatar7.png",
"assets/images/avatar8.png",
"assets/images/avatar9.png",
];
String image = '';
void changeSelectedImage(String image){
this.image = image;
emit(InputWaiting());
}
void initData(){
image = user.image;
phone.text = user.phone;
name.text= user.name;
}
// validate on the name if it is not empty and doesn't contain ant spacial characters
String? nameValidation(String name){
if (name.isEmpty){
return "Name Can't be Empty";
}else if (RegExp(r'[!@#<>?":_`~;[\]\\|=+)(*&^%-]').hasMatch(name)){
return "Invalid Name";
}else {
return null;
}
}
// validate on phone number
String? phoneValidation(String input) {
if (input.isEmpty) {
return "Please Enter a Phone Number";
} else if (!RegExp(
r'^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$')
.hasMatch(input)) {
return "Please Enter a Valid Phone Number";
}
return null;
}
void resetPassword()async{
if(formKey.currentState!.validate()){
emit(ShowLoadingState("Sending Email"));
try{
var response = await resetPasswordUseCase.invoke(user.email);
emit(HideDialog());
emit(ShowSuccessMessageState(response));
}catch (e){
emit(HideDialog());
if (e is FirebaseAuthDataSourceException){
emit(ShowErrorMessageState(e.errorMessage));
}else if (e is FirebaseTimeoutException){
emit(ShowErrorMessageState(e.error));
}else {
emit(ShowErrorMessageState(e.toString()));
}
}
}
}
// registration to validate and send the data to data base
void updateUserData()async{
if(formKey.currentState!.validate()){
emit(ShowLoadingState("Updating"));
user.image = image;
user.name = name.text;
user.phone = phone.text;
try {
var response = await updateUserDataUseCase.invoke(user);
emit(HideDialog());
emit(ShowSuccessMessageState("Data Updated Successfully"));
}catch (e){
emit(HideDialog());
if(e is FirebaseAuthDataSourceException){
emit(ShowErrorMessageState(e.errorMessage));
}else if (e is FirebaseTimeoutException){
emit(ShowErrorMessageState(e.error));
} else {
emit(ShowErrorMessageState(e.toString()));
}
}
}
}
void goToHomeScreen(){
emit(GoToHomeScreenAction());
}
}
class InputWaiting extends BaseCubitState{}
class GoToHomeScreenAction extends BaseCubitState{}
| 0 |
mirrored_repositories/Movies/lib/Presentation/Home/Tabs | mirrored_repositories/Movies/lib/Presentation/Home/Tabs/EditProfileScreen/EditProfileView.dart | import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Core/DI/di.dart';
import 'package:mymoviesapp/Core/Theme/Theme.dart';
import 'package:mymoviesapp/Core/utils/DialogUtils.dart';
import 'package:mymoviesapp/Domain/Models/User/User.dart';
import 'package:mymoviesapp/Domain/UseCase/resetPasswordUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/updateUserDataUseCase.dart';
import 'package:mymoviesapp/Presentation/Global%20Widgets/MyBottomSheet.dart';
import 'package:mymoviesapp/Presentation/Global%20Widgets/MyTextFileds.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/EditProfileScreen/EditProfileViewModel.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Home/HomeTabView.dart';
class EditProfileView extends StatefulWidget {
Users user;
EditProfileView({required this.user,super.key});
static const String routeName = 'EditProfile';
static const String path = '/EditProfile';
@override
State<EditProfileView> createState() => _EditProfileViewState();
}
class _EditProfileViewState extends State<EditProfileView> {
late EditProfileViewModel viewModel = EditProfileViewModel(
widget.user,
UpdateUserDataUseCase(injectUserRepository()),
ResetPasswordUseCase(injectUserRepository())
);
@override
void initState() {
super.initState();
viewModel.initData();
}
@override
Widget build(BuildContext context) {
return BlocProvider<EditProfileViewModel>(
create: (context) => viewModel,
child: BlocConsumer<EditProfileViewModel , BaseCubitState>(
listener: (context, state) {
if (state is HideDialog) {
MyDialogUtils.hideDialog(context);
} else if (state is ShowLoadingState) {
MyDialogUtils.showLoadingDialog(context, state.message);
} else if (state is ShowSuccessMessageState) {
MyDialogUtils.showSuccessMessage(
context: context,
message: state.message,
posActionTitle: "Ok",
posAction: viewModel.goToHomeScreen);
} else if (state is ShowErrorMessageState) {
MyDialogUtils.showFailMessage(
context: context,
message: state.message,
posActionTitle: "Try Again");
}else if (state is GoToHomeScreenAction) {
GoRouter.of(context).goNamed(HomeTabView.routeName);
} else if (state is InputWaiting) {
context.pop();
}
},
builder:(context, state) => Scaffold(
appBar: AppBar(
title: Text("Edit Profile" , style: Theme.of(context).textTheme.displayMedium,),
),
body: SingleChildScrollView(
child: Column(
children: [
Row(
children: [
Expanded(
flex: 2,
child: Image.asset(
viewModel.image,
width: 150,
),
),
Expanded(
flex: 4,
child: GridView.builder(
physics: const NeverScrollableScrollPhysics(),
padding: EdgeInsets.zero,
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 4,
childAspectRatio: 1,
mainAxisSpacing: 10,
crossAxisSpacing: 10
),
itemBuilder: (context, index) => GestureDetector(
onTap: () {
setState(() {
viewModel.image = viewModel.images[index] ;
});
},
child: Container(
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
color: viewModel.image == viewModel.images[index]
? MyTheme.gray
: MyTheme.blackTwo,
borderRadius: BorderRadius.circular(15),
),
child: Image.asset(viewModel.images[index], width: 100)),
),
itemCount: viewModel.images.length,
),
),
SizedBox(width: 20,)
],
),
Form(
key: viewModel.formKey,
child: Column(
children: [
const SizedBox(
height: 20,
),
MyTextFormField(
"Name",
EvaIcons.person,
viewModel.nameValidation,
viewModel.name,
TextInputType.name),
MyTextFormField(
"Phone Number",
EvaIcons.phone,
viewModel.phoneValidation,
viewModel.phone,
TextInputType.phone),
Row(
children: [
SizedBox(width: 15,),
TextButton(onPressed: viewModel.resetPassword, child: Text("Reset Password" ,style: Theme.of(context).textTheme.displaySmall ,textAlign: TextAlign.start,) ,),
],
),
Container(
width: double.infinity,
margin: const EdgeInsets.all(20),
child: ElevatedButton(
onPressed: viewModel.updateUserData,
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(
MyTheme.gold),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
))),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
"Update Data",
style: Theme.of(context)
.textTheme
.displaySmall!
.copyWith(
fontWeight: FontWeight.bold),
),
)),
),
],
)
),
SizedBox(height: 80,),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Movies/lib/Presentation/Home/Tabs | mirrored_repositories/Movies/lib/Presentation/Home/Tabs/Browse/BrowseTabView.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Core/Theme/Theme.dart';
import 'package:mymoviesapp/Domain/UseCase/getMoviesByGenreToBrowseUseCase.dart';
import 'package:mymoviesapp/Presentation/Global%20Widgets/PosterImage.dart';
import 'package:mymoviesapp/Presentation/Home/HomeScreenViewModel.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Browse/BrowseTabViewMode.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Browse/Widgets/TabButton.dart';
import 'package:mymoviesapp/Core/DI/di.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/MovieDetails/MovieDetailsView.dart';
import 'package:provider/provider.dart';
class BrowseTabView extends StatefulWidget {
static const String routeName = 'BrowseTab';
static const String path = '/BrowseTab';
@override
State<BrowseTabView> createState() => _BrowseTabViewState();
}
class _BrowseTabViewState extends State<BrowseTabView> {
BrowseTabViewModel viewModel = BrowseTabViewModel(
GetMoviesByGenreToBrowseUseCase(injectMoviesRepository()));
@override
void initState() {
super.initState();
viewModel.getMoviesByGenre(viewModel.genres[viewModel.selectedIndex], viewModel.pageNumber);
viewModel.homeScreenViewModel = Provider.of<HomeScreenViewModel>(context, listen: false);
}
@override
Widget build(BuildContext context) {
return BlocProvider<BrowseTabViewModel>(
create: (context) => viewModel,
child: Column(
children: [
const SizedBox(height: 20),
Padding(
padding: const EdgeInsets.all(8.0),
child: DefaultTabController(
length: viewModel.genres.length,
child: TabBar(
physics: const BouncingScrollPhysics(),
isScrollable: true,
overlayColor: MaterialStateProperty.all(Colors.transparent),
indicatorColor: Colors.transparent,
labelPadding: const EdgeInsets.all(5),
tabs: viewModel.genres
.map((item) => TabButton(
genre: item,
isSelected: viewModel.genres.indexOf(item) ==
viewModel.selectedIndex,
))
.toList(),
onTap: (value) {
setState(() {
viewModel.changeTap(value);
});
},
),
),
),
Expanded( child: BlocConsumer<BrowseTabViewModel, BaseCubitState>(
listener: (context, state) {
if (state is MovieDetailsAction) {
viewModel.homeScreenViewModel!.setSelectedIndex(9);
context.pushNamed(MovieDetailsScreen.routeName, extra: state.movie);
}
},
buildWhen: (previous, current) {
if (previous is LoadingState && current is MoviesLoadedState){
return true ;
}else if ( current is LoadingState && previous is MoviesLoadedState){
return true ;
}else if ( current is MoviesLoadedState && previous is MoviesLoadedState){
return true ;
}else if ( current is LoadingState && previous is LoadingState){
return true ;
}else if ( current is MoviesLoadedState && previous is MovieDetailsAction){
return true ;
}else {
return false ;
}
},
builder: (context, state) {
if (state is LoadingState) {
return const Center(
child: CircularProgressIndicator(
color: MyTheme.gold,
),
);
} else if (state is ErrorState) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
state.errorMessage,
style: const TextStyle(color: Colors.white),
),
ElevatedButton(
onPressed: () {
viewModel.changeToLoadingState();
viewModel.getMoviesByGenre(
viewModel.genres[viewModel.selectedIndex],
viewModel.pageNumber);
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(MyTheme.gold),
),
child: const Text("Try Again"))
],
);
} else if (state is MoviesLoadedState) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: GridView.builder(
physics: const BouncingScrollPhysics(),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 20 ,
mainAxisSpacing: 20,
childAspectRatio: 0.65
),
itemBuilder: (context, index) {
if (index < viewModel.movies.length) {
return PosterImage(movie : viewModel.movies[index],
goToDetailsScreen: viewModel.goToDetailsScreen);
} else {
viewModel.getMoviesByGenre(
viewModel.genres[viewModel.selectedIndex],
viewModel.pageNumber);
return const Padding(
padding: EdgeInsets.all(20),
child: Center(
child: CircularProgressIndicator(
color: MyTheme.gold,
)),
);
}
},
itemCount: viewModel.movies.length + 1,
),
);
} else {
return Container();
}
},
)),
],
),
);
}
}
| 0 |
mirrored_repositories/Movies/lib/Presentation/Home/Tabs | mirrored_repositories/Movies/lib/Presentation/Home/Tabs/Browse/BrowseTabViewMode.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Domain/Exceptions/ServerException.dart';
import 'package:mymoviesapp/Domain/Models/Movies/Movies.dart';
import 'package:mymoviesapp/Domain/UseCase/getMoviesByGenreToBrowseUseCase.dart';
import 'package:mymoviesapp/Presentation/Home/HomeScreenViewModel.dart';
class BrowseTabViewModel extends Cubit<BaseCubitState>{
List<String> genres = [
'Action', 'Adventure', 'Animation', 'Biography', 'Comedy', 'Crime', 'Documentary', 'Drama',
'Family', 'Fantasy', 'Film Noir', 'History', 'Horror', 'Music', 'Musical', 'Mystery', 'Romance',
'Sci-Fi', 'Short Film', 'Sport', 'Superhero', 'Thriller', 'War', 'Western',
];
int selectedIndex = 0;
int pageNumber = 1;
List<Movies> movies = [];
GetMoviesByGenreToBrowseUseCase useCase ;
BrowseTabViewModel(this.useCase):super(LoadingState());
ScrollController controller = ScrollController();
HomeScreenViewModel? homeScreenViewModel;
Future<void> getMoviesByGenre(String genre , int pageNumber)async{
try {
var response = await useCase.getMoviesToBrowse(genre , pageNumber);
if(response == null){
emit(ErrorState("No Movies To Load"));
}else{
movies.addAll(response);
this.pageNumber++;
emit(MoviesLoadedState());
}
}catch(e){
if(e is ServerException){
emit(ErrorState(e.error));
}else {
emit(ErrorState(e.toString()));
}
}
}
void changeToLoadingState(){
emit(LoadingState());
}
void goToDetailsScreen(num movie){
emit(MovieDetailsAction(movie));
}
void changeTap(int index){
selectedIndex = index;
pageNumber = 1;
movies = [];
emit(LoadingState());
getMoviesByGenre(genres[selectedIndex], pageNumber);
}
}
class MoviesLoadedState extends BaseCubitState {}
| 0 |
mirrored_repositories/Movies/lib/Presentation/Home/Tabs/Browse | mirrored_repositories/Movies/lib/Presentation/Home/Tabs/Browse/Widgets/TabButton.dart | import 'package:flutter/material.dart';
class TabButton extends StatelessWidget {
String genre;
bool isSelected;
TabButton({required this.genre, required this.isSelected});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
decoration: BoxDecoration(
color: isSelected ? Theme.of(context).primaryColor : Colors.transparent,
borderRadius: BorderRadius.circular(30),
border: Border.all(width: 2, color: Theme.of(context).primaryColor),
),
child: Text(
genre,
style: TextStyle( color: isSelected ? Colors.white : Theme.of(context).primaryColor, fontSize: 14 ),
)
);
}
}
| 0 |
mirrored_repositories/Movies/lib/Presentation/Home/Tabs | mirrored_repositories/Movies/lib/Presentation/Home/Tabs/Home/HomeTabView.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Core/Providers/DataProvider.dart';
import 'package:mymoviesapp/Core/Theme/Theme.dart';
import 'package:mymoviesapp/Domain/UseCase/getMoviesByGenreUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/getMoviesDataUseCase.dart';
import 'package:mymoviesapp/Presentation/Global%20Widgets/MoviesLists.dart';
import 'package:mymoviesapp/Presentation/Home/HomeScreenViewModel.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Home/HomeTabViewModel.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Home/Widgets/MyPlaceHolder.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Home/Widgets/TopRatedMovies.dart';
import 'package:mymoviesapp/Core/DI/di.dart';
import 'package:provider/provider.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/MovieDetails/MovieDetailsView.dart';
class HomeTabView extends StatefulWidget {
static const String routeName = 'HomeTab';
static const String path = '/HomeTab';
@override
State<HomeTabView> createState() => _HomeTabViewState();
}
class _HomeTabViewState extends State<HomeTabView> {
HomeTabViewModel viewModel = HomeTabViewModel(
GetMoviesDataUseCase(injectMoviesRepository()),
GetMoviesByGenreUseCase(injectMoviesRepository()));
@override
void initState() {
super.initState();
viewModel.provider = Provider.of<DataProvider>(context,listen: false);
viewModel.homeScreenViewModel = Provider.of<HomeScreenViewModel>(context, listen: false);
viewModel.readData();
}
@override
void dispose() {
super.dispose();
viewModel.provider = null;
}
@override
Widget build(BuildContext context) {
return BlocProvider<HomeTabViewModel>(
create: (context) => viewModel,
child: BlocConsumer<HomeTabViewModel, BaseCubitState>(
listener: (context, state) {
if(state is MovieDetailsAction){
viewModel.homeScreenViewModel?.setSelectedIndex(9);
context.pushNamed(MovieDetailsScreen.routeName , extra: state.movie);
}
},
buildWhen: (previous, current) {
if(previous is LoadingState && current is MoviesLoadedState){
return true;
}else if (previous is LoadingState && current is ErrorState){
return true;
}else if (previous is ErrorState && current is LoadingState){
return true;
}else if (previous is RefreshState && current is MoviesLoadedState){
return true;
}else if (previous is RefreshState && current is ErrorState ){
return true;
}else {
return false;
}
},
builder: (context, state) {
if (state is LoadingState) {
return MyPlaceHolder();
} else if (state is MoviesLoadedState) {
return RefreshIndicator(
onRefresh: viewModel.refreshData,
color: MyTheme.gold,
child: SingleChildScrollView(
child: Column(
children: [
TopRatedMovies(movies: state.movies! , goToDetailsScreen: viewModel.goToDetailsScreen),
const SizedBox(
height: 10,
),
Movieslist(
movies: state.actionMovies!,
type: "Action Movies",
goToDetailsScreen: viewModel.goToDetailsScreen
),
Movieslist(
movies: state.crimeMovies!,
type: "Crime Movies ",
goToDetailsScreen: viewModel.goToDetailsScreen
),
Movieslist(
movies: state.dramaMovies!,
type: "Drama Movies",
goToDetailsScreen: viewModel.goToDetailsScreen
),
Movieslist(
movies: state.animationMovies!,
type: "Animation Movies",
goToDetailsScreen: viewModel.goToDetailsScreen
),
],
)),
);
} else if(state is ErrorState){
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(state.errorMessage , style: const TextStyle(color: Colors.white),),
ElevatedButton(
onPressed: (){
viewModel.readData();
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(MyTheme.gold),
) ,
child:const Text(
"Try Again"
)
)
],
);
}else{
return Container();
}
},
),
);
}
}
| 0 |
mirrored_repositories/Movies/lib/Presentation/Home/Tabs | mirrored_repositories/Movies/lib/Presentation/Home/Tabs/Home/HomeTabViewModel.dart | import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Core/Providers/DataProvider.dart';
import 'package:mymoviesapp/Domain/Exceptions/ServerException.dart';
import 'package:mymoviesapp/Domain/Models/Movies/Movies.dart';
import 'package:mymoviesapp/Domain/UseCase/getMoviesByGenreUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/getMoviesDataUseCase.dart';
import 'package:mymoviesapp/Presentation/Home/HomeScreenViewModel.dart';
class HomeTabViewModel extends Cubit<BaseCubitState>{
GetMoviesDataUseCase getMoviesDataUseCase ;
GetMoviesByGenreUseCase getMoviesByGenreUseCase ;
HomeTabViewModel(this.getMoviesDataUseCase , this.getMoviesByGenreUseCase):super(LoadingState());
DataProvider? provider ;
HomeScreenViewModel? homeScreenViewModel;
Future<void> readData()async{
emit(LoadingState());
if(provider!.movies != null){
emit(MoviesLoadedState(provider!.movies,provider!.actionMovies, provider!.animationMovies, provider!.crimeMovies, provider!.dramaMovies));
} else {
try{
final response = await Future.wait([
getMoviesDataUseCase.doWork(),
getMoviesByGenreUseCase.doWork("Drama"),
getMoviesByGenreUseCase.doWork("Action"),
getMoviesByGenreUseCase.doWork("Crime"),
getMoviesByGenreUseCase.doWork("animation")
]);
var movies = response[0];
var dramaMovies = response[1];
var actionMovies = response[2] ;
var crimeMovies = response[3];
var animationMovies = response[4];
provider!.movies = movies;
provider!.dramaMovies = dramaMovies;
provider!.actionMovies = actionMovies;
provider!.crimeMovies = crimeMovies;
provider!.animationMovies = animationMovies;
if(movies == null || dramaMovies == null || animationMovies == null || actionMovies == null ||crimeMovies == null){
emit(ErrorState("Couldn't Load The Data"));
}else{
emit(MoviesLoadedState(movies, actionMovies, animationMovies, crimeMovies, dramaMovies));
}
}catch(e){
if(e is ServerException){
emit(ErrorState(e.error));
}else {
emit(ErrorState(e.toString()));
}
}
}
}
Future<void> refreshData()async{
emit(RefreshState());
try{
final response = await Future.wait([
getMoviesDataUseCase.doWork(),
getMoviesByGenreUseCase.doWork("Drama"),
getMoviesByGenreUseCase.doWork("Action"),
getMoviesByGenreUseCase.doWork("Crime"),
getMoviesByGenreUseCase.doWork("animation")
]);
var movies = response[0];
var dramaMovies = response[1];
var actionMovies = response[2] ;
var crimeMovies = response[3];
var animationMovies = response[4];
provider!.movies = movies;
provider!.dramaMovies = dramaMovies;
provider!.actionMovies = actionMovies;
provider!.crimeMovies = crimeMovies;
provider!.animationMovies = animationMovies;
if(movies == null || dramaMovies == null || animationMovies == null || actionMovies == null ||crimeMovies == null){
emit(ErrorState("Couldn't Load The Data"));
}else{
emit(MoviesLoadedState(movies, actionMovies, animationMovies, crimeMovies, dramaMovies));
}
}catch(e){
if(e is ServerException){
emit(ErrorState(e.error));
}else {
emit(ErrorState(e.toString()));
}
}
}
void setStateToLoading(){
emit(LoadingState());
}
void goToDetailsScreen(num movie){
emit(MovieDetailsAction(movie));
}
}
class RefreshState extends BaseCubitState{}
class MoviesLoadedState extends BaseCubitState {
List<Movies>? movies ;
List<Movies>? actionMovies ;
List<Movies>? dramaMovies ;
List<Movies>? crimeMovies ;
List<Movies>? animationMovies ;
MoviesLoadedState(this.movies , this.actionMovies , this.animationMovies , this.crimeMovies , this.dramaMovies);
}
| 0 |
mirrored_repositories/Movies/lib/Presentation/Home/Tabs/Home | mirrored_repositories/Movies/lib/Presentation/Home/Tabs/Home/Widgets/MyPlaceHolder.dart | import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:mymoviesapp/Core/Theme/Theme.dart';
// placeholder to show until the data be loaded
class MyPlaceHolder extends StatelessWidget {
List<int> placeholders = [1,1,1,1,1,1,1,1,];
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: [
Stack(
children: [
PlaceHolderContainer(
height: MediaQuery.of(context).size.height *0.9,
width: MediaQuery.of(context).size.width
),
Positioned.fill(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CarouselSlider(
items: placeholders.map((movie) => Image.asset('assets/images/loading.jpg')).toList(),
options: CarouselOptions(
height:300,
viewportFraction: 0.5,
initialPage: 0,
autoPlayInterval: const Duration(seconds: 1),
enableInfiniteScroll: true,
enlargeCenterPage: true,
autoPlay: false,
enlargeFactor: 0.32,
scrollDirection: Axis.horizontal,
),
),
],
),
)
],
),
],
),
);
}
}
class PlaceHolderContainer extends StatelessWidget {
double height ;
double width ;
PlaceHolderContainer({
required this.height,
required this.width,
});
@override
Widget build(BuildContext context) {
return Container(
width: width,
height: height,
decoration: BoxDecoration(
gradient:const LinearGradient(
colors: [
MyTheme.gold,
MyTheme.backGroundColor,
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
borderRadius: BorderRadius.circular(20),
),
child: const Center(
child: CircularProgressIndicator(
color: Colors.white,
),
),
);
}
}
| 0 |
mirrored_repositories/Movies/lib/Presentation/Home/Tabs/Home | mirrored_repositories/Movies/lib/Presentation/Home/Tabs/Home/Widgets/TopRatedMovies.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:mymoviesapp/Domain/Models/Movies/Movies.dart';
import 'package:mymoviesapp/Core/Theme/Theme.dart';
import 'package:mymoviesapp/Presentation/Global%20Widgets/PosterImage.dart';
class TopRatedMovies extends StatefulWidget {
List<Movies> movies;
Function goToDetailsScreen ;
TopRatedMovies({required this.movies , required this.goToDetailsScreen});
@override
State<TopRatedMovies> createState() => _TopRatedMoviesState();
}
class _TopRatedMoviesState extends State<TopRatedMovies> {
String image = '';
@override
void initState() {
super.initState();
image = widget.movies[0].largeCoverImage!;
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
Image.asset('assets/images/loading.jpg',),
// image to show in the background it the same image of the poster
CachedNetworkImage(
imageUrl: image,
imageBuilder: (context, imageProvider) => Image.network(image),
width: MediaQuery.of(context).size.width,
placeholder: (context, url) => Image.asset('assets/images/loading.jpg',),
errorWidget: (context, url, error) => ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.asset('assets/images/error.png'),
),
),
// gradient layer above the image
Positioned.fill(
child: Container(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
height: double.infinity,//MediaQuery.of(context).size.height * 0.6,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
MyTheme.backGroundColor.withOpacity(1),
MyTheme.backGroundColor.withOpacity(0.5),
],
begin: Alignment.bottomCenter,
end: Alignment.topCenter
)
),
),
),
// the poster list (the slider)
Positioned.fill(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/images/Available Now.png',
width: MediaQuery.of(context).size.width * 0.6,
),
CarouselSlider(
items: widget.movies.map((movie) => PosterImage(movie: movie , goToDetailsScreen: widget.goToDetailsScreen,)).toList(),
options: CarouselOptions(
height:300,
viewportFraction: 0.5,
initialPage: 0,
onPageChanged: (index, reason) {
setState(() {image = widget.movies[index].largeCoverImage!;});
},
autoPlayInterval: const Duration(seconds: 1),
enableInfiniteScroll: true,
enlargeCenterPage: true,
autoPlay: false,
enlargeFactor: 0.32,
scrollDirection: Axis.horizontal,
),
),
Image.asset(
'assets/images/Watch Now.png',
width: MediaQuery.of(context).size.width * 0.7,
),
],
),
)
]
);
}
}
| 0 |
mirrored_repositories/Movies/lib/Presentation/Home/Tabs | mirrored_repositories/Movies/lib/Presentation/Home/Tabs/Profile/ProfileTabVIew.dart | import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Core/DI/di.dart';
import 'package:mymoviesapp/Core/Providers/AppConfigProvieder.dart';
import 'package:mymoviesapp/Core/Providers/DataProvider.dart';
import 'package:mymoviesapp/Core/Theme/Theme.dart';
import 'package:mymoviesapp/Core/utils/DialogUtils.dart';
import 'package:mymoviesapp/Domain/UseCase/getHistoryUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/getUserDataUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/getWishListDataUseCase.dart';
import 'package:mymoviesapp/Presentation/Global%20Widgets/PosterImage.dart';
import 'package:mymoviesapp/Presentation/Home/HomeScreenViewModel.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/EditProfileScreen/EditProfileView.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/MovieDetails/MovieDetailsView.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Profile/ProfileTabViewModel.dart';
import 'package:mymoviesapp/Presentation/Welcome/WelcomeScreen.dart';
import 'package:provider/provider.dart';
class ProfileTabView extends StatefulWidget {
static const String routeName = 'ProfileTab';
static const String path = '/ProfileTab';
@override
State<ProfileTabView> createState() => _ProfileTabViewState();
}
class _ProfileTabViewState extends State<ProfileTabView> {
ProfileTabViewModel viewModel = ProfileTabViewModel(
GetUserDataUseCase(injectUserRepository()),
GetHistoryUseCase(injectMoviesRepository()),
GetWishListDataUseCase(injectMoviesRepository()),
);
ScrollController controller = ScrollController();
@override
void initState() {
super.initState();
viewModel.provider = Provider.of<AppConfigProvider>(context, listen: false);
viewModel.dataProvider = Provider.of<DataProvider>(context, listen: false);
viewModel.homeScreenViewModel = Provider.of<HomeScreenViewModel>(context, listen: false);
viewModel.getData();
}
@override
void dispose() {
super.dispose();
viewModel.dataProvider = null;
viewModel.provider = null;
}
@override
Widget build(BuildContext context) {
return BlocProvider<ProfileTabViewModel>(
create: (context) => viewModel,
child: BlocConsumer<ProfileTabViewModel, BaseCubitState>(
listener: (context, state) {
if (state is MovieDetailsAction) {
viewModel.homeScreenViewModel!.setSelectedIndex(9);
context.pushNamed(MovieDetailsScreen.routeName, extra: state.movie);
} else if (state is ShowQuestionMessageState) {
MyDialogUtils.showQuestionMessage(
context: context,
message: state.message,
posActionTitle: "Ok",
posAction: viewModel.signOut,
negativeActionTitle: "Cancel");
} else if (state is SignOutAction) {
context.goNamed(WelcomeScreen.routeName);
}else if (state is EditProfileAction){
GoRouter.of(context).pushNamed( EditProfileView.routeName , extra:state.user );
viewModel.homeScreenViewModel!.setSelectedIndex(9);
}
},
buildWhen: (previous, current) {
if (previous is LoadingState && current is DataLoadedState) {
return true;
} else {
return false;
}
},
builder: (context, state) {
if (state is LoadingState) {
return const Center(
child: CircularProgressIndicator(
color: MyTheme.gold,
),
);
} else if (state is ErrorState) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
state.errorMessage,
style: const TextStyle(color: Colors.white),
),
ElevatedButton(
onPressed: () {
viewModel.getData();
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(MyTheme.gold),
),
child: const Text("Try Again"))
],
);
} else if (state is DataLoadedState) {
return DefaultTabController(
length: 2,
initialIndex: 0,
child: NestedScrollView(
headerSliverBuilder: (context, innerBoxIsScrolled) => [
SliverAppBar(
toolbarHeight: 250,
backgroundColor: MyTheme.blackThree,
title: Container(
height: 250,
child: Column(
children: [
Expanded(
child: Row(
children: [
Expanded(
flex: 2,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(state.user.image),
Text(
state.user.name,
style: Theme.of(context)
.textTheme
.displaySmall,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
maxLines: 1,
)
],
),
),
Expanded(
flex: 3,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceAround,
children: [
Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Text(
state.wishlistMovies.length
.toString(),
style: Theme.of(context)
.textTheme
.displayMedium,
),
Text(
"Wish List",
style: Theme.of(context)
.textTheme
.headlineMedium,
)
],
),
Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Text(
state.historyMovies.length
.toString(),
style: Theme.of(context)
.textTheme
.displayMedium,
),
Text(
"History",
style: Theme.of(context)
.textTheme
.headlineMedium,
)
],
),
],
))
],
)),
Row(
children: [
Expanded(
child: ElevatedButton(
onPressed: (){
viewModel.goToEditProfileScreen(state.user);
},
style: ButtonStyle(
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
)),
backgroundColor:
MaterialStateProperty.all(
MyTheme.gold),
),
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Text(
"Edit Profile",
style: Theme.of(context)
.textTheme
.displaySmall,
),
),
),
),
const SizedBox(
width: 15,
),
ElevatedButton(
onPressed: () {
viewModel.onSignOutPress("Are You Sure You Want To Sign Out");
},
style: ButtonStyle(
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
)),
backgroundColor:
MaterialStateProperty.all(Colors.red),
),
child: Padding(
padding: const EdgeInsets.all(5.0),
child:Row(
children: [
Text("Exit" , style: Theme.of(context).textTheme.displaySmall,),
SizedBox(width: 5,),
Icon(EvaIcons.logOut)
],
),
),
),
],
),
],
),
),
pinned: true,
floating: true,
leading: Container(),
leadingWidth: 0,
forceElevated: innerBoxIsScrolled,
bottom: PreferredSize(
preferredSize: Size.fromHeight(90),
child: TabBar(
indicatorColor: MyTheme.gold,
tabs: [
Padding(
padding: const EdgeInsets.all(15.0),
child: Column(
children: [
Icon(
EvaIcons.list,
color: MyTheme.gold,
),
Text(
"Favorite List ",
style: Theme.of(context)
.textTheme
.displaySmall,
),
],
),
),
Padding(
padding: const EdgeInsets.all(15.0),
child: Column(
children: [
Icon(
EvaIcons.archive,
color: MyTheme.gold,
),
Text(
"History ",
style: Theme.of(context)
.textTheme
.displaySmall,
),
],
),
)
],
),
))
],
body: Column(
children: [
SizedBox(
height: 20,
),
Expanded(
child: TabBarView(
children: [
state.wishlistMovies.isEmpty
? Center(
child: Image.asset(
"assets/images/Empty.png",
width: 100,
),
)
: GridView.builder(
shrinkWrap: true,
// physics: const BouncingScrollPhysics(),
padding:
const EdgeInsets.symmetric(horizontal: 20),
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
childAspectRatio: 0.65),
itemBuilder: (context, index) => PosterImage(
movie: state.wishlistMovies[index],
goToDetailsScreen:
viewModel.goToDetailsScreen,
),
itemCount: state.wishlistMovies.length,
),
state.historyMovies.isEmpty
? Center(
child: Image.asset(
"assets/images/Empty.png",
width: 100,
),
)
: GridView.builder(
shrinkWrap: true,
padding:
const EdgeInsets.symmetric(horizontal: 20),
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
childAspectRatio: 0.65),
itemBuilder: (context, index) => PosterImage(
movie: state.historyMovies[index],
goToDetailsScreen:
viewModel.goToDetailsScreen,
),
itemCount: state.historyMovies.length,
)
],
))
],
),
),
);
} else {
return Container();
}
},
),
);
}
}
| 0 |
mirrored_repositories/Movies/lib/Presentation/Home/Tabs | mirrored_repositories/Movies/lib/Presentation/Home/Tabs/Profile/ProfileTabViewModel.dart | import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mymoviesapp/Core/Base/BaseCubitState.dart';
import 'package:mymoviesapp/Core/Providers/AppConfigProvieder.dart';
import 'package:mymoviesapp/Core/Providers/DataProvider.dart';
import 'package:mymoviesapp/Domain/Exceptions/FirebaseDatabaseExeption.dart';
import 'package:mymoviesapp/Domain/Models/Movies/Movies.dart';
import 'package:mymoviesapp/Domain/Models/User/User.dart';
import 'package:mymoviesapp/Domain/UseCase/getHistoryUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/getUserDataUseCase.dart';
import 'package:mymoviesapp/Domain/UseCase/getWishListDataUseCase.dart';
import 'package:mymoviesapp/Presentation/Home/HomeScreenViewModel.dart';
import 'package:shared_preferences/shared_preferences.dart';
class ProfileTabViewModel extends Cubit<BaseCubitState>{
GetUserDataUseCase getUserDataUseCase;
GetHistoryUseCase getHistoryUseCase;
GetWishListDataUseCase getWishListDataUseCase;
ProfileTabViewModel(this.getUserDataUseCase , this.getHistoryUseCase , this.getWishListDataUseCase):super(LoadingState());
HomeScreenViewModel? homeScreenViewModel ;
AppConfigProvider? provider;
DataProvider? dataProvider;
void getData()async{
emit(LoadingState());
try{
String uid = await provider!.getUid();
var userResponse = await getUserDataUseCase.invoke(uid);
var moviesResponse = await getHistoryUseCase.invoke(uid);
var wishListResponse = await getWishListDataUseCase.invoke(uid);
dataProvider!.watchHistory = moviesResponse;
dataProvider!.wishList= wishListResponse;
emit(DataLoadedState(userResponse , dataProvider!.watchHistory , dataProvider!.wishList));
}catch (e){
if(e is FirebaseDatabaseException){
emit(ErrorState(e.errorMessage));
}else {
emit(ErrorState(e.toString()));
}
}
}
void goToDetailsScreen(num movie){
emit(MovieDetailsAction(movie));
}
void onSignOutPress(String message){
emit(ShowQuestionMessageState(message));
}
void signOut()async{
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setString('uid', '');
emit(SignOutAction());
}
void goToEditProfileScreen(Users user){
emit(EditProfileAction(user));
}
}
class DataLoadedState extends BaseCubitState{
Users user;
List<Movies> historyMovies;
List<Movies> wishlistMovies;
DataLoadedState(this.user , this.historyMovies , this.wishlistMovies);
}
class ShowQuestionMessageState extends BaseCubitState{
String message;
ShowQuestionMessageState(this.message);
}
class SignOutAction extends BaseCubitState{}
class EditProfileAction extends BaseCubitState{
Users user;
EditProfileAction(this.user);
}
| 0 |
mirrored_repositories/Movies/lib/Presentation | mirrored_repositories/Movies/lib/Presentation/Welcome/WelcomeScreen.dart | import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:mymoviesapp/Core/Theme/Theme.dart';
import 'package:mymoviesapp/Presentation/Home/HomeScreenView.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Home/HomeTabView.dart';
import 'package:mymoviesapp/Presentation/Home/Tabs/Search/SearchTabView.dart';
import 'package:mymoviesapp/Presentation/Login/LoginView.dart';
import 'package:mymoviesapp/Presentation/Registration/RegistrationView.dart';
class WelcomeScreen extends StatelessWidget {
static const String routeName = 'welcomeScreen';
static const String path = '/';
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Row(),
Image.asset('assets/images/Logo.png'),
const Text("Welcome" , style: TextStyle(
color: Colors.white ,
fontWeight: FontWeight.w900,
fontSize: 35,
letterSpacing: 3
),),
const SizedBox(height: 30,),
SizedBox(
width: MediaQuery.of(context).size.width * 0.7,
child: ElevatedButton(
onPressed: (){
GoRouter.of(context).goNamed(LoginScreen.routeName);
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(MyTheme.gold),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
side: const BorderSide(width: 5 , color: MyTheme.gold)
)
),
),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
"Login",
style: Theme.of(context).textTheme.displayMedium!,
),
)
),
),
const SizedBox(height: 20,),
SizedBox(
width: MediaQuery.of(context).size.width * 0.7,
child: ElevatedButton(
onPressed: (){
GoRouter.of(context).goNamed(RegistrationScreen.routeName);
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(MyTheme.backGroundColor),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
side: const BorderSide(width: 2 , color: MyTheme.gold)
)
),
),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
"Sign Up",
style: Theme.of(context).textTheme.displayMedium!,
),
)
),
),
],
),
);
}
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.