repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/Clima-Weather-App/lib | mirrored_repositories/Clima-Weather-App/lib/services/location.dart | import 'package:geolocator/geolocator.dart';
class Location {
double latitude;
double longitude;
Future getCurrentLocation() async {
try {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.low);
latitude = position.latitude;
longitude = position.longitude;
} catch (e) {
print(e);
}
}
}
| 0 |
mirrored_repositories/Clima-Weather-App/lib | mirrored_repositories/Clima-Weather-App/lib/services/weather.dart | import 'package:clima/services/location.dart';
import 'package:clima/services/networking.dart';
const apiKey = 'fbf063cf9aba0938456dbe03498e5121';
const openWeatherMapURL = 'https://api.openweathermap.org/data/2.5/weather';
class WeatherModel {
Future<dynamic> getCityWeather(String cityname) async {
var url = '$openWeatherMapURL?q=$cityname&appid=$apiKey&units=metric';
NetworkHelper networkHelper = NetworkHelper(url);
var weatherData = await networkHelper.getData();
return weatherData;
}
Future<dynamic> getLocationWeather() async {
Location location = Location();
await location.getCurrentLocation();
NetworkHelper networkHelper = NetworkHelper(
'$openWeatherMapURL?lat=${location.latitude}&lon=${location.longitude}&appid=$apiKey&units=metric');
var weatherData = await networkHelper.getData();
return weatherData;
}
String getWeatherIcon(int condition) {
if (condition < 300) {
return '🌩';
} else if (condition < 400) {
return '🌧';
} else if (condition < 600) {
return '☔️';
} else if (condition < 700) {
return '☃️';
} else if (condition < 800) {
return '🌫';
} else if (condition == 800) {
return '☀️';
} else if (condition <= 804) {
return '☁️';
} else {
return '🤷';
}
}
String getMessage(int temp) {
if (temp > 25) {
return 'It\'s 🍦 time';
} else if (temp > 20) {
return 'Time for shorts and 👕';
} else if (temp < 10) {
return 'You\'ll need 🧣 and 🧤';
} else {
return 'Bring a 🧥 just in case';
}
}
}
| 0 |
mirrored_repositories/Clima-Weather-App/lib | mirrored_repositories/Clima-Weather-App/lib/screens/city_screen.dart | import 'package:flutter/material.dart';
import 'package:clima/utilities/constants.dart';
class CityScreen extends StatefulWidget {
@override
_CityScreenState createState() => _CityScreenState();
}
class _CityScreenState extends State<CityScreen> {
String cityName;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('images/city_background.jpg'),
fit: BoxFit.cover,
),
),
constraints: BoxConstraints.expand(),
child: SafeArea(
child: Column(
children: <Widget>[
Align(
alignment: Alignment.topLeft,
child: TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Icon(
Icons.arrow_back_ios,
color: Colors.white,
size: 50.0,
),
),
),
Container(
padding: EdgeInsets.all(20.0),
child: TextField(
style: TextStyle(
color: Colors.white,
),
decoration: kTextFieldInputDecoration,
onChanged: (value) {
cityName = value;
print(cityName);
},
),
),
TextButton(
onPressed: () {
Navigator.pop(context, cityName);
},
child: Text(
'Get Weather',
style: kButtonTextStyle,
),
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Clima-Weather-App/lib | mirrored_repositories/Clima-Weather-App/lib/screens/loading_screen.dart | //import 'dart:js';
import 'package:clima/screens/location_screen.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:clima/services/weather.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:clima/utilities/constants.dart';
//F:\pal\Document\Flutter Projects\Clima-Flutter-master\lib\services\location.dart
class LoadingScreen extends StatefulWidget {
@override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
@override
void initState() {
super.initState();
getLocationData();
}
void getLocationData() async {
WeatherModel weatherModel = WeatherModel();
var weatherData = await weatherModel.getLocationWeather();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return LocationScreen(
locationWeather: weatherData,
);
},
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: spinkit,
),
);
}
}
//fbf063cf9aba0938456dbe03498e5121
| 0 |
mirrored_repositories/Clima-Weather-App/lib | mirrored_repositories/Clima-Weather-App/lib/screens/location_screen.dart | //import 'dart:ffi';
import 'package:clima/screens/city_screen.dart';
import 'package:flutter/material.dart';
import 'package:clima/utilities/constants.dart';
import 'package:clima/services/weather.dart';
class LocationScreen extends StatefulWidget {
LocationScreen({this.locationWeather});
final locationWeather;
@override
_LocationScreenState createState() => _LocationScreenState();
}
class _LocationScreenState extends State<LocationScreen> {
WeatherModel weather = WeatherModel();
int temperature;
String weatherIcon;
String weatherMessage;
var cityname;
//var weatherIcon = weather.getWeatherIcon(condition);
@override
void initState() {
super.initState();
print(widget.locationWeather);
updateUI(widget.locationWeather);
}
void updateUI(dynamic weatherData) {
setState(() {
if (weatherData == null) {
temperature = 0;
weatherMessage = 'unable to get location';
weatherIcon = 'ERROR';
cityname = '';
return;
}
double temp = weatherData['main']['temp'].toDouble();
temperature = temp.toInt();
var condition = weatherData['weather'][0]['id'];
weatherIcon = weather.getWeatherIcon(condition);
weatherMessage = weather.getMessage(temperature);
cityname = weatherData['name'];
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('images/location_background.jpg'),
fit: BoxFit.cover,
colorFilter: ColorFilter.mode(
Colors.white.withOpacity(0.8), BlendMode.dstATop),
),
),
constraints: BoxConstraints.expand(),
child: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
TextButton(
onPressed: () async {
var weatherData = await weather.getLocationWeather();
updateUI(weatherData);
},
child: Icon(
Icons.near_me,
size: 50.0,
color: Colors.white,
),
),
TextButton(
onPressed: () async {
print('citybutton');
var typedName = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return CityScreen();
},
),
);
print(typedName);
if (cityname != null) {
var weatherData =
await weather.getCityWeather(typedName);
updateUI(weatherData);
}
},
child: Icon(
Icons.location_city,
size: 50.0,
color: Colors.white,
),
),
],
),
Padding(
padding: EdgeInsets.only(left: 15.0),
child: Row(
children: <Widget>[
Text(
'$temperature' + '°',
style: kTempTextStyle,
),
Expanded(
child: Text(
weatherIcon,
style: kConditionTextStyle,
),
),
],
),
),
Padding(
padding: EdgeInsets.only(right: 15.0),
child: Text(
'$weatherMessage in $cityname',
textAlign: TextAlign.right,
style: kMessageTextStyle,
),
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding | mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/constants.dart | import 'package:flutter/material.dart';
const appName = 'SunGlasses Show';
const emailDescription = '[email protected]';
final drawerMenuItems = ['Settings', 'About Us'];
const secondaryColor = Color(0xFFFE6D8E);
const backgroundColor = Color(0xFFF8F8F8F8);
const textColorActive = Color.fromARGB(0xDD, 0x00, 0x00, 0x00);
const textColorInActive = Color.fromARGB(0x72, 0x00, 0x00, 0x00);
const itemCategories = ['Movies', 'Tv Shows'];
const itemCardRatio = (2 / 3);
const itemRadiusSm = 8.0;
const itemRadiusMd = 10.0;
const itemRadiusXl = 12.0;
const menuIconPath = 'assets/icons/menu.svg';
const edgeInsetsSm = 12.0;
const edgeInsetsMd = 20.0;
| 0 |
mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding | mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/main.dart | import 'package:flutter/material.dart';
import 'package:sunglasses_show/screens/home/home_screen.dart';
import 'constants.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: appName,
theme: ThemeData(
fontFamily: 'Manrope',
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomeScreen(),
);
}
}
| 0 |
mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib | mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/model/movie.dart | class Movie {
String title;
String posterUrl;
int year;
String genres;
String duration;
String rate;
double rating;
String releasedAt;
String language;
String synopsis;
String director;
Movie(
this.title,
this.posterUrl,
this.year,
this.genres,
this.duration,
this.rate,
this.rating,
this.releasedAt,
this.language,
this.synopsis,
this.director);
}
| 0 |
mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib | mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/model/tv_show.dart | class TVShow {
String title;
String posterUrl;
int year;
String genres;
String duration;
String rate;
double rating;
String releasedAt;
String language;
String synopsis;
String creator;
TVShow(
this.title,
this.posterUrl,
this.year,
this.genres,
this.duration,
this.rate,
this.rating,
this.releasedAt,
this.language,
this.synopsis,
this.creator);
}
| 0 |
mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib | mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/utils/data_utils.dart | import 'package:sunglasses_show/model/movie.dart';
import 'package:sunglasses_show/model/tv_show.dart';
List<Movie> getMovies() => <Movie>[
Movie(
"A Star Is Born",
"assets/images/movies/poster_overlord.jpg",
2017,
"Drama, Romance, Music",
"2h 16m",
"R",
7.2,
"October 3, 2018",
"US",
"Seasoned musician Jackson Maine discovers — and falls in love with — struggling artist Ally. She has just about given up on her dream to make it big as a singer — until Jack coaxes her into the spotlight. But even as Ally's career takes off, the personal side of their relationship is breaking down, as Jack fights an ongoing battle with his own internal demons.",
"Bradley Cooper"),
Movie(
"Alita: Battle Angel",
"assets/images/movies/poster_alita.jpg",
2019,
"Action, Science Fiction, Adventure",
"2h 2m",
"PG-13",
7.7,
"January 31, 2019",
"US",
"When Alita awakens with no memory of who she is in a future world she does not recognize, she is taken in by Ido, a compassionate doctor who realizes that somewhere in this abandoned cyborg shell is the heart and soul of a young woman with an extraordinary past.",
"Robert Rodriguez"),
Movie(
"Aquaman",
"assets/images/movies/poster_aquaman.jpg",
2018,
"Action, Adventure, Fantasy",
"2h 23m",
"PG-13",
6.9,
"December 7, 2018",
"US",
"Once home to the most advanced civilization on Earth, Atlantis is now an underwater kingdom ruled by the power-hungry King Orm. With a vast army at his disposal, Orm plans to conquer the remaining oceanic people and then the surface world. Standing in his way is Arthur Curry, Orm's half-human, half-Atlantean brother and true heir to the throne.",
"James Wan"),
Movie(
"Bohemian Rhapsody",
"assets/images/movies/poster_bohemian.jpg",
2018,
"Music, Drama, History",
"2h 23m",
"PG-13",
8.0,
"October 24, 2018",
"US",
"Singer Freddie Mercury, guitarist Brian May, drummer Roger Taylor and bass guitarist John Deacon take the music world by storm when they form the rock 'n' roll band Queen in 1970. Hit songs become instant classics. When Mercury's increasingly wild lifestyle starts to spiral out of control, Queen soon faces its greatest challenge yet – finding a way to keep the band together amid the success and excess.",
"Bryan Singer"),
Movie(
"Cold Pursuit",
"assets/images/movies/poster_cold_pursuit.jpg",
2019,
"Action, Crime, Thriller",
"1h 59m",
"PG-13",
5.7,
"February 7, 2019",
"US",
"The quiet family life of Nels Coxman, a snowplow driver, is upended after his son's murder. Nels begins a vengeful hunt for Viking, the drug lord he holds responsible for the killing, eliminating Viking's associates one by one. As Nels draws closer to Viking, his actions bring even more unexpected and violent consequences, as he proves that revenge is all in the execution.",
"Hans Petter Moland"),
Movie(
"Creed II",
"assets/images/movies/poster_creed.jpg",
2018,
"Drama",
"2h 10m",
"PG-13",
6.9,
"November 21, 2018",
"US",
"Between personal obligations and training for his next big fight against an opponent with ties to his family's past, Adonis Creed is up against the challenge of his life.",
"Steven Caple Jr."),
Movie(
"Fantastic Beast: The Crime of Grindelwald",
"assets/images/movies/poster_crimes.jpg",
2018,
"Adventure, Fantasy, Drama",
"2h 14m",
"PG-13",
6.9,
"November 14, 2018",
"US",
"Gellert Grindelwald has escaped imprisonment and has begun gathering followers to his cause—elevating wizards above all non-magical beings. The only one capable of putting a stop to him is the wizard he once called his closest friend, Albus Dumbledore. However, Dumbledore will need to seek help from the wizard who had thwarted Grindelwald once before, his former student Newt Scamander, who agrees to help, unaware of the dangers that lie ahead. Lines are drawn as love and loyalty are tested, even among the truest friends and family, in an increasingly divided wizarding world.",
"David Yates"),
Movie(
"Glass",
"assets/images/movies/poster_glass.jpg",
2019,
"Thriller, Drama, Science Fiction",
"2h 9m",
"PG-13",
6.7,
"January 16, 2019",
"US",
"In a series of escalating encounters, former security guard David Dunn uses his supernatural abilities to track Kevin Wendell Crumb, a disturbed man who has twenty-four personalities. Meanwhile, the shadowy presence of Elijah Price emerges as an orchestrator who holds secrets critical to both men.",
"M. Night Shyamalan"),
Movie(
"How to Train Your Dragon",
"assets/images/movies/poster_how_to_train.jpg",
2010,
"Fantasy, Adventure, Animation, Family",
"1h 38m",
"PG",
7.8,
"March 10, 2010",
"US",
"As the son of a Viking leader on the cusp of manhood, shy Hiccup Horrendous Haddock III faces a rite of passage: he must kill a dragon to prove his warrior mettle. But after downing a feared dragon, he realizes that he no longer wants to destroy it, and instead befriends the beast – which he names Toothless – much to the chagrin of his warrior father.",
"Dean DeBlois"),
Movie(
"Avengers: Infinity War",
"assets/images/movies/poster_infinity_war.jpg",
2018,
"Adventure, Action, Science Fiction",
"2h 29m",
"PG",
8.3,
"April 25, 2018",
"US",
"As the Avengers and their allies have continued to protect the world from threats too large for any one hero to handle, a new danger has emerged from the cosmic shadows: Thanos. A despot of intergalactic infamy, his goal is to collect all six Infinity Stones, artifacts of unimaginable power, and use them to inflict his twisted will on all of reality. Everything the Avengers have fought for has led up to this moment - the fate of Earth and existence itself has never been more uncertain.",
"Joe Russo"),
Movie(
"Master Z: Ip Man Legacy",
"assets/images/movies/poster_master_z.jpg",
2018,
"Action",
"1h 47m",
"PG-13",
5.9,
"December 20, 2018",
"US",
"Following his defeat by Master Ip, Cheung Tin Chi tries to make a life with his young son in Hong Kong, waiting tables at a bar that caters to expats. But it's not long before the mix of foreigners, money, and triad leaders draw him once again to the fight.",
"Yuen Woo-ping"),
Movie(
"Mortal Engines",
"assets/images/movies/poster_mortal_engines.jpg",
2018,
"Adventure, Science Fiction",
"2h 9m",
"PG-13",
6.1,
"November 27, 2018",
"US",
"Many thousands of years in the future, Earth’s cities roam the globe on huge wheels, devouring each other in a struggle for ever diminishing resources. On one of these massive traction cities, the old London, Tom Natsworthy has an unexpected encounter with a mysterious young woman from the wastelands who will change the course of his life forever.",
"Christian Rivers"),
Movie(
"Overlord",
"assets/images/movies/poster_overlord.jpg",
2018,
"Horror, War, Science Fiction",
"1h 50m",
"R",
6.1,
"November 1, 2018",
"US",
"France, June 1944. On the eve of D-Day, some American paratroopers fall behind enemy lines after their aircraft crashes while on a mission to destroy a radio tower in a small village near the beaches of Normandy. After reaching their target, the surviving paratroopers realise that, in addition to fighting the Nazi troops that patrol the village, they also must fight against something else.",
"Julius Avery"),
Movie(
"Ralph Breaks the Internet",
"assets/images/movies/poster_ralph.jpg",
2018,
"Family, Animation, Comedy, Adventure",
"1h 52m",
"PG",
7.2,
"November 20, 2018",
"US",
"Video game bad guy Ralph and fellow misfit Vanellope von Schweetz must risk it all by traveling to the World Wide Web in search of a replacement part to save Vanellope's video game, Sugar Rush. In way over their heads, Ralph and Vanellope rely on the citizens of the internet — the netizens — to help navigate their way, including an entrepreneur named Yesss, who is the head algorithm and the heart and soul of trend-making site BuzzzTube.",
"Phil Johnston"),
Movie(
"Robin Hood",
"assets/images/movies/poster_robin_hood.jpg",
2018,
"Adventure, Action, Thriller",
"1h 56m",
"PG-13",
5.9,
"November 21, 2018",
"US",
"A war-hardened Crusader and his Moorish commander mount an audacious revolt against the corrupt English crown.",
"Otto Bathurst"),
Movie(
"Spider-Man: Into the Spider-Verse",
"assets/images/movies/poster_spiderman.jpg",
2018,
"Action, Adventure, Animation, Science Fiction, Comedy",
"1h 57m",
"PG",
8.4,
"December 6, 2018",
"US",
"Miles Morales is juggling his life between being a high school student and being a spider-man. When Wilson 'Kingpin' Fisk uses a super collider, others from across the Spider-Verse are transported to this dimension.",
"Rodney Rothman"),
Movie(
"T-34",
"assets/images/movies/poster_t34.jpg",
2018,
"War, Action, Drama, History",
"2h 19m",
"PG",
6.4,
"December 27, 2018",
"RU",
"In 1944, a courageous group of Russian soldiers managed to escape from German captivity in a half-destroyed legendary T-34 tank. Those were the times of unforgettable bravery, fierce fighting, unbreakable love, and legendary miracles.",
"Alexey Sidorov"),
];
List<TVShow> getTVShows() => <TVShow>[
TVShow(
"Arrow",
"assets/images/tv_shows/poster_arrow.jpg",
2012,
"Crime, Drama, Mystery, Action & Adventure",
"42m",
"TV-14",
6.6,
"October 10, 2012",
"US",
"Spoiled billionaire playboy Oliver Queen is missing and presumed dead when his yacht is lost at sea. He returns five years later a changed man, determined to clean up the city as a hooded vigilante armed with a bow.",
"Greg Berlanti"),
TVShow(
"Doom Patrol",
"assets/images/tv_shows/poster_doom_patrol.jpg",
2019,
"Sci-Fi & Fantasy, Comedy, Drama",
"49m",
"TV-MA",
7.6,
"February 15, 2019",
"US",
"The Doom Patrol’s members each suffered horrible accidents that gave them superhuman abilities — but also left them scarred and disfigured. Traumatized and downtrodden, the team found purpose through The Chief, who brought them together to investigate the weirdest phenomena in existence — and to protect Earth from what they find.",
"Jeremy Carver"),
TVShow(
"Dragon Ball Z",
"assets/images/tv_shows/poster_dragon_ball.jpg",
1989,
"Animation, Sci-Fi & Fantasy, Action & Adventure",
"26m",
"TV-PG",
8.2,
"April 26, 1989",
"US",
"Five years have passed since the fight with Piccolo Jr., and Goku now has a son, Gohan. The peace is interrupted when an alien named Raditz arrives on Earth in a spacecraft and tracks down Goku, revealing to him that that they are members of a near-extinct warrior race called the Saiyans.",
"Akira Toriyama"),
TVShow(
"Fairy Tail: Phoenix Priestess",
"assets/images/tv_shows/poster_fairytail.jpg",
2012,
"Action, Adventure, Comedy, Fantasy, Animation",
"1h 26m",
"PG-13",
7.3,
"August 18, 2012",
"US",
"The film revolves around a mysterious girl named Éclair who appears before Fairy Tail, the world's most notorious wizard's guild. She lost all of her memories, except for the imperative that she must deliver two Phoenix Stones somewhere. The stones may spell the collapse of the magical world, and Natsu, Lucy, and the rest of the Fairy Tail guild are caught up in the intrigue.",
"Masaya Fujimori"),
TVShow(
"Family Guy",
"assets/images/tv_shows/poster_family_guy.jpg",
1999,
"Animation, Comedy",
"22m",
"TV-14",
7.0,
"January 31, 1999",
"US",
"Sick, twisted, politically incorrect and Freakin' Sweet animated series featuring the adventures of the dysfunctional Griffin family. Bumbling Peter and long-suffering Lois have three kids. Stewie (a brilliant but sadistic baby bent on killing his mother and taking over the world), Meg (the oldest, and is the most unpopular girl in town) and Chris (the middle kid, he's not very bright but has a passion for movies). The final member of the family is Brian - a talking dog and much more than a pet, he keeps Stewie in check whilst sipping Martinis and sorting through his own life issues.",
"Seth MacFarlane"),
TVShow(
"The Flash",
"assets/images/tv_shows/poster_flash.jpg",
2014,
"Drama, Sci-Fi & Fantasy",
"22m",
"TV-14",
7.7,
"October 7, 2014",
"US",
"After a particle accelerator causes a freak storm, CSI Investigator Barry Allen is struck by lightning and falls into a coma. Months later he awakens with the power of super speed, granting him the ability to move through Central City like an unseen guardian angel. Though initially excited by his newfound powers, Barry is shocked to discover he is not the only 'meta-human' who was created in the wake of the accelerator explosion -- and not everyone is using their new powers for good. Barry partners with S.T.A.R. Labs and dedicates his life to protect the innocent. For now, only a few close friends and associates know that Barry is literally the fastest man alive, but it won't be long before the world learns what Barry Allen has become...The Flash.",
"Greg Berlanti"),
TVShow(
"Gotham",
"assets/images/tv_shows/poster_gotham.jpg",
2014,
"Drama, Crime, Sci-Fi & Fantasy",
"43m",
"TV-14",
7.5,
"September 22, 2014",
"US",
"Everyone knows the name Commissioner Gordon. He is one of the crime world's greatest foes, a man whose reputation is synonymous with law and order. But what is known of Gordon's story and his rise from rookie detective to Police Commissioner? What did it take to navigate the multiple layers of corruption that secretly ruled Gotham City, the spawning ground of the world's most iconic villains? And what circumstances created them – the larger-than-life personas who would become Catwoman, The Penguin, The Riddler, Two-Face and The Joker?",
"Bruno Heller"),
TVShow(
"Grey's Anatomy",
"assets/images/tv_shows/poster_grey_anatomy.jpg",
2005,
"Drama",
"43m",
"TV-14",
8.2,
"March 27, 2005",
"US",
"Follows the personal and professional lives of a group of doctors at Seattle’s Grey Sloan Memorial Hospital.",
"Shonda Rhimes"),
TVShow(
"Hanna",
"assets/images/tv_shows/poster_hanna.jpg",
2019,
"Action & Adventure, Drama",
"50m",
"TV-14",
7.5,
"March 28, 2019",
"US",
"This thriller and coming-of-age drama follows the journey of an extraordinary young girl as she evades the relentless pursuit of an off-book CIA agent and tries to unearth the truth behind who she is. Based on the 2011 Joe Wright film.",
"David Farr"),
TVShow(
"Marvel's Iron Fist",
"assets/images/tv_shows/poster_iron_fist.jpg",
2017,
"Action & Adventure, Drama, Sci-Fi & Fantasy",
"55m",
"TV-MA",
6.6,
"March 17, 2017",
"US",
"Danny Rand resurfaces 15 years after being presumed dead. Now, with the power of the Iron Fist, he seeks to reclaim his past and fulfill his destiny.",
"Scott Buck"),
TVShow(
"Naruto Shippūden",
"assets/images/tv_shows/poster_naruto_shipudden.jpg",
2007,
"Animation, Action & Adventure, Sci-Fi & Fantasy",
"25m",
"TV-14",
8.6,
"February 15, 2007",
"US",
"Naruto Shippuuden is the continuation of the original animated TV series Naruto.The story revolves around an older and slightly more matured Uzumaki Naruto and his quest to save his friend Uchiha Sasuke from the grips of the snake-like Shinobi, Orochimaru. After 2 and a half years Naruto finally returns to his village of Konoha, and sets about putting his ambitions to work, though it will not be easy, as He has amassed a few (more dangerous) enemies, in the likes of the shinobi organization; Akatsuki.",
"Masashi Kishimoto"),
TVShow(
"NCIS",
"assets/images/tv_shows/poster_ncis.jpg",
2003,
"Crime, Action & Adventure, Drama",
"45m",
"TV-14",
7.4,
"September 23, 2003",
"US",
"From murder and espionage to terrorism and stolen submarines, a team of special agents investigates any crime that has a shred of evidence connected to Navy and Marine Corps personnel, regardless of rank or position.",
"Donald P. Bellisario"),
TVShow(
"Riverdale",
"assets/images/tv_shows/poster_riverdale.jpg",
2017,
"Mystery, Drama, Crime",
"45m",
"TV-14",
8.6,
"January 26, 2017",
"US",
"Set in the present, the series offers a bold, subversive take on Archie, Betty, Veronica and their friends, exploring the surreality of small-town life, the darkness and weirdness bubbling beneath Riverdale’s wholesome facade.",
"Roberto Aguirre-Sacasa"),
TVShow(
"Shameless",
"assets/images/tv_shows/poster_shameless.jpg",
2011,
"Drama, Comedy",
"57m",
"TV-MA",
8.6,
"January 9, 2011",
"US",
"Chicagoan Frank Gallagher is the proud single dad of six smart, industrious, independent kids, who without him would be... perhaps better off. When Frank's not at the bar spending what little money they have, he's passed out on the floor. But the kids have found ways to grow up in spite of him. They may not be like any family you know, but they make no apologies for being exactly who they are.",
"John Wells"),
TVShow(
"Supergirl",
"assets/images/tv_shows/poster_supergirl.jpg",
2015,
"Drama, Sci-Fi & Fantasy, Action & Adventure",
"42m",
"TV-MA",
7.2,
"October 26, 2015",
"US",
"Twenty-four-year-old Kara Zor-El, who was taken in by the Danvers family when she was 13 after being sent away from Krypton, must learn to embrace her powers after previously hiding them. The Danvers teach her to be careful with her powers, until she has to reveal them during an unexpected disaster, setting her on her journey of heroism.",
"Greg Berlanti"),
TVShow(
"Supernatural",
"assets/images/tv_shows/poster_supernatural.jpg",
2015,
"Drama, Mystery, Sci-Fi & Fantasy",
"45m",
"TV-14",
8.2,
"September 13, 2005",
"US",
"When they were boys, Sam and Dean Winchester lost their mother to a mysterious and demonic supernatural force. Subsequently, their father raised them to be soldiers. He taught them about the paranormal evil that lives in the dark corners and on the back roads of America ... and he taught them how to kill it. Now, the Winchester brothers crisscross the country in their '67 Chevy Impala, battling every kind of supernatural threat they encounter along the way.",
"Eric Kripke"),
TVShow(
"The Simpsons",
"assets/images/tv_shows/poster_the_simpson.jpg",
2015,
"Family, Animation, Comedy",
"22m",
"TV-PG",
7.8,
"December 17, 1989",
"US",
"Set in Springfield, the average American town, the show focuses on the antics and everyday adventures of the Simpson family; Homer, Marge, Bart, Lisa and Maggie, as well as a virtual cast of thousands. Since the beginning, the series has been a pop culture icon, attracting hundreds of celebrities to guest star. The show has also made name for itself in its fearless satirical take on politics, media and American life in general.",
"Matt Groening"),
TVShow(
"The Umbrella Academy",
"assets/images/tv_shows/poster_the_umbrella.jpg",
2019,
"Action & Adventure, Sci-Fi & Fantasy, Drama",
"55m",
"TV-MA",
8.7,
"February 15, 2019",
"US",
"A dysfunctional family of superheroes comes together to solve the mystery of their father's death, the threat of the apocalypse and more.",
"Steve Blackman"),
TVShow(
"The Walking Dead",
"assets/images/tv_shows/poster_the_walking_dead.jpg",
2019,
"Action & Adventure, Drama, Sci-Fi & Fantasy",
"42m",
"TV-MA",
8.1,
"October 31, 2010",
"US",
"Sheriff's deputy Rick Grimes awakens from a coma to find a post-apocalyptic world dominated by flesh-eating zombies. He sets out to find his family and encounters many other survivors along the way.",
"Frank Darabont"),
];
| 0 |
mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib | mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/utils/widget_utils.dart | import 'package:flutter/material.dart';
TextStyle buildTextStyleLight(double fontSize, Color color) =>
TextStyle(fontSize: fontSize, fontWeight: FontWeight.w300, color: color);
TextStyle buildTextStyleNormal(double fontSize, Color color) =>
TextStyle(fontSize: fontSize, fontWeight: FontWeight.w400, color: color);
TextStyle buildTextStyleMedium(double fontSize, Color color) =>
TextStyle(fontSize: fontSize, fontWeight: FontWeight.w500, color: color);
TextStyle buildTextStyleBold(double fontSize, Color color) =>
TextStyle(fontSize: fontSize, fontWeight: FontWeight.w700, color: color);
double getResponsiveDimension(BuildContext ctx, double initialValue) {
final width = MediaQuery.of(ctx).size.width;
if (width < 600) {
return initialValue + 4.0;
} else if (width < 900) {
return initialValue + 8.0;
} else {
return initialValue + 12.0;
}
}
double getResponsiveLongDimension(BuildContext ctx, double min, double max) {
var actualWidth = (MediaQuery.of(ctx).size.width / 6.0) + 32.0;
if (actualWidth < min) {
actualWidth = min;
} else if (actualWidth > max) {
actualWidth = max;
}
return actualWidth;
}
| 0 |
mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/screens | mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/screens/detail/detail_screen.dart | import 'package:flutter/material.dart';
import 'package:sunglasses_show/model/movie.dart';
import 'package:sunglasses_show/model/tv_show.dart';
import 'package:sunglasses_show/utils/widget_utils.dart';
import '../../constants.dart';
import 'components/body.dart';
class DetailScreen extends StatelessWidget {
final Movie? movie;
final TVShow? tvShow;
final bool isContentForMovies;
const DetailScreen(
{Key? key, required this.isContentForMovies, this.movie, this.tvShow})
: super(key: key);
@override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
final header = "Detail ${this.isContentForMovies ? 'Movie' : 'TV Show'}";
final title = isContentForMovies ? movie!.title : tvShow!.title;
final synopsis = isContentForMovies ? movie!.synopsis : tvShow!.synopsis;
final posterUrl = isContentForMovies ? movie!.posterUrl : tvShow!.posterUrl;
final genres = isContentForMovies ? movie!.genres : tvShow!.genres;
final year = isContentForMovies ? movie!.year : tvShow!.year;
final duration = isContentForMovies ? movie!.duration : tvShow!.duration;
final rating = isContentForMovies ? movie!.rating : tvShow!.rating;
final releasedAt =
isContentForMovies ? movie!.releasedAt : tvShow!.releasedAt;
final directorOrCreator =
isContentForMovies ? movie!.director : tvShow!.creator;
final language = isContentForMovies ? movie!.language : tvShow!.language;
final rate = isContentForMovies ? movie!.rate : tvShow!.rate;
return Scaffold(
backgroundColor: backgroundColor,
body: CustomScrollView(
physics: const BouncingScrollPhysics(),
slivers: [
SliverAppBar(
backgroundColor: secondaryColor,
expandedHeight: getHeaderHeight(screenWidth),
pinned: true,
stretch: true,
flexibleSpace: FlexibleSpaceBar(
title: Text(
header,
style: buildTextStyleMedium(18.0, Colors.white),
),
centerTitle: true,
stretchModes: [
StretchMode.zoomBackground,
StretchMode.fadeTitle,
],
background: Stack(
fit: StackFit.expand,
children: <Widget>[
Image.asset(
posterUrl,
fit: BoxFit.cover,
),
DecoratedBox(
decoration: buildOverlayBackground(),
),
],
),
),
),
SliverList(
delegate: SliverChildListDelegate([
Container(
margin: EdgeInsets.only(top: 12.0),
padding: EdgeInsets.symmetric(
horizontal: getPaddingBody(screenWidth),
),
child: Body(
title: title,
synopsis: synopsis,
posterUrl: posterUrl,
genres: genres,
rating: rating,
rate: rate,
year: year,
duration: duration,
releasedAt: releasedAt,
language: language,
directorOrCreator: directorOrCreator,
isContentForMovies: isContentForMovies,
),
),
]),
),
],
),
);
}
BoxDecoration buildOverlayBackground() {
return BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: <Color>[
Color(0xEE000000),
Color(0x88000000),
],
),
);
}
double getHeaderHeight(double screenWidth) {
if (screenWidth < 600) {
return 240.0;
} else if (screenWidth < 900) {
return 220.0;
} else {
return 210.0;
}
}
double getPaddingBody(double screenWidth) {
if (screenWidth < 600) {
return 8.0;
} else if (screenWidth < 900) {
return 80.0;
} else {
return 120.0;
}
}
double getCardFlexSize(double screenWidth) {
if (screenWidth < 600) {
return 3;
} else {
return 2;
}
}
}
| 0 |
mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/screens/detail | mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/screens/detail/components/body.dart | import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:sunglasses_show/utils/widget_utils.dart';
import '../../../constants.dart';
class Body extends StatelessWidget {
final title;
final synopsis;
final posterUrl;
final genres;
final year;
final duration;
final rating;
final releasedAt;
final directorOrCreator;
final language;
final rate;
final isContentForMovies;
const Body(
{Key? key,
this.title,
this.synopsis,
this.posterUrl,
this.genres,
this.year,
this.duration,
this.rating,
this.releasedAt,
this.directorOrCreator,
this.language,
this.rate,
this.isContentForMovies})
: super(key: key);
Widget showImage(context) {
var screenWidth = MediaQuery.of(context).size.width;
if (screenWidth > 900) {
return Expanded(
child: ClipRRect(
borderRadius: BorderRadius.circular(itemRadiusSm),
child: Image.asset(
posterUrl,
fit: BoxFit.cover,
),
),
);
} else {
return Container();
}
}
double getCardMargin(BuildContext context) {
var screenWidth = MediaQuery.of(context).size.width;
if (screenWidth > 900) {
return edgeInsetsSm;
} else {
return 0;
}
}
@override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
showImage(context),
Expanded(
flex: 2,
child: Card(
margin: EdgeInsets.only(left: getCardMargin(context)),
child: Padding(
padding: const EdgeInsets.all(edgeInsetsSm),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"$title ($year)",
style: buildTextStyleBold(
getTitleTextSize(screenWidth),
Colors.black,
),
),
RatingBar.builder(
initialRating: rating - 3.6,
itemCount: 5,
itemSize: 18.0,
itemBuilder: (_, __) => Icon(
Icons.star,
color: secondaryColor,
),
onRatingUpdate: (rating) {},
),
SizedBox(height: 12.0),
buildDescriptionInfo(screenWidth, 'Rate:', rate),
buildDescriptionInfo(screenWidth, 'Genres:', genres),
buildDescriptionInfo(
screenWidth,
'Released At:',
releasedAt,
),
buildDescriptionInfo(screenWidth, 'Duration:', duration),
buildDescriptionInfo(screenWidth, 'Language:', language),
buildDescriptionInfo(
screenWidth,
"${isContentForMovies ? 'Director' : 'Creator'}:",
directorOrCreator,
),
SizedBox(height: edgeInsetsMd),
Text(
"Synopsis",
style: buildTextStyleBold(
getDescriptionLabelTextSize(screenWidth),
Colors.black,
),
),
SizedBox(height: 4.0),
Text(
synopsis,
style: buildTextStyleLight(
getDescriptionInfoTextSize(screenWidth),
Colors.black,
),
),
SizedBox(height: edgeInsetsMd),
Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: secondaryColor,
),
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("'Watch Now' not implemented yet!"),
),
);
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(
Icons.play_arrow_rounded,
color: Colors.white,
size: getIconSize(screenWidth),
),
SizedBox(width: 4),
Text(
'Watch Now',
style: TextStyle(
fontSize:
getDescriptionLabelTextSize(screenWidth),
),
),
],
),
),
),
),
],
),
),
),
),
],
);
}
Row buildDescriptionInfo(double screenWidth, String label, String info) {
return Row(
children: <Widget>[
Text(
label,
style: buildTextStyleMedium(
getDescriptionLabelTextSize(screenWidth),
Colors.black,
),
),
SizedBox(width: 8.0),
Text(
info,
overflow: TextOverflow.ellipsis,
style: buildTextStyleLight(
getDescriptionInfoTextSize(screenWidth),
Colors.black,
),
),
],
);
}
double getTitleTextSize(double screenWidth) {
if (screenWidth < 600) {
return 16.0;
} else if (screenWidth < 900) {
return 18.0;
} else {
return 24.0;
}
}
double getDescriptionLabelTextSize(double screenWidth) {
if (screenWidth < 600) {
return 12.0;
} else if (screenWidth < 900) {
return 14.0;
} else {
return 16.0;
}
}
double getDescriptionInfoTextSize(double screenWidth) {
if (screenWidth < 600) {
return 10.0;
} else if (screenWidth < 900) {
return 12.0;
} else {
return 14.0;
}
}
double getIconSize(double screenWidth) {
if (screenWidth < 600) {
return 16.0;
} else if (screenWidth < 900) {
return 24.0;
} else {
return 26.0;
}
}
}
| 0 |
mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/screens | mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/screens/home/home_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:sunglasses_show/utils/widget_utils.dart';
import '../../constants.dart';
import 'components/body.dart';
class HomeScreen extends StatelessWidget {
final _globalKey = GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
return Scaffold(
key: _globalKey,
appBar: buildAppBar(context),
drawer: buildDrawerMenu(context),
body: Body(),
backgroundColor: backgroundColor,
);
}
Drawer buildDrawerMenu(BuildContext context) {
return Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
decoration: BoxDecoration(
color: secondaryColor,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
appName,
style: buildTextStyleBold(18.0, Colors.white),
),
SizedBox(height: 4),
Text(
emailDescription,
style: buildTextStyleLight(
12.0,
Color.fromARGB(0x88, 0xFF, 0xFF, 0xFF),
),
),
],
),
),
ListTile(
title: Text(
drawerMenuItems[0],
style: buildTextStyleNormal(12.0, Colors.black87),
),
onTap: () {
_showSnackbar(
context, "'${drawerMenuItems[0]}' not implemented yet!");
Navigator.pop(context);
},
),
ListTile(
title: Text(
drawerMenuItems[1],
style: buildTextStyleNormal(12.0, Colors.black87),
),
onTap: () {
_showSnackbar(
context, "'${drawerMenuItems[1]}' not implemented yet!");
Navigator.pop(context);
},
),
],
),
);
}
AppBar buildAppBar(BuildContext context) => AppBar(
backgroundColor: backgroundColor,
elevation: 0,
leading: IconButton(
icon: SvgPicture.asset(
menuIconPath,
color: secondaryColor,
),
onPressed: () => _globalKey.currentState!.openDrawer(),
),
);
void _showSnackbar(BuildContext context, String message) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(message)));
}
}
| 0 |
mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/screens/home | mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/screens/home/components/item_category_list.dart | import 'package:flutter/material.dart';
import 'package:sunglasses_show/utils/widget_utils.dart';
import '../../../constants.dart';
class ItemCategoryList extends StatelessWidget {
final int selectedTabIndex;
final Function onTapItemCard;
ItemCategoryList(this.selectedTabIndex, this.onTapItemCard);
@override
Widget build(BuildContext context) {
final fontSize = getResponsiveDimension(context, 10.0);
return Container(
decoration: BoxDecoration(color: backgroundColor),
child: ListView.builder(
padding: EdgeInsets.zero,
scrollDirection: Axis.horizontal,
itemCount: itemCategories.length,
itemBuilder: (context, index) =>
buildItemCatogories(context, index, fontSize),
),
);
}
Padding buildItemCatogories(
BuildContext context, int index, double fontSize) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: edgeInsetsMd, vertical: edgeInsetsSm),
child: InkWell(
onTap: () => onTapItemCard(index),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
itemCategories[index],
style: Theme.of(context).textTheme.headline6!.copyWith(
fontFamily: "Manrope",
fontWeight: FontWeight.w500,
fontSize: fontSize,
color: index == selectedTabIndex
? textColorActive
: textColorInActive),
),
Container(
margin: EdgeInsets.only(top: edgeInsetsSm - 3.0),
height: 6,
width: (fontSize * 2),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8.0),
color: index == selectedTabIndex
? secondaryColor
: Colors.transparent,
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/screens/home | mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/lib/screens/home/components/body.dart | import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:sunglasses_show/screens/detail/detail_screen.dart';
import 'package:sunglasses_show/utils/data_utils.dart';
import 'package:sunglasses_show/utils/widget_utils.dart';
import '../../../constants.dart';
import 'item_category_list.dart';
class Body extends StatefulWidget {
@override
_BodyState createState() => _BodyState();
}
class _BodyState extends State<Body> {
final PageController controller = PageController(initialPage: 0);
var movieList = getMovies();
var tvShowList = getTVShows();
int seletedTabIndex = 0;
@override
Widget build(BuildContext context) {
return SafeArea(
child: Container(
child: Column(
children: [
Expanded(
flex: 1,
child: ItemCategoryList(seletedTabIndex, (index) {
setState(() {
seletedTabIndex = index;
});
controller.animateToPage(
index,
duration: Duration(milliseconds: 350),
curve: Curves.easeInOut,
);
}),
),
Expanded(
flex: 7,
child: PageView(
scrollDirection: Axis.horizontal,
controller: controller,
onPageChanged: (selectedIndex) {
setState(() {
seletedTabIndex = selectedIndex;
});
},
physics: BouncingScrollPhysics(),
children: <Widget>[
Padding(
padding:
const EdgeInsets.symmetric(horizontal: edgeInsetsSm),
child: buildMoviesLayout(),
),
Padding(
padding:
const EdgeInsets.symmetric(horizontal: edgeInsetsSm),
child: buildTVShowsLayout(),
),
],
),
),
],
),
),
);
}
LayoutBuilder buildMoviesLayout() => LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
if (constraints.maxWidth < 600) {
return GridView.count(
crossAxisCount: 2,
childAspectRatio: itemCardRatio,
children: _generateMovieCardList(context, itemRadiusSm),
);
} else if (constraints.maxWidth < 900) {
return GridView.count(
crossAxisCount: 3,
childAspectRatio: itemCardRatio,
children: _generateMovieCardList(context, itemRadiusMd),
);
} else {
return GridView.count(
crossAxisCount: 4,
childAspectRatio: itemCardRatio,
children: _generateMovieCardList(context, itemRadiusXl),
);
}
});
LayoutBuilder buildTVShowsLayout() => LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
if (constraints.maxWidth < 600) {
return GridView.count(
crossAxisCount: 2,
childAspectRatio: itemCardRatio,
children: _generateTVShowCardList(context, itemRadiusSm),
);
} else if (constraints.maxWidth < 900) {
return GridView.count(
crossAxisCount: 3,
childAspectRatio: itemCardRatio,
children: _generateTVShowCardList(context, itemRadiusMd),
);
} else {
return GridView.count(
crossAxisCount: 4,
childAspectRatio: itemCardRatio,
children: _generateTVShowCardList(context, itemRadiusXl),
);
}
});
List<Widget> _generateMovieCardList(BuildContext ctx, double radiusSize) =>
movieList.map((movie) {
var fontSize = getResponsiveDimension(ctx, 8.0);
final containerTitleWidth =
getResponsiveLongDimension(ctx, 100.0, 240.0);
return buildCardItem(
containerTitleWidth,
radiusSize,
fontSize,
"${movie.title} (${movie.year})",
movie.rating,
movie.posterUrl, () {
Navigator.push(
ctx,
MaterialPageRoute(
builder: (ctx) => DetailScreen(
isContentForMovies: true,
movie: movie,
),
),
);
});
}).toList();
List<Widget> _generateTVShowCardList(BuildContext ctx, double radiusSize) =>
tvShowList.map((tvShow) {
var fontSize = getResponsiveDimension(ctx, 8.0);
final containerTitleWidth =
getResponsiveLongDimension(ctx, 100.0, 240.0);
return buildCardItem(
containerTitleWidth,
radiusSize,
fontSize,
"${tvShow.title} (${tvShow.year})",
tvShow.rating,
tvShow.posterUrl, () {
Navigator.push(
ctx,
MaterialPageRoute(
builder: (ctx) => DetailScreen(
isContentForMovies: false,
tvShow: tvShow,
),
),
);
});
}).toList();
InkWell buildCardItem(
double containerTitleWidth,
double radiusSize,
double fontSize,
String title,
double rating,
String posterUrl,
GestureTapCallback onTap) =>
InkWell(
onTap: onTap,
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(radiusSize),
),
elevation: 2,
shadowColor: Colors.black26,
child: Stack(
alignment: Alignment.center,
children: <Widget>[
Positioned.fill(
child: buildImagePreview(posterUrl),
),
Positioned.fill(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(radiusSize),
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: <Color>[
Colors.transparent,
Colors.black,
],
),
),
),
),
Positioned(
bottom: edgeInsetsSm,
left: edgeInsetsSm,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
width: containerTitleWidth,
child: Text(
title,
style: buildTextStyleNormal(fontSize, Colors.white),
overflow: TextOverflow.fade,
),
),
SizedBox(
height: 6.0,
),
RatingBar.builder(
initialRating: rating - 3.6,
itemCount: 5,
allowHalfRating: true,
minRating: 1,
itemSize: 16.0,
itemBuilder: (ctx, _) => Icon(
Icons.star,
color: secondaryColor,
),
onRatingUpdate: (rating) {},
),
],
),
),
),
],
),
),
);
Image buildImagePreview(String posterUrl) => Image.asset(
posterUrl,
fit: BoxFit.fill,
);
}
| 0 |
mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding | mirrored_repositories/SunGlassesShow-multiplatform-flutter-beginners-Dicoding/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:sunglasses_show/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/plant-app-ui | mirrored_repositories/plant-app-ui/lib/detailScreen.dart | import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
class DetailScreen extends StatefulWidget {
@override
_DetailScreenState createState() => _DetailScreenState();
}
class _DetailScreenState extends State<DetailScreen> {
Color primaryColor = Color(0xFF0C9869);
Color textColor = Color(0xFF3C4046);
Color backColor = Color(0xFFF9F8FD);
@override
Widget build(BuildContext context) {
return Scaffold(
body: new SingleChildScrollView(
scrollDirection: Axis.vertical,
child: new Column(
children: [new SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: new Row(
children: [
new Padding(padding: const EdgeInsets.symmetric(horizontal: 10)),
new Container(
child: new Column(
children: [
new Row(
children: [
new IconButton(icon: new SvgPicture.asset("assets/icons/back_arrow.svg",height: 30,), onPressed: (){Navigator.pop(context);}),
],
),
new Padding(padding: const EdgeInsets.only(top: 120),),
new Card(
color: Colors.white,
shape: new RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
elevation: 20,
shadowColor: Colors.black45,
child: new Container(
padding: const EdgeInsets.all(10),
child: new SvgPicture.asset("assets/icons/sun.svg"),
),
),
new Padding(padding: const EdgeInsets.only(top: 30),),
new Card(
color: Colors.white,
shape: new RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(18))),
elevation: 20,
shadowColor: Colors.black45,
child: new Container(
padding: const EdgeInsets.all(15),
child: new SvgPicture.asset("assets/icons/icon_2.svg"),
),
),
new Padding(padding: const EdgeInsets.only(top: 30),),
new Card(
color: Colors.white,
shape: new RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(18))),
elevation: 20,
shadowColor: Colors.black45,
child: new Container(
padding: const EdgeInsets.all(15),
child: new SvgPicture.asset("assets/icons/icon_3.svg"),
),
),
new Padding(padding: const EdgeInsets.only(top: 30),),
new Card(
color: Colors.white,
shape: new RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(18))),
elevation: 20,
shadowColor: Colors.black45,
child: new Container(
padding: const EdgeInsets.all(15),
child: new SvgPicture.asset("assets/icons/icon_4.svg"),
),
),
],
),
),
new Container(
alignment: Alignment.topRight,
child: new ClipRRect(
child: new Image.asset("assets/images/img_main.png",fit: BoxFit.cover,height:650,),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(30),
topLeft: Radius.circular(30),
),
),
)
],
),
),
new Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
new Padding(padding: const EdgeInsets.symmetric(horizontal: 10),),
new Column(
children: [
new Text("Angelica",style: TextStyle(fontSize: 35,color: textColor,fontWeight: FontWeight.bold),),
new Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
new Text("Russia",style: TextStyle(fontSize: 25,color: primaryColor),)
],
)
],
),
new Padding(padding: const EdgeInsets.symmetric(horizontal: 80),),
new Text("\$440",style: TextStyle(fontSize: 30,color: primaryColor),),
],
),
new Row(
children: [
new Container(
padding: const EdgeInsets.all(25),
height: 180,
width: 220,
decoration: new BoxDecoration(
color: primaryColor,
borderRadius: BorderRadius.only(
topRight: Radius.circular(30),
)
),
child: new Text("Buy Now",style: TextStyle(fontSize: 30,color: Colors.white,),),
),
new Container(
padding: const EdgeInsets.all(25),
height: 180,
width: 190,
decoration: new BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topRight: Radius.circular(30),
)
),
child: new Text("Description",style: TextStyle(fontSize: 25,color: textColor,),),
),
],
)
]
),
)
);
}
} | 0 |
mirrored_repositories/plant-app-ui | mirrored_repositories/plant-app-ui/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:plant_app_ui/detailScreen.dart';
void main()=>runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: new ThemeData(
brightness : Brightness.light,
),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Color primaryColor = Color(0xFF0C9869);
Color textColor = Color(0xFF3C4046);
Color backColor = Color(0xFFF9F8FD);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
backgroundColor: primaryColor,
elevation: 0,
leading: new IconButton(icon: new SvgPicture.asset("assets/icons/menu.svg"), onPressed: (){}),
),
bottomNavigationBar: new BottomAppBar(
color: Colors.white,
child: new SizedBox(
height: 50,
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
new SvgPicture.asset("assets/icons/flower.svg"),
new SvgPicture.asset("assets/icons/heart-icon.svg"),
new SvgPicture.asset("assets/icons/user-icon.svg"),
],
),
),
),
body: new SingleChildScrollView(
child: new Column(
children: [
new Stack(
children: [
new Container(
height: 140,
width: 720,
decoration: new BoxDecoration(
color: primaryColor,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(36),
bottomRight: Radius.circular(36),
)
),
),
new Container(
padding: const EdgeInsets.all(12),
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
new Text("Hi Uishopy!",style: TextStyle(fontSize: 35,color: Colors.white,fontWeight: FontWeight.bold),),
new Image.asset("assets/images/logo.png"),
],
),
),
new Container(
height: 190,
width: 720,
alignment: Alignment.bottomCenter,
child: new Container(
padding: const EdgeInsets.all(25),
child: new Card(
elevation: 20,
shadowColor: Colors.black12,
shape: new RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
color: Colors.white,
child: new TextFormField(
decoration: new InputDecoration(
contentPadding: const EdgeInsets.all(15),
hintText: "Search",
hintStyle: TextStyle(fontSize: 15,color: primaryColor),
suffixIcon: new Icon(Icons.search,size:30,color: primaryColor,),
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
),
),
)
),
)
],
),
//new Padding(padding: const EdgeInsets.only(top: 5)),
new Row(
children: [
new Padding(padding: const EdgeInsets.symmetric(horizontal: 10),),
new Text("Recomended",style: TextStyle(fontSize: 25,color:textColor,fontWeight: FontWeight.bold)),
new Padding(padding: const EdgeInsets.symmetric(horizontal: 80),),
new Card(
color: primaryColor,
shape: new RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
child: new Container(
padding: const EdgeInsets.all(10),
child: new Text("More",style: TextStyle(fontSize: 15,color: Colors.white,fontWeight: FontWeight.bold),),
)
)
],
),
new Padding(padding: const EdgeInsets.only(top : 5)),
new SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: new Row(
children: [
new Padding(padding: const EdgeInsets.symmetric(horizontal: 10),),
new Card(
elevation: 20,
shadowColor: Colors.black38,
shape: new RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))),
child: new Column(
children: [
new Image.asset("assets/images/image_1.png",height: 240,width: 200,fit: BoxFit.fitHeight,),
new Padding(padding: const EdgeInsets.only(top: 5),),
new Row(
children: [
new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
new Text("SAMNTHA",style: TextStyle(fontSize: 20,color:textColor),),
new Padding(padding: const EdgeInsets.only(top: 5)),
new Text("RUSSIA",style: TextStyle(fontSize: 15,color:primaryColor),),
],
),
new Padding(padding: const EdgeInsets.symmetric(horizontal: 20),),
new Text("\$400",style: TextStyle(fontSize: 20,color: primaryColor,fontWeight: FontWeight.bold),)
],
),
new Padding(padding: const EdgeInsets.only(bottom: 5)),
],
),
),
new Padding(padding: const EdgeInsets.symmetric(horizontal: 5),),
new GestureDetector(
child: new Card(
elevation: 20,
shadowColor: Colors.black38,
shape: new RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))),
child: new Column(
children: [
new Image.asset("assets/images/image_2.png",height: 240,width: 200,fit: BoxFit.fitHeight,),
new Padding(padding: const EdgeInsets.only(top: 5),),
new Row(
children: [
new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
new Text("ANGELICA",style: TextStyle(fontSize: 20,color:textColor),),
new Padding(padding: const EdgeInsets.only(top: 5)),
new Text("RUSSIA",style: TextStyle(fontSize: 15,color:primaryColor),),
],
),
new Padding(padding: const EdgeInsets.symmetric(horizontal: 20),),
new Text("\$540",style: TextStyle(fontSize: 20,color: primaryColor,fontWeight: FontWeight.bold),)
],
),
new Padding(padding: const EdgeInsets.only(bottom: 5)),
],
),
),
onTap: (){
Navigator.push(context, MaterialPageRoute(builder: (BuildContext context)=>DetailScreen()));
},
),
],
),
),
new Padding(padding: const EdgeInsets.only(top: 5)),
new Row(
children: [
new Padding(padding: const EdgeInsets.symmetric(horizontal: 10),),
new Text("Featured Plants",style: TextStyle(fontSize: 25,color:textColor,fontWeight: FontWeight.bold)),
new Padding(padding: const EdgeInsets.symmetric(horizontal: 66),),
new Card(
color: primaryColor,
shape: new RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
child: new Container(
padding: const EdgeInsets.all(10),
child: new Text("More",style: TextStyle(fontSize: 15,color: Colors.white,fontWeight: FontWeight.bold),),
)
)
],
),
new Padding(padding: const EdgeInsets.only(top : 5)),
new SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: new Row(
children: [
new Padding(padding: const EdgeInsets.symmetric(horizontal: 10),),
new Card(
elevation: 20,
shadowColor: Colors.black38,
shape: new RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))),
child: new Column(
children: [
new ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10)),
child: new Image.asset("assets/images/bottom_img_1.png",height: 239,width: 300,fit: BoxFit.fitHeight),
)
],
),
),
new Padding(padding: const EdgeInsets.symmetric(horizontal: 5),),
new Card(
elevation: 20,
shadowColor: Colors.black38,
shape: new RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))),
child: new Column(
children: [
new Image.asset("assets/images/bottom_img_2.png",height: 240,width: 200,fit: BoxFit.fitWidth,),
],
),
),
],
),
),
],
),
),
);
}
} | 0 |
mirrored_repositories/plant-app-ui | mirrored_repositories/plant-app-ui/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:plant_app_ui/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 | mirrored_repositories/sd-with-Dart/String.dart | //Things to know about strings
main(){
//possible ways to write strings
var s1 = 'This is the easiest way.';
var s2 = 'It\'s amazing how this thing works.';
var s3 = "Another way to do this is using double qoutes.";
var s4 = "It's as easy as that.";
//print output
print(s1);
print(s2);
print(s3);
print(s4);
print(' ');
/*In order for the new line, tab, ... to not be implemented
while displaying strings Raw strings are being used */
//RAW String
var s = r'Wish I learned how to type in my early ages. \n Now I have to start its study all over.';
print(s);
} | 0 |
mirrored_repositories | mirrored_repositories/sd-with-Dart/type-conversions.dart | /*in order to convert a string to an integer we use the
parse method of an interger*/
//here's how it's done
main(){
//string to interger
var one = int.parse('2');
assert(one == 2);
//same is done for an string to double conversion
var onePointOne = double.parse('1.1');
assert(onePointOne == 1.1);
/*Now to convert a an integer to a string we
do as follows */
String oneAsString = 1.toString();
assert(oneAsString == '1');
//for a floating point number...
String piAsString = 3.14159.toStringAsPrecision(4);
assert(piAsString == 3.1415);
} | 0 |
mirrored_repositories | mirrored_repositories/sd-with-Dart/classes.dart | void main() {
//Similarly to the manner in which variables are assigned datatypes like String, int, etc. a class is considered as a datatype. This is verified below:
User user1 = User('Clair',
25); //User here is used as the datatype and also called as a fxn and stored in the variable user1
superUser user2 = superUser('Nesta', 20);
//Printing the attributes of the object
print(user1.userName);
print(user2.age);
user1.login();
user2.publish();
user2.login();
}
//creating a class - User
class User {
//using our class this way will assign all user's userNames to be Nesta, similarly with the age
// String userName = 'Nesta';
// int age = 20;
//to escape that we do as below:
String userName = '';
int age = 0;
//We'll create a constructor (Which is a special type of fxn which takes in parameters. And this constructor needs to have the same name as the class inwhich it is found) as such:
User(String userName, int age) {
this.userName = userName;
this.age = age;
}
//classes can contain fxns as seen below:
void login() {
print('User logged in!');
}
}
//Now what we want to do is add extra properties to instances of the class
//And to do that what we'll do is we'll extend the class as such:
class superUser extends User {
superUser(String username, int age) : super(username, age);
void publish() {
print('Publish Update');
}
}
| 0 |
mirrored_repositories | mirrored_repositories/sd-with-Dart/operators.dart | class numx {
int Numx = 17;
}
main() {
numx a = numx();
print(a.Numx);
// int num = 20 + 11;
// num = num - 2;
// print(num);
// num = num % 5;
// print(num);
//relational operators
// if (num == 4) {
// print('true');
// } else {
// print('false');
// }
// num *= 5;
// print(num);
//unary operator
// ++num;
// print(num);
// num++; //which is same as num = num + ... a certain variable
// print(num);
//logical operators
// if (num > 2 && num < 30) {
// //operatorfor logical AND – &&
// print('Great!!');
// } else if (num > 2 || num == 0) {
// //operatorfor logical OR – ||
// print('Too bad!');
// }
// if (num != 20) {
// //operatorfor logical NOT – !
// print('Finished successfully');
// }
//Tenary operator
// var x = 100;
// var result = x % 2 == 0 ? 'Even' : 'Odd';
// print(result);
//Testing operator
// if(x is int){
// print('integer');
// }
//Testing my numx class
// var n = numx();
// int number;
// number = n.Numx;
// print(number);
}
| 0 |
mirrored_repositories | mirrored_repositories/sd-with-Dart/functions.dart | void main() {
List names = ['luca', 'lucy', 'lucio'];
//The List datatype doesn't give a specific datatype to the list it creates but rather permits the adding of values of any datatype
//This isn't good practice and to remedy this we use angle brackets to specify the list's datatype
//List<String> names = ['luca', 'lucy', 'lucio'];
//Adding new names to the List (Array in JavaScript)
names.add('Clair');
//Adding an interger to the list
names.add(20);
//Removing a name from the list
names.remove('luca');
//Printing the names in the list
print(names);
//calling external fxns in main()
String name = lastName();
print(name);
}
String lastName() => 'Nesta'; //one way of writing fxns
//Another way to write the above fxn is as so...
// String lastName() {
// return 'Nesta';
// }
| 0 |
mirrored_repositories | mirrored_repositories/sd-with-Dart/playground.dart | main() {
print("Hello World!");
//printing out some text – my name
var firstName = 'Egbe';
String lastName = 'Nesta Enow';
print(firstName + ' ' + lastName);
} | 0 |
mirrored_repositories | mirrored_repositories/sd-with-Dart/constants.dart | main(){
const aConstNum = 1;
const aConstBool = false;
const aConstString = 'Nesta';
/* when using the const keyword/datatype keep in mind that
it takes the data type of the value which is being assigned to it */
print(aConstNum);
print(aConstBool);
print(aConstString);
/* to determine the constant type during
runtime we use the .runtimetype as seen below */
print(aConstNum.runtimeType);
print(aConstBool.runtimeType);
print(aConstString.runtimeType);
/* If a variable is declared and no value is being assigned to it
note that is automatically assigned the value NULL */
//For example
var num;
//printing this variable verifies our hypothesis
print(num);
} | 0 |
mirrored_repositories | mirrored_repositories/sd-with-Dart/input-output.dart | import 'dart:io';
main() {
//prompting the user to enter some data
stdout.writeln('What is your name: ?');
//declare a variable and store the value gotten from the user in it
String? name = stdin.readLineSync();
//print the value gotten
//that is the one stored in the variable name
print('My name is $name');
} | 0 |
mirrored_repositories | mirrored_repositories/sd-with-Dart/datatypes.dart | main() {
//integer variable declaration
int amount1 = 100;
var amount2 = 200;
//print the values out
print('Amount1: $amount1 | Amount2: $amount2 \n');
//double variable declaration
double dAmount1 = 100.11;
var dAmount2 = 200.12;
print('Amount1: $dAmount1 | Amount2: $dAmount2 \n');
//String variable declaration
String name1 = 'Egbe';
var name2 = 'Nesta Enow';
print('My Name is: $name1 $name2 \n');
//Boolean variable delaration
bool isItTrue1 = true;
var isItTrue2 = false;
print('isItTrue1: $isItTrue1 | isItTrue2: $isItTrue2 \n');
//dynamic variable declaration
dynamic weakVariable = 100;
print('WeakVariable 1: $weakVariable \n');
weakVariable = 'Dart Programming';
print('WeakVariable 2: $weakVariable');
} | 0 |
mirrored_repositories/eho_haber | mirrored_repositories/eho_haber/lib/main.dart | import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'home/view/home_page_view.dart';
import 'login/view/login_view.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
User? _user = FirebaseAuth.instance.currentUser;
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(brightness: Brightness.dark),
title: 'Pixels News',
home: _user != null ? HomePageView() : LoginView(),
),
);
}
| 0 |
mirrored_repositories/eho_haber/lib | mirrored_repositories/eho_haber/lib/constants/images.dart | import 'package:flutter/material.dart';
class Images {
static const AssetImage whiteTextLogo =
AssetImage("assets/logo/logo_white_red_text.png");
static const AssetImage imagePhone =
AssetImage("assets/images/image_app.png");
}
| 0 |
mirrored_repositories/eho_haber/lib/login | mirrored_repositories/eho_haber/lib/login/view-model/login_view_model.dart | import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import '../../home/view/home_page_view.dart';
import 'package:mobx/mobx.dart';
part 'login_view_model.g.dart';
class LoginViewModel = _LoginViewModelBase with _$LoginViewModel;
abstract class _LoginViewModelBase with Store {
@observable
TextEditingController emailController = TextEditingController();
@observable
TextEditingController passwordController = TextEditingController();
Future userLogin({String? email, String? password, BuildContext? context}) async {
try {
await FirebaseAuth.instance.signInWithEmailAndPassword(email: email!, password: password!);
Navigator.pushReplacement(context!, MaterialPageRoute(builder: (context) => HomePageView()));
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
debugPrint('No user found for that email.');
} else if (e.code == 'wrong-password') {
debugPrint('Wrong password provided for that user.');
}
}
}
}
| 0 |
mirrored_repositories/eho_haber/lib/login | mirrored_repositories/eho_haber/lib/login/view-model/login_view_model.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'login_view_model.dart';
// **************************************************************************
// StoreGenerator
// **************************************************************************
// ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic
mixin _$LoginViewModel on _LoginViewModelBase, Store {
final _$emailControllerAtom =
Atom(name: '_LoginViewModelBase.emailController');
@override
TextEditingController get emailController {
_$emailControllerAtom.reportRead();
return super.emailController;
}
@override
set emailController(TextEditingController value) {
_$emailControllerAtom.reportWrite(value, super.emailController, () {
super.emailController = value;
});
}
final _$passwordControllerAtom =
Atom(name: '_LoginViewModelBase.passwordController');
@override
TextEditingController get passwordController {
_$passwordControllerAtom.reportRead();
return super.passwordController;
}
@override
set passwordController(TextEditingController value) {
_$passwordControllerAtom.reportWrite(value, super.passwordController, () {
super.passwordController = value;
});
}
@override
String toString() {
return '''
emailController: ${emailController},
passwordController: ${passwordController}
''';
}
}
| 0 |
mirrored_repositories/eho_haber/lib/login | mirrored_repositories/eho_haber/lib/login/view/login_view.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../constants/images.dart';
import '../view-model/login_view_model.dart';
import '../../register/view/register_view.dart';
class LoginView extends StatelessWidget {
LoginView({Key? key}) : super(key: key);
final _loginviewModel = LoginViewModel();
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
bildLogoImage(),
const SizedBox(height: 150),
TextFormField(
keyboardType: TextInputType.emailAddress,
controller: _loginviewModel.emailController,
decoration: const InputDecoration(
label: Padding(
padding: EdgeInsets.all(8.0),
child: Text("Email adresiniz"),
),
),
),
const SizedBox(
height: 30,
),
TextFormField(
controller: _loginviewModel.passwordController,
obscureText: true,
decoration: const InputDecoration(
label: Padding(
padding: EdgeInsets.all(8.0),
child: Text("Parolanız"),
),
),
),
const SizedBox(
height: 40,
),
OutlinedButton(
onPressed: () => _loginviewModel.userLogin(
email: _loginviewModel.emailController.text, password: _loginviewModel.passwordController.text, context: context),
child: const Text(
"Giriş Yap",
style: TextStyle(
color: Colors.white,
),
),
style: OutlinedButton.styleFrom(
backgroundColor: Colors.red,
),
),
const SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("Kayıtlı değil misin?"),
TextButton(
child: const Text(
"Kayıt Ol",
style: TextStyle(color: Colors.red),
),
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => RegisterView())),
),
],
),
],
),
),
),
),
);
}
Image bildLogoImage() {
return const Image(
image: Images.whiteTextLogo,
width: 300,
);
}
}
| 0 |
mirrored_repositories/eho_haber/lib/home | mirrored_repositories/eho_haber/lib/home/view-model/home_page_view_model.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import '../model/currency.dart';
import '../model/news.dart';
import '../model/weather.dart';
import '../../login/view/login_view.dart';
import 'package:http/http.dart';
import 'package:mobx/mobx.dart';
import 'package:firebase_auth/firebase_auth.dart';
part 'home_page_view_model.g.dart';
class HomePageViewModel = _HomePageViewModelBase with _$HomePageViewModel;
abstract class _HomePageViewModelBase with Store {
@action
String? getCurrentUser() {
String? userName = FirebaseAuth.instance.currentUser != null ? FirebaseAuth.instance.currentUser!.email : '';
return userName;
}
@action
Future userSigningOut({BuildContext? context}) async {
await FirebaseAuth.instance.signOut();
Navigator.pushReplacement(context!, MaterialPageRoute(builder: (context) => LoginView()));
}
@action
Future<List<Currency>> getCurrency() async {
List<Currency> w = [];
Response response = await get(
Uri.parse('https://api.genelpara.com/embed/para-birimleri.json'),
);
try {
Map l = json.decode(response.body);
for (var map in l.keys) {
w.add(Currency.fromMap(l[map]));
}
return w;
} catch (e) {
debugPrint(e.toString());
return w;
}
}
@action
Future<Weather?> getWeather() async {
List<Weather> w = [];
Response response = await get(
Uri.parse('https://api.collectapi.com/weather/getWeather?data.lang=tr&data.city=sakarya'),
headers: {
"content-type": "application/json",
"authorization": "apikey 6WoaWIEu5rfwTdKyYu3M3O:2qCPHjyHeqpDPYkgL8IXsY",
},
);
try {
List l = json.decode(response.body)['result'];
for (var map in l) {
w.add(Weather.fromMap(map));
}
return w.first;
} catch (e) {
debugPrint(e.toString());
return w.first;
}
}
@action
Future<List<News>> getNews() async {
List<News> w = [];
Response response = await get(
Uri.parse('https://api.collectapi.com/news/getNews?country=tr&tag=general'),
headers: {
"content-type": "application/json",
"authorization": "apikey 6WoaWIEu5rfwTdKyYu3M3O:2qCPHjyHeqpDPYkgL8IXsY",
},
);
try {
List l = json.decode(response.body)['result'];
for (var map in l) {
w.add(News.fromMap(map));
}
return w;
} catch (e) {
debugPrint(e.toString());
return w;
}
}
}
| 0 |
mirrored_repositories/eho_haber/lib/home | mirrored_repositories/eho_haber/lib/home/view-model/home_page_view_model.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'home_page_view_model.dart';
// **************************************************************************
// StoreGenerator
// **************************************************************************
// ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic
mixin _$HomePageViewModel on _HomePageViewModelBase, Store {
final _$userSigningOutAsyncAction =
AsyncAction('_HomePageViewModelBase.userSigningOut');
@override
Future<dynamic> userSigningOut({BuildContext? context}) {
return _$userSigningOutAsyncAction
.run(() => super.userSigningOut(context: context));
}
final _$getCurrencyAsyncAction =
AsyncAction('_HomePageViewModelBase.getCurrency');
@override
Future<List<Currency>> getCurrency() {
return _$getCurrencyAsyncAction.run(() => super.getCurrency());
}
final _$getWeatherAsyncAction =
AsyncAction('_HomePageViewModelBase.getWeather');
@override
Future<Weather?> getWeather() {
return _$getWeatherAsyncAction.run(() => super.getWeather());
}
final _$getNewsAsyncAction = AsyncAction('_HomePageViewModelBase.getNews');
@override
Future<List<News>> getNews() {
return _$getNewsAsyncAction.run(() => super.getNews());
}
final _$_HomePageViewModelBaseActionController =
ActionController(name: '_HomePageViewModelBase');
@override
String? getCurrentUser() {
final _$actionInfo = _$_HomePageViewModelBaseActionController.startAction(
name: '_HomePageViewModelBase.getCurrentUser');
try {
return super.getCurrentUser();
} finally {
_$_HomePageViewModelBaseActionController.endAction(_$actionInfo);
}
}
@override
String toString() {
return '''
''';
}
}
| 0 |
mirrored_repositories/eho_haber/lib/home | mirrored_repositories/eho_haber/lib/home/view/home_page_view.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../constants/images.dart';
import '../model/currency.dart';
import '../model/news.dart';
import '../model/weather.dart';
import '../view-model/home_page_view_model.dart';
class HomePageView extends StatelessWidget {
HomePageView({Key? key}) : super(key: key);
final _homePageViewModel = HomePageViewModel();
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: buildDrawerMenu(context),
appBar: buildAppBar(),
body: SafeArea(
child: FutureBuilder(
future: _homePageViewModel.getNews(),
builder: (BuildContext c, AsyncSnapshot s) {
if (!s.hasData) return const Center(child: CircularProgressIndicator());
List<News> data = s.data;
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return buildNewsCard(data[index]);
});
},
),
),
);
}
Container buildNewsCard(News data) {
return Container(
width: double.infinity,
height: 140,
color: Colors.white10,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(
data.name!.toUpperCase(),
style: const TextStyle(fontWeight: FontWeight.bold),
),
const Text("*Genel"),
],
),
),
Image(
height: 124,
width: 160,
image: NetworkImage(data.image!),
),
],
),
),
);
}
AppBar buildAppBar() {
return AppBar(
centerTitle: true,
title: const Image(
image: Images.whiteTextLogo,
height: 30,
),
);
}
Drawer buildDrawerMenu(BuildContext context) {
return Drawer(
child: Column(
children: [
SizedBox(
height: 85,
child: DrawerHeader(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(_homePageViewModel.getCurrentUser() ?? ''),
IconButton(
onPressed: () => _homePageViewModel.userSigningOut(context: context),
icon: const Icon(
Icons.exit_to_app,
),
)
],
)),
),
Container(
height: 120,
width: 200,
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Colors.blueAccent, Colors.white, Colors.blueAccent],
begin: Alignment.centerLeft,
end: Alignment.centerRight,
),
),
child: FutureBuilder(
future: _homePageViewModel.getWeather(),
builder: (BuildContext c, AsyncSnapshot s) {
if (!s.hasData) return const Center(child: CircularProgressIndicator());
Weather homeList = s.data;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Sakarya',
style: TextStyle(color: Colors.black, fontSize: 16),
),
Text(
homeList.degree!.toStringAsFixed(0) + '°',
style: const TextStyle(color: Colors.black, fontSize: 26),
),
Text(
homeList.description.toString(),
style: const TextStyle(
color: Colors.black,
fontSize: 14,
),
),
Text(
homeList.day.toString(),
style: const TextStyle(color: Colors.black, fontSize: 12),
),
],
);
},
),
),
ListTile(
title: const Text(''),
trailing: Wrap(
spacing: 12,
children: const [
Text('Alış'),
Text('Satış'),
],
),
),
Expanded(
child: FutureBuilder(
future: _homePageViewModel.getCurrency(),
builder: (BuildContext c, AsyncSnapshot s) {
if (!s.hasData) return const Center(child: CircularProgressIndicator());
List<Currency> homeList = s.data;
return ListView.builder(
itemCount: homeList.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(homeList[index].isim.toString()),
trailing: Wrap(
spacing: 12,
children: [
Text(homeList[index].alis.toString()),
Text(homeList[index].satis.toString()),
],
),
);
});
},
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/eho_haber/lib/home | mirrored_repositories/eho_haber/lib/home/model/news.dart | import 'dart:convert';
class News {
String? name;
String? description;
String? image;
News({
this.name,
this.description,
this.image,
});
Map<String, dynamic> toMap() {
return {
'name': name,
'description': description,
'image': image,
};
}
factory News.fromMap(Map<String, dynamic> map) {
return News(
name: map['name'],
description: map['description'],
image: map['image'],
);
}
String toJson() => json.encode(toMap());
factory News.fromJson(String source) => News.fromMap(json.decode(source));
}
| 0 |
mirrored_repositories/eho_haber/lib/home | mirrored_repositories/eho_haber/lib/home/model/weather.dart | import 'dart:convert';
class Weather {
String? day;
String? description;
double? degree;
Weather({
this.day,
this.description,
this.degree,
});
Map<String, dynamic> toMap() {
return {
'day': day,
'description': description,
'degree': degree,
};
}
factory Weather.fromMap(Map<String, dynamic> map) {
return Weather(
day: map['day'],
description: map['description'],
degree: double.parse(map['degree']),
);
}
String toJson() => json.encode(toMap());
factory Weather.fromJson(String source) => Weather.fromMap(json.decode(source));
}
| 0 |
mirrored_repositories/eho_haber/lib/home | mirrored_repositories/eho_haber/lib/home/model/currency.dart | import 'dart:convert';
class Currency {
double? satis;
double? alis;
String? isim;
Currency({
this.satis,
this.alis,
this.isim,
});
Map<String, dynamic> toMap() {
return {
'satis': satis,
'alis': alis,
'isim': isim,
};
}
factory Currency.fromMap(Map<String, dynamic> map) {
return Currency(
satis: double.tryParse(map['satis']),
alis: double.tryParse(map['alis']),
isim: map['isim'],
);
}
String toJson() => json.encode(toMap());
factory Currency.fromJson(String source) => Currency.fromMap(json.decode(source));
}
| 0 |
mirrored_repositories/eho_haber/lib/register | mirrored_repositories/eho_haber/lib/register/view-model/register_view_model.dart | import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:mobx/mobx.dart';
import '../../home/view/home_page_view.dart';
part 'register_view_model.g.dart';
class RegisterViewModel = _RegisterViewModelBase with _$RegisterViewModel;
abstract class _RegisterViewModelBase with Store {
@observable
TextEditingController emailController = TextEditingController();
@observable
TextEditingController passwordController = TextEditingController();
@action
Future userRegister({String? email, String? password, BuildContext? context}) async {
try {
if (password!.length < 6) {
ScaffoldMessenger.of(context!).showSnackBar(const SnackBar(content: Text('Şifreniz en az 6 haneli olmalı!!!')));
return;
}
await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email!, password: password)
.whenComplete(() => Navigator.pushAndRemoveUntil(context!, MaterialPageRoute(builder: (context) => HomePageView()), (route) => false));
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
debugPrint('The password provided is too weak.');
ScaffoldMessenger.of(context!).showSnackBar(const SnackBar(content: Text('The password provided is too weak.')));
} else if (e.code == 'email-already-in-use') {
debugPrint('The account already exists for that email.');
ScaffoldMessenger.of(context!).showSnackBar(const SnackBar(content: Text('The account already exists for that email.')));
}
} catch (e) {
debugPrint(e.toString());
}
}
}
| 0 |
mirrored_repositories/eho_haber/lib/register | mirrored_repositories/eho_haber/lib/register/view-model/register_view_model.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'register_view_model.dart';
// **************************************************************************
// StoreGenerator
// **************************************************************************
// ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic
mixin _$RegisterViewModel on _RegisterViewModelBase, Store {
final _$emailControllerAtom =
Atom(name: '_RegisterViewModelBase.emailController');
@override
TextEditingController get emailController {
_$emailControllerAtom.reportRead();
return super.emailController;
}
@override
set emailController(TextEditingController value) {
_$emailControllerAtom.reportWrite(value, super.emailController, () {
super.emailController = value;
});
}
final _$passwordControllerAtom =
Atom(name: '_RegisterViewModelBase.passwordController');
@override
TextEditingController get passwordController {
_$passwordControllerAtom.reportRead();
return super.passwordController;
}
@override
set passwordController(TextEditingController value) {
_$passwordControllerAtom.reportWrite(value, super.passwordController, () {
super.passwordController = value;
});
}
final _$userRegisterAsyncAction =
AsyncAction('_RegisterViewModelBase.userRegister');
@override
Future<dynamic> userRegister(
{String? email, String? password, BuildContext? context}) {
return _$userRegisterAsyncAction.run(() =>
super.userRegister(email: email, password: password, context: context));
}
@override
String toString() {
return '''
emailController: ${emailController},
passwordController: ${passwordController}
''';
}
}
| 0 |
mirrored_repositories/eho_haber/lib/register | mirrored_repositories/eho_haber/lib/register/view/register_view.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../constants/images.dart';
import '../view-model/register_view_model.dart';
class RegisterView extends StatelessWidget {
RegisterView({Key? key}) : super(key: key);
final _registerViewModel = RegisterViewModel();
// final TextEditingController emailController = TextEditingController();
// final TextEditingController passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: buildAppBar(),
body: SafeArea(
child: Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Image(
image: Images.whiteTextLogo,
width: 300,
),
const SizedBox(height: 150),
TextFormField(
keyboardType: TextInputType.emailAddress,
controller: _registerViewModel.emailController,
decoration: const InputDecoration(
label: Text("Email adresiniz"),
),
),
const SizedBox(
height: 30,
),
TextFormField(
obscureText: true,
controller: _registerViewModel.passwordController,
decoration: const InputDecoration(
label: Text("Parolanız"),
),
),
const SizedBox(
height: 20,
),
OutlinedButton(
onPressed: () => _registerViewModel.userRegister(
email: _registerViewModel.emailController.text, password: _registerViewModel.passwordController.text, context: context),
child: const Text(
"Kayıt Ol",
style: TextStyle(
color: Colors.white,
),
),
style: OutlinedButton.styleFrom(
backgroundColor: Colors.red,
),
),
],
),
),
),
),
);
}
AppBar buildAppBar() {
return AppBar(
title: const Text('Kayıt Ol'),
centerTitle: true,
);
}
}
| 0 |
mirrored_repositories/eho_haber/lib/register | mirrored_repositories/eho_haber/lib/register/model/register.dart | import 'dart:convert';
class Register {
String? email;
String? password;
Register({
this.email,
this.password,
});
Map<String, dynamic> toMap() {
return {
'email': email,
'password': password,
};
}
factory Register.fromMap(Map<String, dynamic> map) {
return Register(
email: map['email'],
password: map['password'],
);
}
String toJson() => json.encode(toMap());
factory Register.fromJson(String source) => Register.fromMap(json.decode(source));
}
| 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/providerEmailVerification.dart | import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
//import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'globalVariables.dart';
import './addservice.dart';
import './addservice.dart';
class ProviderEmailVerification extends StatelessWidget {
final String provider_id;
final String email;
final String username;
final String password;
ProviderEmailVerification(this.provider_id,this.email, this.username, this.password);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: providerProgressPage(provider_id,email, username, password),
);
}
}
class providerProgressPage extends StatefulWidget {
final String provider_id;
final String email;
final String username;
final String password;
providerProgressPage(this.provider_id,this.email, this.username, this.password);
@override
_providerProgressPageState createState() =>
_providerProgressPageState(provider_id,email, username, password);
}
class _providerProgressPageState extends State<providerProgressPage> {
final String provider_id;
final String email;
final String username;
final String password;
String usern;
_providerProgressPageState(this.provider_id,this.email, this.username, this.password);
bool isEmailVerified = false;
Timer timer;
void setData(String uname) {
setState(() {
usern = uname;
//Fluttertoast.showToast(msg: username);
});
//Fluttertoast.showToast(msg: username);
}
void RetrieveUser() {
String path = 'service_provider/' + provider_id;
FirebaseFirestore.instance.doc(path).get().then((value) => {
//String uname = value.data()['Usename']
//Fluttertoast.showToast(msg: value.data()['Username'].toString()),
setData(value.data()['Username'].toString())
});
}
void checkStatus() async {
User user = FirebaseAuth.instance.currentUser;
await user.reload();
//Variables().setFIrebaseUser(user);
setState(() {
isEmailVerified = user.emailVerified;
});
}
Future<void> addServiceProvider() {
String path = 'service_provider/'+provider_id;
FirebaseFirestore.instance
.doc(path)
.set({'Email': email, 'Username': username, 'Password': password})
.then((value) => print("Provider Added"))
.catchError((error) => {
print("Failed to add provider: $error"),
});
;
// Call the user's CollectionReference to add a new user
// return users
// .set({'Email': email, 'Username': username, 'Password': password})
// .then((value) => print("User Added"))
// .catchError((error) => {
// print("Failed to add user: $error"),
// });
}
@override
void initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 4), (timer) {
checkStatus();
if (isEmailVerified == true) {
addServiceProvider();
RetrieveUser();
timer.cancel();
}
});
}
@override
void dipose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: isEmailVerified != true
? <Widget>[
Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Color.fromRGBO(6, 13, 217, 1)),
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
Text("Verify email to proceed")
]
: <Widget>[
Center(
child: Icon(
Icons.check,
color: Color.fromRGBO(6, 13, 217, 1),
size: MediaQuery.of(context).size.width * 0.20,
)),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
Text("Email verified Successfully!"),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
ButtonTheme(
buttonColor: Color.fromRGBO(6, 13, 217, 1),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
child: RaisedButton(
child: Text(
"Add Service",
style: TextStyle(color: Colors.white),
),
onPressed: () {
Timer(Duration(seconds: 3), (){
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => AddService(email,usern)));
});
},
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/cart.dart | import 'dart:async';
import 'package:SetItUp/signInOptions.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'productDetails.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:SetItUp/globalVariables.dart';
class Cart extends StatefulWidget {
@override
_CartState createState() => _CartState();
}
String userid;
getUserData() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getStringList('User') ?? null;
}
class _CartState extends State<Cart> {
void convert(List<Timestamp> list_1, List<DateTime> list_2) {
DateTime x;
Timestamp y;
for (int i = 0; i < list_1.length; i++) {
y = list_1[i];
x = y.toDate();
list_2.add(x);
}
}
bool service_exists;
void updateservicestatus(DocumentSnapshot value) {
if (value.exists == true) {
setState(() {
service_exists = true;
});
} else {
setState(() {
service_exists = false;
});
}
}
@override
void initState() {
// TODO: implement initState
super.initState();
if (Variables().firebaseuser != null && Variables().cart_updated != 1) {
getUserData().then((value) => setUserData(value));
Timer(Duration(seconds: 1), () {
getCart();
});
}
}
void setUserData(List<String> data) {
if (data != null) {
setState(() {
userid = data[0];
//Fluttertoast.showToast(msg: userid);
Variables().setUserId(userid);
Fluttertoast.showToast(msg: Variables().userid);
});
} else {
Fluttertoast.showToast(msg: 'null data');
}
}
void getCart() {
String path = 'carts/' + userid + '/cart_items';
FirebaseFirestore.instance
.collection('carts')
.doc(Variables().session_ID)
.collection('cart_items')
.get()
.then((QuerySnapshot data) {
if (data.size != 0) {
//print('Document data: ${data.data()}');
updateCart(data, path);
} else {
print('Document does not exist on the database');
}
});
}
updateCart(QuerySnapshot data, String path) {
FirebaseFirestore.instance
.collection('carts')
.doc(userid)
.set({'Dummy': 'dummy'});
data.docs.forEach((element) {
FirebaseFirestore.instance
.collection('carts')
.doc(userid)
.collection('cart_items')
.doc(element.id)
.set(element.data());
});
deleteCart();
}
deleteCart() {
FirebaseFirestore.instance
.collection('carts')
.doc(Variables().session_ID)
.collection('cart_items')
.get()
.then((value) => {value.docs.forEach((element) {
element.reference.delete();
})});
//.catchError((error) => print("Error in deleting old cart document"));
FirebaseFirestore.instance
.doc('carts/' + Variables().session_ID)
.delete()
.then((value) => print("Deleted old cart doc"))
.catchError((error) => print('failed to remove old cart doc'));
Variables().setCartUpdateStatus(1);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromRGBO(6, 13, 217, 1),
appBar: AppBar(
centerTitle: true,
backgroundColor: Color(0xff060DD9),
title: Align(
alignment: Alignment.center,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.shopping_cart_rounded,
color: Colors.white,
),
SizedBox(width: MediaQuery.of(context).size.width * 0.03),
Text("My Cart"),
SizedBox(width: MediaQuery.of(context).size.width * 0.15)
],
),
)),
body: Variables().firebaseuser == null
? Column(children: <Widget>[
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
Container(
height: MediaQuery.of(context).size.height * 0.65,
width: double.infinity,
padding: EdgeInsets.all(20),
decoration: BoxDecoration(
border: Border.all(),
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(40),
topRight: Radius.circular(40),
bottomLeft: Radius.circular(40),
bottomRight: Radius.circular(40))),
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('carts')
.doc(Variables().session_ID)
.collection('cart_items')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Something went wrong'));
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: Text("Loading"));
}
if (snapshot.data.size == 0) {
return Center(
child: Text(
"No items in your Cart !",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold,
color: Color.fromRGBO(6, 13, 217, 1)),
));
}
Variables().cartstatus = 1;
return ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (BuildContext context, int index) {
DocumentSnapshot documentSnapshot =
snapshot.data.docs[index];
String serviceid = documentSnapshot.id.toString();
String Image = documentSnapshot['Image'];
String Title = documentSnapshot['Title'];
String Name = documentSnapshot['Name'];
String Duration =
((documentSnapshot['Duration']) / 60)
.toString();
int Price = documentSnapshot['Price'];
String Email = documentSnapshot['Email'];
String Desc = documentSnapshot['Description'];
String Slot = documentSnapshot['Booked_Slot'];
String servicepath = 'services/' + serviceid;
if (FirebaseFirestore.instance.doc(servicepath) !=
null) {
return ServiceTile(
serviceImage: Image,
serviceName: Title,
providerName: Name,
defaultSlot: Duration,
price: Price,
documentSnapshot: documentSnapshot,
slot: Slot,
);
}
});
}),
),
Expanded(
child: Container(
padding: EdgeInsets.all(20),
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('carts')
.doc(Variables().session_ID)
.collection('cart_items')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Something went wrong'));
}
if (snapshot.connectionState ==
ConnectionState.waiting) {
return Center(child: Text("Loading"));
}
if (snapshot.data.size == 0) {
return Center();
}
int grand_total = 0;
snapshot.data.docs.forEach((element) {
grand_total += element.data()['Price'];
});
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Grand Total - ₹" + grand_total.toString(),
style: TextStyle(
color: Colors.white,
fontFamily: "Poppins",
fontWeight: FontWeight.bold,
fontSize:
MediaQuery.of(context).size.width *
0.045))
],
),
Container(
margin: EdgeInsets.all(10),
alignment: Alignment.bottomCenter,
child: ButtonTheme(
height:
MediaQuery.of(context).size.height * 0.05,
minWidth:
MediaQuery.of(context).size.width * 0.25,
buttonColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
child: ElevatedButton(
onPressed: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) =>
SignInOptions()),
(route) => false);
},
child: Text(
"Proceed to Checkout",
style: TextStyle(
color: Color.fromRGBO(6, 13, 217, 1),
fontFamily: "Poppins",
fontWeight: FontWeight.bold,
fontSize:
MediaQuery.of(context).size.width *
0.045),
),
),
),
),
],
);
}),
),
),
])
: Column(children: <Widget>[
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
Container(
height: MediaQuery.of(context).size.height * 0.65,
width: double.infinity,
padding: EdgeInsets.all(20),
decoration: BoxDecoration(
border: Border.all(),
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(40),
topRight: Radius.circular(40),
bottomLeft: Radius.circular(40),
bottomRight: Radius.circular(40))),
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('carts')
.doc(userid)
.collection('cart_items')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Something went wrong'));
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: Text("Loading"));
}
if (snapshot.data.size == 0) {
return Center(
child: Text(
"No items in your Cart !",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold,
color: Color.fromRGBO(6, 13, 217, 1)),
));
}
//Variables().cartstatus = 1;
return ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (BuildContext context, int index) {
DocumentSnapshot documentSnapshot =
snapshot.data.docs[index];
String serviceid = documentSnapshot.id.toString();
String Image = documentSnapshot['Image'];
String Title = documentSnapshot['Title'];
String Name = documentSnapshot['Name'];
String Duration =
((documentSnapshot['Duration']) / 60)
.toString();
int Price = documentSnapshot['Price'];
String Email = documentSnapshot['Email'];
String Desc = documentSnapshot['Description'];
String Slot = documentSnapshot['Booked_Slot'];
String servicepath = 'services/' + serviceid;
if (FirebaseFirestore.instance.doc(servicepath) !=
null) {
return ServiceTile(
serviceImage: Image,
serviceName: Title,
providerName: Name,
defaultSlot: Duration,
price: Price,
documentSnapshot: documentSnapshot,
slot: Slot,
);
}
});
}),
),
Expanded(
child: Container(
padding: EdgeInsets.all(20),
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('carts')
.doc(userid)
.collection('cart_items')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Something went wrong'));
}
if (snapshot.connectionState ==
ConnectionState.waiting) {
return Center(child: Text("Loading"));
}
if (snapshot.data.size == 0) {
return Center();
}
int grand_total = 0;
snapshot.data.docs.forEach((element) {
grand_total += element.data()['Price'];
});
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Grand Total - ₹" + grand_total.toString(),
style: TextStyle(
color: Colors.white,
fontFamily: "Poppins",
fontWeight: FontWeight.bold,
fontSize:
MediaQuery.of(context).size.width *
0.045))
],
),
Container(
margin: EdgeInsets.all(10),
alignment: Alignment.bottomCenter,
child: ButtonTheme(
height:
MediaQuery.of(context).size.height * 0.05,
minWidth:
MediaQuery.of(context).size.width * 0.25,
buttonColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
child: ElevatedButton(
onPressed: () {},
child: Text(
"Proceed to Checkout",
style: TextStyle(
color: Color.fromRGBO(6, 13, 217, 1),
fontFamily: "Poppins",
fontWeight: FontWeight.bold,
fontSize:
MediaQuery.of(context).size.width *
0.045),
),
),
),
),
],
);
}),
),
),
]),
);
}
}
class ServiceTile extends StatelessWidget {
final String serviceImage;
final String serviceName;
final String providerName;
final String defaultSlot;
//final String productDesc;
final int price;
final String slot;
final DocumentSnapshot documentSnapshot;
// List<DateTime> unAvailable = [];
// List<DateTime> booked = [];
// List<DateTime> unBooked = [];
ServiceTile(
{@required this.serviceImage,
@required this.serviceName,
@required this.providerName,
@required this.defaultSlot,
@required this.price,
@required this.documentSnapshot,
@required this.slot
// @required this.unAvailable,
// @required this.booked,
// @required this.unBooked
});
@override
//
Widget build(BuildContext context) {
return Column(
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
border: Border.all(width: 1),
),
//margin: EdgeInsets.symmetric(vertical: 16),
padding: EdgeInsets.all(MediaQuery.of(context).size.width * 0.030),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(60),
child: Image.network(
serviceImage,
height: MediaQuery.of(context).size.height *
MediaQuery.of(context).size.width *
0.00019,
width: MediaQuery.of(context).size.height *
MediaQuery.of(context).size.width *
0.00019,
fit: BoxFit.cover,
),
),
SizedBox(
width: MediaQuery.of(context).size.width * 0.06,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
serviceName,
softWrap: true,
style: TextStyle(
color: Color.fromRGBO(6, 13, 217, 1),
fontSize: 17,
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.005,
),
Text(
"Provider: " + providerName,
softWrap: true,
style: TextStyle(
color: Color.fromRGBO(6, 168, 217, 1),
fontSize: 12,
fontFamily: "Poppins"),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
Text(
"Duration (in hrs) - " + defaultSlot,
softWrap: true,
style: TextStyle(
color: Color.fromRGBO(6, 13, 217, 1),
fontSize: 9,
fontFamily: "Poppins",
fontWeight: FontWeight.bold),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
Text(
slot,
softWrap: true,
style: TextStyle(
color: Color.fromRGBO(6, 13, 217, 1),
fontSize: 12,
fontFamily: "Poppins",
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
width: MediaQuery.of(context).size.width * 0.04,
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
// SizedBox(
// height: MediaQuery.of(context).size.height * 0.01,
// ),
Container(
padding: EdgeInsets.all(6),
decoration: BoxDecoration(
color: Color.fromRGBO(6, 13, 217, 1),
borderRadius: BorderRadius.circular(40)),
width: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00020,
height: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00012,
child: FittedBox(
child: Text(
" ₹ " + price.toString(),
style: TextStyle(color: Colors.white),
),
fit: BoxFit.fitWidth,
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.04,
),
Row(
children: <Widget>[
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => productDetails(
documentSnapshot.id.toString(),
documentSnapshot['Image'],
documentSnapshot['Title'],
documentSnapshot['Price'],
documentSnapshot['Description'],
((documentSnapshot['Duration']) /
60.toInt())
.toString(),
documentSnapshot['Name'],
documentSnapshot['Email'],
documentSnapshot['UnBookedSlot'],
documentSnapshot['BookedSlot'],
documentSnapshot['UnAvailableSlot'],
documentSnapshot['Booked_Slot'])));
},
child: Text(
"Edit",
//softWrap: true,
style: TextStyle(
color: Color.fromRGBO(6, 13, 217, 1),
fontSize: 15,
fontFamily: "Poppins",
fontWeight: FontWeight.bold),
),
),
SizedBox(
width: MediaQuery.of(context).size.width * 0.02,
),
Variables().firebaseuser == null
? GestureDetector(
onTap: () {
FirebaseFirestore.instance
.collection("carts")
.doc(Variables().session_ID)
.collection("cart_items")
.doc(documentSnapshot.id)
.delete();
},
child: Text(
"Remove",
//softWrap: true,
style: TextStyle(
color: Colors.red,
fontSize: 15,
fontFamily: "Poppins",
fontWeight: FontWeight.bold),
),
)
: GestureDetector(
onTap: () {
FirebaseFirestore.instance
.collection("carts")
.doc(userid)
.collection("cart_items")
.doc(documentSnapshot.id)
.delete();
},
child: Text(
"Remove",
//softWrap: true,
style: TextStyle(
color: Colors.red,
fontSize: 15,
fontFamily: "Poppins",
fontWeight: FontWeight.bold),
),
)
],
),
],
),
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.03,
),
],
);
}
}
| 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/globalVariables.dart | import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
class Variables
{
User firebaseuser;
User provider;
String user_type;
FirebaseAuth admin_auth;
FirebaseAuth provider_auth;
String session_ID;
String service_ID;
int cartstatus;
int carttotal;
String userid;
int cart_updated;
static final Variables _singleton = new Variables._internal();
factory Variables() {
return _singleton;
}
void setUserId(String userid)
{
this.userid = userid;
}
void setCartUpdateStatus(int cart_updated)
{
this.cart_updated=cart_updated;
}
void setFIrebaseUser(User firebaseuser)
{
this.firebaseuser = firebaseuser;
}
void setAdminAuth(FirebaseAuth admin_auth)
{
this.admin_auth = admin_auth;
}
void setProviderAuth(FirebaseAuth provider_auth)
{
this.provider_auth = provider_auth;
}
void setProvider(User provider)
{
this.provider = provider;
}
void setUsertype(String user_type)
{
this.user_type=user_type;
}
void setSessionId(String session_ID)
{
this.session_ID=session_ID;
}
void setServiceID(String service_ID)
{
this.service_ID=service_ID;
}
void setCartStatus(int cartstatus)
{
this.cartstatus=cartstatus;
}
void setCartTotal(int carttotal)
{
this.carttotal=carttotal;
}
Variables._internal();
} | 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/productDisplay.dart | import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:string_validator/string_validator.dart';
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:syncfusion_flutter_calendar/calendar.dart';
class ProductDisplay extends StatefulWidget {
@override
_ProductDisplayState createState() => _ProductDisplayState();
}
class _ProductDisplayState extends State<ProductDisplay> {
FirebaseFirestore firestore = FirebaseFirestore.instance;
void _onPressed() {
firestore.collection("services").get().then((querySnapshot) {
querySnapshot.docs.forEach((result) {
print(result.data());
});
});
}
int img_flag = 0,
data_flag = 0,
title_flag = 0,
price_flag = 0,
select_img_flag = 0,
description_flag = 0,
about_flag = 0,
date_flag = 0;
String title_msg = '',
price_msg = '',
img_msg = '',
about_msg = '',
date_msg = '',
desc_msg = '';
File _image;
String _uploadedImageURL;
final title_controller = TextEditingController();
final price_controller = TextEditingController();
final product_description_controller = TextEditingController();
final about_controller = TextEditingController();
String title = '', about = '', product_desc = '', slot_duration = '';
//String price = '';
double price = 0;
CalendarView _calendarView;
List<TimeRegion> _specialTimeRegions = [];
List<DateTime> _unAvailable = [];
List<DateTime> _booked = [];
List<DateTime> _unBooked = [];
@override
void initState() {
_getTimeRegions();
_calendarView = CalendarView.week;
super.initState();
}
final picker = ImagePicker();
String dropdownValue = '1';
void _getTimeRegions() {
_specialTimeRegions = <TimeRegion>[];
_specialTimeRegions.add(TimeRegion(
startTime: DateTime(2020, 5, 29, 09, 0, 0),
endTime: DateTime(2020, 5, 29, 10, 0, 0),
recurrenceRule: 'FREQ=WEEKLY;INTERVAL=1;BYDAY=SAT,',
text: 'Special Region',
color: Colors.red,
enablePointerInteraction: true,
textStyle: TextStyle(
color: Colors.black,
fontStyle: FontStyle.italic,
fontSize: 10,
)));
}
void initialize(int slot) {
_unAvailable.clear();
_unBooked.clear();
DateTime present = DateTime.now();
DateTime date = DateTime(present.year, present.month, present.day);
DateTime max = date.add(Duration(days: 7));
print('hiii');
while (date.isBefore(max)) {
_unAvailable.add(date);
date = date.add(Duration(minutes: slot));
}
print(date);
print('hola');
print(_unAvailable);
}
void calendarTapped(CalendarTapDetails calendarTapDetails) {
DateTime dates;
//print(DateTime.now().month);
_specialTimeRegions.add(TimeRegion(
startTime: calendarTapDetails.date,
endTime: calendarTapDetails.date
.add(Duration(minutes: (double.parse(dropdownValue) * 60).toInt())),
//text: 'tap',
color: Color(0xffbD3D3D3),
));
setState(() {
dates = calendarTapDetails.date;
print(dates);
_unBooked.add(dates);
_unAvailable.remove(dates);
print(_unBooked);
print('TEST');
print(_unAvailable);
});
}
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
Future uploadFile() async {
firebase_storage.Reference storageReference = firebase_storage
.FirebaseStorage.instance
.ref()
.child('services/${title}/display_image_${title}.png');
firebase_storage.UploadTask uploadTask = storageReference.putFile(_image);
await uploadTask.whenComplete(() => {
print('File Uploaded'),
storageReference.getDownloadURL().then((fileURL) {
setState(() {
_uploadedImageURL = fileURL;
// print('I am here!!!!!'+_uploadedImageURL);
});
})
});
await uploadTask.catchError((error) => {
setState(() {
img_flag = 1;
print(error);
})
});
}
CollectionReference services =
FirebaseFirestore.instance.collection('services');
Future<void> addService() {
// Call the user's CollectionReference to add a new user
return services
.add({
'Image': _uploadedImageURL.toString(),
'Title': title, // John Doe
'Price': price, // Stokes and Sons
'Description': product_desc,
'UnAvailableSlot': _unAvailable,
'UnBookedSlot': _unBooked,
'BookedSlot': _booked,
'Duration': slot_duration,
'About': about,
})
.then((value) => print("Service Added"))
.catchError((error) => {
print("Failed to add user: $error"),
setState(() {
data_flag = 1;
})
});
}
void validator() {
if (_image == null) {
setState(() {
select_img_flag = 1;
img_msg = 'Upload Image';
});
}
if (title == '') {
setState(() {
title_flag = 1;
title_msg = 'Field Required';
});
} else if (!(isAlphanumeric(title))) {
if (title.contains(' ')) {
setState(() {
title_flag = 0;
});
} else {
setState(() {
title_flag = 1;
title_msg = 'Invalid Title';
});
}
}
if (price == 0) {
setState(() {
price_flag = 1;
price_msg = 'Field Required';
});
} else if (price < 0) {
setState(() {
price_flag = 1;
price_msg = 'Invalid Price';
});
}
if (product_desc == '') {
setState(() {
description_flag = 1;
desc_msg = 'Field Required';
});
} else if (isNumeric(product_desc)) {
setState(() {
description_flag = 1;
desc_msg = 'Invalid Description';
});
}
if (_unBooked.isEmpty) {
setState(() {
date_flag = 1;
date_msg = 'Date Required';
});
}
if (about == '') {
setState(() {
about_flag = 1;
about_msg = 'Field Required';
});
} else if (isNumeric(about)) {
setState(() {
about_flag = 1;
about_msg = 'Invalid About';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: <Widget>[
SizedBox(
height: MediaQuery.of(context).size.height * 0.10,
),
Container(
child: Row(
children: <Widget>[
Container(
child: Column(
children: [
GestureDetector(
//onTap: getImage,
child: Container(
clipBehavior: Clip.antiAlias,
child: _image == null
? Align(
child: Text(
'No image selected.',
style: TextStyle(fontFamily: "Poppins"),
),
alignment: Alignment.center,
)
: FittedBox(
//child: Image.file(_image),
fit: BoxFit.fill,
),
margin: EdgeInsets.symmetric(
horizontal:
MediaQuery.of(context).size.width * 0.11),
decoration: BoxDecoration(
border: Border.all(), shape: BoxShape.circle),
height: MediaQuery.of(context).size.height * 0.15,
width: MediaQuery.of(context).size.width * 0.32,
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.02),
select_img_flag == 0
? SizedBox(height: 0)
: Container(
child: Text('*' + img_msg,
style: TextStyle(color: Colors.red)),
),
],
),
),
Container(
height: MediaQuery.of(context).size.height * 0.25,
width: MediaQuery.of(context).size.width * 0.30,
child: Column(
children: <Widget>[
TextField(
controller: title_controller,
decoration: InputDecoration(hintText: 'Set Title'),
),
title_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + title_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.02,
),
TextField(
controller: price_controller,
keyboardType: TextInputType.number,
decoration: InputDecoration(hintText: 'Set Price'),
),
price_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + price_msg,
style: TextStyle(color: Colors.red))),
],
),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.03,
),
Container(
height: MediaQuery.of(context).size.height * 0.20,
width: MediaQuery.of(context).size.width * 0.75,
padding: EdgeInsets.all(MediaQuery.of(context).size.width * 0.02),
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.circular(60)),
child: TextField(
controller: product_description_controller,
textAlign: TextAlign.center,
keyboardType: TextInputType.multiline,
minLines: 1,
maxLines: 5,
decoration: InputDecoration(
hintText: 'Add Product Description',
)),
),
description_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + desc_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.04,
),
// Container(
// height: MediaQuery.of(context).size.height * 0.30,
// width: MediaQuery.of(context).size.width * 0.80,
// child: FittedBox(
// fit: BoxFit.contain,
// child: SfDateRangePicker(
// onSelectionChanged: _onSelectionChanged,
// selectionMode: DateRangePickerSelectionMode.multiple,
// enablePastDates: false,
// ),
// ),
// ),
Container(
height: MediaQuery.of(context).size.height * 0.03,
width: MediaQuery.of(context).size.width * 0.75,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Select Slot Duration(in hrs)'),
SizedBox(width: MediaQuery.of(context).size.width * 0.03),
DropdownButton<String>(
value: dropdownValue,
icon: Icon(Icons.arrow_downward_rounded),
iconSize: 17,
elevation: 16,
// style: TextStyle(color: Colors.deepPurple),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
// ignore: unnecessary_statements
initialize(
(double.parse(dropdownValue) * 60).toInt());
print(dropdownValue);
});
},
items: <String>['0.5', '1', '2']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: TextStyle(
fontSize: 20,
),
),
);
}).toList(),
)
],
)),
SizedBox(
height: MediaQuery.of(context).size.height * 0.04,
),
Container(
child: SfCalendar(
view: CalendarView.week,
specialRegions: _specialTimeRegions,
minDate: DateTime.now(),
maxDate: DateTime.now().add(Duration(days: 6)),
// onViewChanged: viewChanged,
onTap: calendarTapped,
//onLongPress: longPressed,
timeSlotViewSettings: TimeSlotViewSettings(
timeInterval: Duration(
minutes: (double.parse(dropdownValue) * 60).toInt()),
timeFormat: 'hh:mm a'),
),
),
date_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + date_msg,
style: TextStyle(color: Colors.red))),
SizedBox(height: MediaQuery.of(context).size.height * 0.03),
SizedBox(height: MediaQuery.of(context).size.height * 0.03),
Container(
height: MediaQuery.of(context).size.height * 0.20,
width: MediaQuery.of(context).size.width * 0.75,
padding: EdgeInsets.all(MediaQuery.of(context).size.width * 0.02),
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.circular(60)),
child: TextField(
controller: about_controller,
textAlign: TextAlign.center,
keyboardType: TextInputType.multiline,
minLines: 1,
maxLines: 5,
decoration: InputDecoration(
hintText: 'About ',
)),
),
about_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + about_msg,
style: TextStyle(color: Colors.red))),
SizedBox(height: MediaQuery.of(context).size.height * 0.05),
ButtonTheme(
height: MediaQuery.of(context).size.height * 0.05,
minWidth: MediaQuery.of(context).size.width * 0.25,
buttonColor: Color.fromRGBO(6, 13, 217, 1),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
child: Row(
children: <Widget>[
RaisedButton(child: Text('Back'), onPressed: null),
SizedBox(width: MediaQuery.of(context).size.width * 0.05),
RaisedButton(
onPressed: () {
setState(() {
title = title_controller.text;
price = double.parse(price_controller.text);
product_desc = product_description_controller.text;
about = about_controller.text;
slot_duration = dropdownValue;
title_flag = 0;
price_flag = 0;
about_flag = 0;
description_flag = 0;
select_img_flag = 0;
date_flag = 0;
});
validator();
if (about_flag == 0 &&
date_flag == 0 &&
select_img_flag == 0 &&
title_flag == 0 &&
price_flag == 0 &&
description_flag == 0) {
uploadFile();
addService();
if (img_flag == 0 && data_flag == 0) {
Fluttertoast.showToast(
msg: "Service added Successfully!",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 16.0);
} else {
Fluttertoast.showToast(
msg: "Error adding Service! Try Again.",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
}
} else {
Fluttertoast.showToast(
msg: "Fill all the required Fields!!",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
}
},
child: Text(
"Add to Cart",
style: TextStyle(
color: Colors.white,
fontFamily: "Poppins",
fontWeight: FontWeight.bold,
fontSize: MediaQuery.of(context).size.width * 0.045),
),
),
],
),
),
SizedBox(height: MediaQuery.of(context).size.height * 0.05),
//_image == null ? Text('null') : Text('${_image.absolute}')
],
),
),
);
}
}
| 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/providerSignUp.dart | import 'dart:async';
//import './providerEmailVerification.dart';
import 'package:SetItUp/providerEmailVerification.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:string_validator/string_validator.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:syncfusion_flutter_calendar/calendar.dart';
import 'globalVariables.dart';
import 'package:uuid/uuid.dart';
class ProviderSignUp extends StatefulWidget {
@override
_ProviderSignUpState createState() => _ProviderSignUpState();
}
class _ProviderSignUpState extends State<ProviderSignUp> {
var uuid = Uuid();
User user;
int email_flag = 0, username_flag = 0, password_flag = 0;
String email_msg = '', username_msg = '', password_msg = '';
int register_flag = 0;
String email = '', username = '', password = '';
final email_controller = TextEditingController();
final username_controller = TextEditingController();
final password_controller = TextEditingController();
FirebaseAuth providerauth = FirebaseAuth.instance;
String provider_id;
void Validator() {
if (email == '') {
setState(() {
email_flag = 1;
email_msg = 'Field Required';
});
} else if (!(RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(email))) {
setState(() {
email_flag = 1;
email_msg = 'Invalid Email';
});
} else {
email_flag = 0;
}
if (username == '') {
setState(() {
username_flag = 1;
username_msg = 'Field Required';
});
} else if (!(RegExp(r'^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$')
.hasMatch(username))) {
setState(() {
username_flag = 1;
username_msg = 'Invalid Username';
});
} else {
setState(() {
username_flag = 0;
//Fluttertoast.showToast(msg: username);
});
}
if (password == '') {
setState(() {
password_flag = 1;
password_msg = 'Field Required';
});
} else if (!(RegExp(
"^(?=.{8,32}\$)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#\$%^&*(),.?:{}|<>]).*")
.hasMatch(password))) {
setState(() {
password_flag = 1;
password_msg = 'Password is too weak!';
});
} else {
password_flag = 0;
}
}
createUser() async {
try {
UserCredential userCredential = await providerauth
.createUserWithEmailAndPassword(email: email, password: password);
//user = userCredential.user;
Variables().setProvider(userCredential.user);
Variables().setProviderAuth(providerauth);
Fluttertoast.showToast(
msg: "Sign Up Succesful!",
textColor: Colors.white,
backgroundColor: Colors.green);
await Variables().provider.sendEmailVerification();
provider_id = uuid.v4();
await Fluttertoast.showToast(
msg: "Verification link has been sent to your email");
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
Fluttertoast.showToast(msg: 'The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
Fluttertoast.showToast(
msg: 'The account already exists for that email.');
}
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
//crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
Container(
height: MediaQuery.of(context).size.height * 0.25,
width: MediaQuery.of(context).size.width,
child: Image.asset(
"assets/images/setitup_final.png",
fit: BoxFit.contain,
)),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
Container(
alignment: Alignment.center,
child: Text(
"Create Provider Account",
style: TextStyle(
fontFamily: "Poppins",
fontSize: 20,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(6, 13, 217, 1)),
),
),
SizedBox(height: MediaQuery.of(context).size.height * 0.03),
Container(
margin: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width * 0.10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Email",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1)),
),
TextField(
controller: email_controller,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50))),
),
email_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + email_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.035,
),
Text(
"Username",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1)),
),
TextField(
controller: username_controller,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50))),
),
username_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + username_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.035,
),
Text(
"Password",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1)),
),
TextField(
controller: password_controller,
obscureText: true,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50))),
),
password_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + password_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
)
],
),
),
ButtonTheme(
height: MediaQuery.of(context).size.height * 0.05,
minWidth: MediaQuery.of(context).size.width * 0.25,
buttonColor: Color.fromRGBO(6, 13, 217, 1),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
child: RaisedButton(
onPressed: () async {
setState(() {
email = email_controller.text;
username = username_controller.text;
password = password_controller.text;
});
Validator();
if (email_flag == 0 &&
username_flag == 0 &&
password_flag == 0) {
await createUser();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProviderEmailVerification(
provider_id, email, username, password)));
//sendEmail();
// if (Variables().firebaseuser!=null) {
// //print("inside if");
// Timer(Duration(seconds: 10), () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) =>
// emailVerificationProgress()));
// });
// }
}
},
child: Text(
"Sign Up",
style: TextStyle(
color: Colors.white,
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.045,
fontWeight: FontWeight.bold,
),
),
),
),
// Container(
// margin: EdgeInsets.symmetric(
// vertical: MediaQuery.of(context).size.height * 0.04),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.center,
// children: <Widget>[
// Text(
// "Already a User?",
// style: TextStyle(
// fontFamily: "Poppins",
// fontSize: MediaQuery.of(context).size.width * 0.035,
// color: Color.fromRGBO(6, 13, 217, 1)),
// ),
// GestureDetector(
// onTap: () {
// Navigator.pop(context);
// },
// child: Text(" SignIn",
// style: TextStyle(
// fontFamily: "Poppins",
// fontWeight: FontWeight.bold,
// fontSize: MediaQuery.of(context).size.width * 0.035,
// color: Color.fromRGBO(6, 13, 217, 1))),
// )
// ],
// ),
// ),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/userEmailVerificaton.dart | import 'dart:async';
import 'package:SetItUp/cart.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
//import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'globalVariables.dart';
import 'homescreen.dart';
class UserEmailVerification extends StatelessWidget {
final String user_id;
final String email;
final String username;
final String password;
UserEmailVerification(this.user_id, this.email, this.username, this.password);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: userProgressPage(user_id, email, username, password),
);
}
}
class userProgressPage extends StatefulWidget {
final String user_id;
final String email;
final String username;
final String password;
userProgressPage(this.user_id, this.email, this.username, this.password);
@override
_userProgressPageState createState() =>
_userProgressPageState(user_id, email, username, password);
}
class _userProgressPageState extends State<userProgressPage> {
final String user_id;
final String email;
final String username;
final String password;
_userProgressPageState(
this.user_id, this.email, this.username, this.password);
bool isEmailVerified = false;
Timer timer;
void checkStatus() async {
User user = FirebaseAuth.instance.currentUser;
await user.reload();
Variables().setFIrebaseUser(user);
setState(() {
isEmailVerified = user.emailVerified;
});
}
Future<void> addUser() {
String path = 'users/' + user_id;
FirebaseFirestore.instance
.doc(path)
.set({'Email': email, 'Username': username, 'Password': password})
.then((value) => print("User Added"))
.catchError((error) => {
print("Failed to add user: $error"),
});
;
// Call the user's CollectionReference to add a new user
// return users
// .set({'Email': email, 'Username': username, 'Password': password})
// .then((value) => print("User Added"))
// .catchError((error) => {
// print("Failed to add user: $error"),
// });
}
// void updateCart()
// {
// }
@override
void initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 4), (timer) {
checkStatus();
if (isEmailVerified == true) {
addUser();
timer.cancel();
}
});
}
@override
void dipose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: isEmailVerified != true
? <Widget>[
Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Color.fromRGBO(6, 13, 217, 1)),
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
Text("Verify email to proceed")
]
: <Widget>[
Center(
child: Icon(
Icons.check,
color: Color.fromRGBO(6, 13, 217, 1),
size: MediaQuery.of(context).size.width * 0.20,
)),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
Text("Email verified Successfully!"),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
Variables().cartstatus!=1?
ButtonTheme(
buttonColor: Color.fromRGBO(6, 13, 217, 1),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
child: ElevatedButton(
child: Text(
"Proceed to Home Screen",
style: TextStyle(color: Colors.white),
),
onPressed: () {
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => HomeScreen()));
},
),
):ButtonTheme(
buttonColor: Color.fromRGBO(6, 13, 217, 1),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
child: ElevatedButton(
child: Text(
"Proceed to Cart",
style: TextStyle(color: Colors.white),
),
onPressed: () {
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => Cart()));
},
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/data.dart |
import 'package:SetItUp/events_model.dart';
List<ChatModel> getChats()
{
List<ChatModel> chats = new List();
ChatModel chatModel = new ChatModel();
//1
chatModel.name = "Atharva Kulkarni";
chatModel.imgUrl ="https://images.unsplash.com/photo-1521572267360-ee0c2909d518?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=60";
chatModel.lastMessage ="Guitar Class";
chatModel.lastSeenTime = "5m";
chatModel.haveunreadmessages = true;
chatModel.unreadmessages = 1;
chats.add(chatModel);
chatModel = new ChatModel();
//1
chatModel.name = "Adwait Gondhalekar";
chatModel.imgUrl = "https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=934&q=80";
chatModel.lastMessage = "Dance class";
chatModel.lastSeenTime = "5 m";
chatModel.haveunreadmessages = false;
chatModel.unreadmessages = 1;
chats.add(chatModel);
chatModel = new ChatModel();
//1
chatModel.name = "Vidit Bapat";
chatModel.imgUrl = "https://images.unsplash.com/photo-1521572267360-ee0c2909d518?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=60";
chatModel.lastMessage = "Tabla class";
chatModel.lastSeenTime = "1 hr";
chatModel.haveunreadmessages = false;
chatModel.unreadmessages = 1;
chats.add(chatModel);
chatModel = new ChatModel();
chatModel.name = "Nidhi Abhyankar";
chatModel.imgUrl = "https://images.unsplash.com/photo-1521572267360-ee0c2909d518?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=60";
chatModel.lastMessage = "Singing class";
chatModel.lastSeenTime = "1 hr";
chatModel.haveunreadmessages = false;
chatModel.unreadmessages = 1;
chats.add(chatModel);
chatModel = new ChatModel();
chatModel.name = "Nidhi Abhyankar";
chatModel.imgUrl = "https://images.unsplash.com/photo-1521572267360-ee0c2909d518?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=60";
chatModel.lastMessage = "Singing class";
chatModel.lastSeenTime = "1 hr";
chatModel.haveunreadmessages = false;
chatModel.unreadmessages = 1;
chats.add(chatModel);
chatModel = new ChatModel();
chatModel.name = "Nidhi Abhyankar";
chatModel.imgUrl = "https://images.unsplash.com/photo-1521572267360-ee0c2909d518?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=60";
chatModel.lastMessage = "Singing class";
chatModel.lastSeenTime = "1 hr";
chatModel.haveunreadmessages = false;
chatModel.unreadmessages = 1;
chats.add(chatModel);
chatModel = new ChatModel();
chatModel.name = "Nidhi Abhyankar";
chatModel.imgUrl = "https://images.unsplash.com/photo-1521572267360-ee0c2909d518?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=60";
chatModel.lastMessage = "Singing class";
chatModel.lastSeenTime = "1 hr";
chatModel.haveunreadmessages = false;
chatModel.unreadmessages = 1;
chats.add(chatModel);
chatModel = new ChatModel();
chatModel.name = "Nidhi Abhyankar";
chatModel.imgUrl = "https://images.unsplash.com/photo-1521572267360-ee0c2909d518?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=60";
chatModel.lastMessage = "Singing class";
chatModel.lastSeenTime = "1 hr";
chatModel.haveunreadmessages = false;
chatModel.unreadmessages = 1;
chats.add(chatModel);
chatModel = new ChatModel();
chatModel.name = "Nidhi Abhyankar";
chatModel.imgUrl = "https://images.unsplash.com/photo-1521572267360-ee0c2909d518?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=60";
chatModel.lastMessage = "Singing class";
chatModel.lastSeenTime = "1 hr";
chatModel.haveunreadmessages = false;
chatModel.unreadmessages = 1;
chats.add(chatModel);
return chats;
} | 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/productDetails.dart | import 'dart:async';
import 'package:SetItUp/globalVariables.dart';
import 'package:SetItUp/userSignIn.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:syncfusion_flutter_calendar/calendar.dart';
import 'cart.dart';
import 'package:intl/intl.dart';
class productDetails extends StatefulWidget {
String serviceid;
String productImage;
String productTitle;
int productPrice;
String productDesc;
String providerName;
String providerEmail;
int productDuration;
String booked_slot;
List<dynamic> _unBooked_nc = [];
List<dynamic> _booked_nc = [];
List<dynamic> _unAvailable_nc = [];
productDetails(
String serviceid,
String image,
String title,
int price,
String desc,
String productDuration,
String name,
String email,
List<dynamic> _unBooked_nc,
List<dynamic> _booked_nc,
List<dynamic> _unAvailable_nc,
String booked_slot) {
this.serviceid = serviceid;
this.productImage = image;
this.productTitle = title;
this.productPrice = price;
this.productDesc = desc;
this.providerName = name;
this.providerEmail = email;
this._unBooked_nc = _unBooked_nc;
this._booked_nc = _booked_nc;
this._unAvailable_nc = _unAvailable_nc;
this.productDuration = (double.parse(productDuration) * 60).toInt();
this.booked_slot = booked_slot;
}
@override
_productDetailsState createState() => _productDetailsState();
}
class _productDetailsState extends State<productDetails> {
String dropdownvalue;
List<String> converted = [];
List<DateTime> _unAvailable = [];
List<DateTime> _booked = [];
List<DateTime> _unBooked = [];
void convert(List<Timestamp> list_1, List<DateTime> list_2) {
DateTime x;
Timestamp y;
for (int i = 0; i < list_1.length; i++) {
y = list_1[i];
x = y.toDate();
if (x.isAfter(DateTime.now())) {
list_2.add(x);
}
}
}
void convertDateTime() {
_unBooked.forEach((element) {
converted.add("Date : " +
DateFormat('dd-MM-yyyy – kk:mm').format(element) +
" to " +
(DateFormat('kk:mm')
.format(element.add(Duration(minutes: widget.productDuration)))));
});
}
void checkbookedslot() {
if (widget.booked_slot != "null") {
setState(() {
dropdownvalue = widget.booked_slot;
});
}
}
@override
void initState() {
// TODO: implement initState
super.initState();
if (widget._unBooked_nc.isNotEmpty) {
List<Timestamp> a = widget._unBooked_nc.cast();
print("Converted" + a[0].toDate().toString());
convert(a, _unBooked);
print(_unBooked);
}
if (widget._booked_nc.isNotEmpty) {
List<Timestamp> b = widget._booked_nc.cast();
print("Converted" + b[0].toDate().toString());
convert(b, _booked);
print(_booked);
}
if (widget._unAvailable_nc.isNotEmpty) {
List<Timestamp> c = widget._unAvailable_nc.cast();
print("Converted" + c[0].toDate().toString());
convert(c, _unAvailable);
print(_unAvailable);
}
convertDateTime();
checkbookedslot();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
Align(
alignment: Alignment.topLeft,
child: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Container(
//alignment: Alignment.topLeft,
//decoration: BoxDecoration(border: Border.all()),
margin: EdgeInsets.only(
left: MediaQuery.of(context).size.width * 0.02),
child: Icon(
Icons.arrow_back_ios_sharp,
color: Color.fromRGBO(6, 13, 217, 1),
size: MediaQuery.of(context).size.height *
MediaQuery.of(context).size.width *
0.00011,
),
),
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.035,
),
// Container(
// decoration: BoxDecoration(border: Border.all()),
// )
Container(
padding: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width * 0.05),
//decoration: BoxDecoration(border: Border.all()),
child: Row(
//mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
// SizedBox(
// width: MediaQuery.of(context).size.width * 0.05,
// ),
Container(
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.circular(60)),
child: ClipRRect(
borderRadius: BorderRadius.circular(60),
child: Image.network(
widget.productImage,
height: MediaQuery.of(context).size.height *
MediaQuery.of(context).size.width *
0.00032,
width: MediaQuery.of(context).size.height *
MediaQuery.of(context).size.width *
0.00032,
fit: BoxFit.cover,
),
),
),
SizedBox(
width: MediaQuery.of(context).size.width * 0.08,
),
Expanded(
child: Column(
children: <Widget>[
// SizedBox(
// height: MediaQuery.of(context).size.height * 0.01,
// ),
Text(
widget.productTitle,
softWrap: true,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
color: Color.fromRGBO(6, 13, 217, 1),
fontFamily: 'Poppins',
fontWeight: FontWeight.bold,
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
Container(
padding: EdgeInsets.all(6),
decoration: BoxDecoration(
color: Color.fromRGBO(6, 13, 217, 1),
borderRadius: BorderRadius.circular(40)),
width: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00025,
height: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00012,
child: FittedBox(
child: Text(
" ₹ " + widget.productPrice.toString(),
style: TextStyle(
color: Colors.white,
),
),
fit: BoxFit.fitWidth,
),
),
],
),
),
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
Container(
margin: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width * 0.10),
padding: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width * 0.04,
vertical: MediaQuery.of(context).size.height * 0.02),
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.circular(35)),
child: Text(
widget.productDesc,
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Poppinns',
fontSize: 16,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(6, 13, 217, 1),
),
)),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
Container(
margin: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width * 0.10),
padding: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width * 0.04,
vertical: MediaQuery.of(context).size.height * 0.02),
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.circular(35)),
child: Column(
children: [
Text(
'Provider : ' + widget.providerName,
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Poppinns',
fontSize: 16,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(6, 13, 217, 1),
),
),
Text(
widget.providerEmail,
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Poppinns',
fontSize: 16,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(6, 13, 217, 1),
),
),
],
)),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
Text(
"Duration (in hrs) - " +
(widget.productDuration / 60).toInt().toString(),
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Poppinns',
fontSize: 16,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(6, 13, 217, 1),
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
DropdownButton<String>(
hint: Text("Select a slot"),
value: dropdownvalue,
items: converted.map<DropdownMenuItem<String>>((String slot) {
return DropdownMenuItem<String>(
value: slot,
child: Row(
children: <Widget>[
// Text("Date : "+DateFormat('dd-MM-yyyy – kk:mm').format(slot) +
// " to " +
// (DateFormat('kk:mm').format(slot.add(Duration(minutes: widget.productDuration )))))
Text(slot)
],
),
);
}).toList(),
onChanged: (String dateTime) {
setState(() {
dropdownvalue = dateTime;
});
print(dropdownvalue);
}),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
Variables().firebaseuser==null
? ButtonTheme(
height: MediaQuery.of(context).size.height * 0.05,
minWidth: MediaQuery.of(context).size.width * 0.25,
buttonColor: Color.fromRGBO(6, 13, 217, 1),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
child: ElevatedButton(
onPressed: () {
// if (Variables().firebaseuser == null) {
// Fluttertoast.showToast(
// msg: "Please sign in before proceeding to cart");
// Timer(Duration(seconds: 2), () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => userSignIn()));
// });
// } else if (dropdownvalue == null) {
// Fluttertoast.showToast(msg: "Please Select a Slot !!");
// } else
// addProduct();
if (dropdownvalue == null) {
Fluttertoast.showToast(msg: "Please Select a Slot !!");
} else
addProduct();
},
child: Text(
"Add to Cart",
style: TextStyle(
color: Colors.white,
fontFamily: "Poppins",
fontWeight: FontWeight.bold,
fontSize: 18),
),
),
)
: Variables().user_type!='admin'?
Variables().firebaseuser.email!=widget.providerEmail?
ButtonTheme(
height: MediaQuery.of(context).size.height * 0.05,
minWidth: MediaQuery.of(context).size.width * 0.25,
buttonColor: Color.fromRGBO(6, 13, 217, 1),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
child: ElevatedButton(
onPressed: () {
// if (Variables().firebaseuser == null) {
// Fluttertoast.showToast(
// msg: "Please sign in before proceeding to cart");
// Timer(Duration(seconds: 2), () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => userSignIn()));
// });
// } else if (dropdownvalue == null) {
// Fluttertoast.showToast(msg: "Please Select a Slot !!");
// } else
// addProduct();
if (dropdownvalue == null) {
Fluttertoast.showToast(msg: "Please Select a Slot !!");
} else
addProduct();
},
child: Text(
"Add to Cart",
style: TextStyle(
color: Colors.white,
fontFamily: "Poppins",
fontWeight: FontWeight.bold,
fontSize: 18),
),
),
):
SizedBox():
SizedBox(),
],
),
);
}
Future<void> addProduct() {
if (Variables().firebaseuser == null) {
FirebaseFirestore.instance
.collection('carts')
.doc(Variables().session_ID)
.set({'Dummy': 'dummy'});
//String docpath = 'carts/' + Variables().session_ID;
FirebaseFirestore.instance
.collection('carts')
.doc(Variables().session_ID)
.collection('/cart_items')
.doc(widget.serviceid)
//.update({'Booked_Slot':dropdownvalue})
.set({
'Image': widget.productImage,
'Title': widget.productTitle, // John Doe
'Price': widget.productPrice, // Stokes and Sons
'Description': widget.productDesc,
'UnAvailableSlot': widget._unAvailable_nc,
'UnBookedSlot': widget._unBooked_nc,
'BookedSlot': widget._booked_nc,
'Duration': widget.productDuration,
'Email': widget.providerEmail,
'Name': widget.providerName,
'Booked_Slot': dropdownvalue
})
.then((value) => Navigator.push(
context, MaterialPageRoute(builder: (context) => Cart())))
// Fluttertoast.showToast(msg: "added to cart"))
.catchError((error) => {
Fluttertoast.showToast(
msg: "Failed to add product: $error",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 16.0),
setState(() {
//data_flag = 1;
})
});
} else {
FirebaseFirestore.instance
.collection('carts')
.doc(Variables().session_ID)
.set({'Dummy': 'dummy'});
//String docpath = 'carts/' + Variables().userid;
FirebaseFirestore.instance
.collection('carts')
.doc(Variables().userid)
.collection('/cart_items')
.doc(widget.serviceid)
//.update({'Booked_Slot':dropdownvalue})
.set({
'Image': widget.productImage,
'Title': widget.productTitle, // John Doe
'Price': widget.productPrice, // Stokes and Sons
'Description': widget.productDesc,
'UnAvailableSlot': widget._unAvailable_nc,
'UnBookedSlot': widget._unBooked_nc,
'BookedSlot': widget._booked_nc,
'Duration': widget.productDuration,
'Email': widget.providerEmail,
'Name': widget.providerName,
'Booked_Slot': dropdownvalue
})
.then((value) => Navigator.push(
context, MaterialPageRoute(builder: (context) => Cart())))
// Fluttertoast.showToast(msg: "added to cart"))
.catchError((error) => {
Fluttertoast.showToast(
msg: "Failed to add product: $error",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 16.0),
setState(() {
//data_flag = 1;
})
});
}
}
}
| 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/signInOptions.dart | import 'package:SetItUp/adminSignin.dart';
import 'package:SetItUp/userSignIn.dart';
import 'package:flutter/material.dart';
import './userSignIn.dart';
import './providerSignIn.dart';
import './productDisplay.dart';
class SignInOptions extends StatefulWidget {
@override
_SignInOptionsState createState() => _SignInOptionsState();
}
class _SignInOptionsState extends State<SignInOptions> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
alignment: Alignment.center,
child: ButtonTheme(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
minWidth: MediaQuery.of(context).size.width * 0.3,
height: MediaQuery.of(context).size.height * 0.05,
child: RaisedButton(
color: Color.fromRGBO(6, 13, 217, 1),
child: Text(
'Sign in as a User',
style: TextStyle(color: Colors.white,fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => userSignIn()));
},
)),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.15,
),
Container(
alignment: Alignment.center,
child: ButtonTheme(
minWidth: MediaQuery.of(context).size.width * 0.3,
height: MediaQuery.of(context).size.height * 0.05,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
child: RaisedButton(
color: Color.fromRGBO(6, 13, 217, 1),
child: Text(
'Sign in as a Service Provider',
style: TextStyle(color: Colors.white,fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => ProviderSignIn()));
},
)),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.15,
),
Container(
alignment: Alignment.center,
child: ButtonTheme(
minWidth: MediaQuery.of(context).size.width * 0.3,
height: MediaQuery.of(context).size.height * 0.05,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
child: RaisedButton(
color: Color.fromRGBO(6, 13, 217, 1),
child: Text(
'Sign in as an Administrator',
style: TextStyle(color: Colors.white,fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => adminSignIn ()));
},
)),
),
],
));
}
}
| 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/events_model.dart | class ChatModel
{
String imgUrl;
String name;
String lastMessage;
bool haveunreadmessages;
int unreadmessages;
String lastSeenTime;
} | 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/addservice.dart | import 'dart:async';
import 'package:SetItUp/globalVariables.dart';
import 'package:SetItUp/homescreen.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:string_validator/string_validator.dart';
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:syncfusion_flutter_calendar/calendar.dart';
import 'package:uuid/uuid.dart';
class AddService extends StatefulWidget {
final String email;
final String usern;
AddService(this.email, this.usern);
@override
_AddServiceState createState() => _AddServiceState(email, usern);
}
class _AddServiceState extends State<AddService> {
final String email;
final String usern;
_AddServiceState(this.email, this.usern);
FirebaseFirestore firestore = FirebaseFirestore.instance;
//String username;
int img_flag = 0,
data_flag = 0,
title_flag = 0,
price_flag = 0,
select_img_flag = 0,
description_flag = 0,
email_flag = 0,
date_flag = 0,
provider_name_flag = 0;
String title_msg = '',
price_msg = '',
img_msg = '',
email_msg = '',
date_msg = '',
desc_msg = '',
provider_name_msg = '';
File _image;
var _uploadedImageURL;
final title_controller = TextEditingController();
final price_controller = TextEditingController();
final product_description_controller = TextEditingController();
final provider_name_controller = TextEditingController();
String title = '', product_desc = '', slot_duration = '', provider_name = '';
//String price = '';
double price ;
CalendarView _calendarView;
List<TimeRegion> _specialTimeRegions = [];
List<DateTime> _unAvailable = [];
List<DateTime> _booked = [];
List<DateTime> _unBooked = [];
@override
void initState() {
_getTimeRegions();
_calendarView = CalendarView.week;
//RetrieveUser();
super.initState();
}
final picker = ImagePicker();
String dropdownValue = '1';
void _getTimeRegions() {
_specialTimeRegions = <TimeRegion>[];
_specialTimeRegions.add(TimeRegion(
startTime: DateTime(2020, 5, 29, 09, 0, 0),
endTime: DateTime(2020, 5, 29, 10, 0, 0),
recurrenceRule: 'FREQ=WEEKLY;INTERVAL=1;BYDAY=SAT,',
text: 'Special Region',
color: Colors.red,
enablePointerInteraction: true,
textStyle: TextStyle(
color: Colors.black,
fontStyle: FontStyle.italic,
fontSize: 10,
)));
}
void initialize(int slot) {
_unAvailable.clear();
_unBooked.clear();
DateTime present = DateTime.now();
DateTime date = DateTime(present.year, present.month, present.day);
DateTime max = date.add(Duration(days: 7));
//print('hiii');
while (date.isBefore(max)) {
_unAvailable.add(date);
date = date.add(Duration(minutes: slot));
}
}
void calendarTapped(CalendarTapDetails calendarTapDetails) {
DateTime dates;
//print(DateTime.now().month);
_specialTimeRegions.add(TimeRegion(
startTime: calendarTapDetails.date,
endTime: calendarTapDetails.date
.add(Duration(minutes: (double.parse(dropdownValue) * 60).toInt())),
//text: 'tap',
color: Color(0xffbD3D3D3),
));
setState(() {
dates = calendarTapDetails.date;
_unBooked.add(dates);
_unAvailable.remove(dates);
});
}
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
void getServiceId() {
var uuid = Uuid();
String service_id = uuid.v4();
Variables().setServiceID(service_id);
}
Future uploadFile() async {
firebase_storage.Reference storageReference = firebase_storage
.FirebaseStorage.instance
.ref()
.child('services/'+Variables().service_ID+'/${title}.png');
firebase_storage.UploadTask uploadTask = storageReference.putFile(_image);
//var image_Url;
uploadTask
.then((tasksnapshot) async => {
_uploadedImageURL = await storageReference.getDownloadURL(),
addService()
})
.catchError((error) => {
setState(() {
img_flag = 1;
print(error);
})
});
}
Future<void> addService() {
String path = 'services/' + Variables().service_ID;
FirebaseFirestore.instance
.doc(path)
.set({
'Image': _uploadedImageURL.toString(),
'Title': title, // John Doe
'Price': price.toInt(), // Stokes and Sons
'Description': product_desc,
'UnAvailableSlot': _unAvailable,
'UnBookedSlot': _unBooked,
'BookedSlot': _booked,
'Duration': slot_duration,
'Email': email,
'Name': usern,
})
.then((value) => print("Service Added" + _uploadedImageURL))
.catchError((error) => {
print("Failed to add user: $error"),
setState(() {
data_flag = 1;
})
});
// Call the user's CollectionReference to add a new user
/* return services
.add({
'Image': _uploadedImageURL.toString(),
'Title': title, // John Doe
'Price': price, // Stokes and Sons
'Description': product_desc,
'UnAvailableSlot': _unAvailable,
'UnBookedSlot': _unBooked,
'BookedSlot': _booked,
'Duration': slot_duration,
'Email': email,
'Name': usern,
})
.then((value) => print("Service Added" + _uploadedImageURL))
.catchError((error) => {
print("Failed to add user: $error"),
setState(() {
data_flag = 1;
})
});*/
}
void validator() {
if (_image == null) {
setState(() {
select_img_flag = 1;
img_msg = 'Upload Image';
});
}
if (title == '') {
setState(() {
title_flag = 1;
title_msg = 'Field Required';
});
} else if (!(isAlphanumeric(title))) {
if (title.contains(' ')) {
setState(() {
title_flag = 0;
});
} else {
setState(() {
title_flag = 1;
title_msg = 'Invalid Title';
});
}
}
// if (provider_name == '') {
// setState(() {
// provider_name_flag = 1;
// provider_name_msg = 'Full Name Required';
// });
// } else if (!(isAlpha(provider_name))) {
// if (provider_name.contains(' ')) {
// setState(() {
// provider_name_flag = 0;
// });
// } else {
// setState(() {
// provider_name_flag = 1;
// provider_name_msg = 'Invalid Name';
// });
// }
// }
if (price == '') {
setState(() {
price_flag = 1;
price_msg = 'Field Required';
});
} else if (price < 0) {
setState(() {
price_flag = 1;
price_msg = 'Invalid Price';
});
}
if (product_desc == '') {
setState(() {
description_flag = 1;
desc_msg = 'Field Required';
});
} else if (isNumeric(product_desc)) {
setState(() {
description_flag = 1;
desc_msg = 'Invalid Description';
});
}
if (_unBooked.isEmpty) {
setState(() {
date_flag = 1;
date_msg = 'Date Required';
});
}
if (email == '') {
setState(() {
email_flag = 1;
email_msg = 'Field Required';
});
} else if (!(RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(email))) {
setState(() {
email_flag = 1;
email_msg = 'Invalid Email';
});
} else {
email_flag = 0;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: <Widget>[
SizedBox(
height: 50,
),
Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
//padding: EdgeInsets.symmetric(horizontal:MediaQuery.of(context).size.width*0.02),
child: Column(
children: [
GestureDetector(
onTap: getImage,
child: Container(
clipBehavior: Clip.antiAlias,
child: _image == null
? Container(
alignment: Alignment.center,
child: Text(
'No image selected.',
style: TextStyle(
fontFamily: "Poppins",
),
textAlign: TextAlign.center,
),
)
: FittedBox(
child: Image.file(_image),
fit: BoxFit.fill,
),
margin: EdgeInsets.symmetric(
horizontal:
MediaQuery.of(context).size.width * 0.11),
decoration: BoxDecoration(
border: Border.all(), shape: BoxShape.circle),
height: MediaQuery.of(context).size.height * 0.15,
width: MediaQuery.of(context).size.width * 0.32,
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.02),
select_img_flag == 0
? SizedBox(height: 0)
: Container(
child: Text('*' + img_msg,
style: TextStyle(color: Colors.red)),
),
],
),
),
Container(
height: MediaQuery.of(context).size.height * 0.25,
width: MediaQuery.of(context).size.width * 0.30,
child: Column(
children: <Widget>[
TextField(
minLines: 1,
maxLines: 3,
maxLength: 70,
textAlign: TextAlign.center,
controller: title_controller,
decoration: InputDecoration(hintText: 'Set Title'),
),
title_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + title_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.02,
),
TextField(
textAlign: TextAlign.center,
controller: price_controller,
keyboardType: TextInputType.number,
decoration: InputDecoration(hintText: 'Set Price'),
),
price_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + price_msg,
style: TextStyle(color: Colors.red))),
],
),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.03,
),
Container(
alignment: Alignment.center,
//height: MediaQuery.of(context).size.height * 0.20,
width: MediaQuery.of(context).size.width * 0.75,
padding:
EdgeInsets.all(MediaQuery.of(context).size.width * 0.035),
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.circular(60)),
child: TextField(
textAlignVertical: TextAlignVertical.center,
controller: product_description_controller,
textAlign: TextAlign.center,
keyboardType: TextInputType.multiline,
minLines: 1,
maxLines: 5,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Add Product Description',
)),
),
description_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + desc_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.04,
),
Container(
height: MediaQuery.of(context).size.height * 0.03,
width: MediaQuery.of(context).size.width * 0.75,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Select Slot Duration(in hrs)'),
SizedBox(width: MediaQuery.of(context).size.width * 0.04),
DropdownButton<String>(
underline: Container(),
value: dropdownValue,
icon: Icon(
Icons.arrow_drop_down,
),
// style: TextStyle(color: Colors.deepPurple),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
// ignore: unnecessary_statements
initialize(
(double.parse(dropdownValue) * 60).toInt());
print(dropdownValue);
});
},
items: <String>['0.5', '1', '2']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: TextStyle(
fontSize: 20,
),
),
);
}).toList(),
)
],
)),
SizedBox(
height: MediaQuery.of(context).size.height * 0.04,
),
Container(
child: SfCalendar(
view: CalendarView.week,
specialRegions: _specialTimeRegions,
minDate: DateTime.now(),
maxDate: DateTime.now().add(Duration(days: 6)),
// onViewChanged: viewChanged,
onTap: calendarTapped,
//onLongPress: longPressed,
timeSlotViewSettings: TimeSlotViewSettings(
timeInterval: Duration(
minutes: (double.parse(dropdownValue) * 60).toInt()),
timeFormat: 'hh:mm a'),
),
),
date_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + date_msg,
style: TextStyle(color: Colors.red))),
SizedBox(height: MediaQuery.of(context).size.height * 0.03),
SizedBox(height: MediaQuery.of(context).size.height * 0.03),
Container(
padding: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width * 0.05),
//decoration: BoxDecoration(border: Border.all()),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.email_outlined),
SizedBox(
width: MediaQuery.of(context).size.width * 0.02,
),
Container(
height: MediaQuery.of(context).size.height * 0.03,
// decoration: BoxDecoration(border: Border.all()),
width: MediaQuery.of(context).size.width * 0.65,
child: FittedBox(
fit: BoxFit.contain,
child: Text(
email,
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Poppins',
//fontSize: 1,
fontWeight: FontWeight.bold),
),
),
)
],
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.person),
SizedBox(
width: MediaQuery.of(context).size.width * 0.02,
),
Container(
height: MediaQuery.of(context).size.height * 0.03,
// decoration: BoxDecoration(border: Border.all()),
width: MediaQuery.of(context).size.width * 0.65,
child: FittedBox(
fit: BoxFit.contain,
child: Text(
usern,
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Poppins',
//fontSize: 1,
fontWeight: FontWeight.bold),
),
),
)
],
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
// Row(
// mainAxisAlignment: MainAxisAlignment.center,
// children: <Widget>[
// Icon(Icons.person_pin_outlined),
// SizedBox(
// width: MediaQuery.of(context).size.width * 0.02,
// ),
// Container(
// alignment: Alignment.center,
// height: MediaQuery.of(context).size.height * 0.04,
// //decoration: BoxDecoration(border: Border.all()),
// width: MediaQuery.of(context).size.width * 0.65,
// child: TextField(
// textAlign: TextAlign.center,
// decoration: InputDecoration(
// border: InputBorder.none,
// hintText: "Add Your Full Name",
// ),
// ),
// )
// ],
// ),
],
),
),
// SizedBox(
// height: MediaQuery.of(context).size.height * 0.05,
// ),
// provider_name_flag == 0
// ? SizedBox(height: 0)
// : Container(
// padding: EdgeInsets.all(
// MediaQuery.of(context).size.width * 0.01),
// child: Text('*' + provider_name_msg,
// style: TextStyle(color: Colors.red))),
// SizedBox(
// height: MediaQuery.of(context).size.height * 0.05,
// ),
ButtonTheme(
height: MediaQuery.of(context).size.height * 0.05,
minWidth: MediaQuery.of(context).size.width * 0.25,
buttonColor: Color.fromRGBO(6, 13, 217, 1),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
child: RaisedButton(
onPressed: () {
setState(() {
title = title_controller.text;
price = double.parse(price_controller.text);
product_desc = product_description_controller.text;
provider_name = provider_name_controller.text;
slot_duration = dropdownValue;
title_flag = 0;
price_flag = 0;
email_flag = 0;
description_flag = 0;
select_img_flag = 0;
date_flag = 0;
});
getServiceId();
validator();
if (email_flag == 0 &&
date_flag == 0 &&
select_img_flag == 0 &&
title_flag == 0 &&
price_flag == 0 &&
description_flag == 0) {
uploadFile();
if (img_flag == 0 && data_flag == 0) {
Timer(Duration(seconds: 4), () {
Fluttertoast.showToast(
msg: "Service added Successfully!",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 16.0);
});
Timer(Duration(seconds: 6), () {
//Variables().provider_auth.signOut();
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => HomeScreen()));
});
} else {
Timer(Duration(seconds: 4), () {
Fluttertoast.showToast(
msg: "Error adding Service! Try Again.",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
});
}
} else {
Fluttertoast.showToast(
msg: "Fill all the required Fields!!",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
}
},
child: Text(
"Add Service",
style: TextStyle(
color: Colors.white,
fontFamily: "Poppins",
fontWeight: FontWeight.bold,
fontSize: MediaQuery.of(context).size.width * 0.045),
),
),
),
SizedBox(height: MediaQuery.of(context).size.height * 0.05),
//_image == null ? Text('null') : Text('${_image.absolute}')
],
),
),
);
}
}
| 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/homescreen.dart | import 'dart:async';
import 'package:SetItUp/addservice.dart';
import 'package:SetItUp/globalVariables.dart';
import 'providerSignUp.dart';
import 'package:SetItUp/signInOptions.dart';
import 'productDetails.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import './events_model.dart';
import './data.dart';
import 'cart.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:SetItUp/userSignIn.dart';
import 'package:uuid/uuid.dart';
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
var uuid = Uuid();
FirebaseFirestore firestore = FirebaseFirestore.instance;
String email = null,
password = null,
user_type = null,
username = null,
user_id = null;
bool funcstatus = false;
Future<List> getUser() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getStringList('User') ?? null;
}
// getUser() async {
// final prefs = await SharedPreferences.getInstance();
// return prefs.getStringList('User') ?? null;
// }
@override
void initState() {
super.initState();
if (Variables().session_ID == null) {
String session_id = uuid.v1();
Variables().setSessionId(session_id);
}
if (Variables().provider != null) {
Variables().provider_auth.signOut();
Variables().setProvider(null);
}
// if (Variables().firebaseuser == null) {
// getUser().then((value) => setUserData(value));
// } else {
// getUser().then((value) => setUserData(value));
// }
if (Variables().firebaseuser == null) {
getUserInfo();
}
if (Variables().firebaseuser != null) {
if (Variables().firebaseuser.email == '[email protected]') {
funcstatus = true;
username = 'Administrator';
} else {
getUserInfo();
}
}
}
getUserInfo() async {
List User_Info = await getUser();
if (User_Info != null) {
if (User_Info[3] != 'admin') {
setState(() {
email = User_Info[1];
password = User_Info[2];
username = User_Info[3];
user_type = User_Info[4];
});
} else {
email = User_Info[0];
password = User_Info[1];
username = User_Info[2];
user_type = User_Info[3];
}
if (Variables().firebaseuser == null) {
await signinuser(email, password);
}
setState(() {
funcstatus = true;
});
} else {
setState(() {
funcstatus = true;
});
}
}
Future<void> signinuser(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
Variables().setFIrebaseUser(userCredential.user);
Variables().setUsertype(user_type);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided for that user.');
}
}
}
// void setUserData(List<String> data) {
// if (data != null) {
// setState(() {
// email = data[1];
// password = data[2];
// username = data[3];
// user_type = data[4];
// Fluttertoast.showToast(msg: username);
// });
// }
// //Fluttertoast.showToast(msg: email + password);
// if (email != null && password != null) {
// signinuser(email, password);
// }
// }
@override
Widget build(BuildContext context) {
if (funcstatus == false) {
return Center(
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<Color>(Color.fromRGBO(6, 13, 217, 1)),
),
);
} else {
return Scaffold(
backgroundColor: Color.fromRGBO(6, 13, 217, 1),
drawer: new AppDrawer(username),
appBar: AppBar(
centerTitle: true,
backgroundColor: Color(0xff060DD9),
title: Text("Set It Up"),
actions: Variables().user_type != "admin"
? <Widget>[
IconButton(
color: Colors.white,
onPressed: () {
// if (Variables().firebaseuser == null) {
// Fluttertoast.showToast(
// msg: "Dude Please sign in before proceeding to cart");
// Timer(Duration(seconds: 2), () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => userSignIn()));
// });
// } else
// Navigator.push(context,
// MaterialPageRoute(builder: (context) => Cart()));
Navigator.push(context,
MaterialPageRoute(builder: (context) => Cart()));
},
icon:
Icon(Icons.shopping_cart_rounded, color: Colors.white),
)
]
: null,
),
body: Column(
children: <Widget>[
Variables().user_type != "admin"
? Container(
alignment: Alignment.topRight,
padding: EdgeInsets.only(
right: MediaQuery.of(context).size.width * 0.030,
top: MediaQuery.of(context).size.width * 0.032,
bottom: MediaQuery.of(context).size.width * 0.032),
child: Icon(
Icons.filter_list,
color: Colors.white,
),
)
: SizedBox(),
Expanded(
child: Container(
width: double.infinity,
padding: EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(40),
topRight: Radius.circular(40))),
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('services')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Something went wrong'));
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: Text("Loading"));
}
if (snapshot.data.size == 0) {
return Center(
child: Text(
"Currently no service is available !",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold,
color: Colors.red),
));
}
// return new ListView(
// children:
// snapshot.data.docs.map((DocumentSnapshot document) {
// return ServiceTile(
// serviceImage: document.data()['Image'],
// serviceName:document.data()['Title'],
// providerName: document.data()['Description'],
// defaultSlot: document.data()['Duration'],
// price: document.data()['Price']);
// }).toList(),
// );
//Fluttertoast.showToast(msg: Variables().firebaseuser.email);
return ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (BuildContext context, int index) {
DocumentSnapshot documentSnapshot =
snapshot.data.docs[index];
String Image = documentSnapshot['Image'];
String Title = documentSnapshot['Title'];
String Name = documentSnapshot['Name'];
String Duration = documentSnapshot['Duration'];
int Price = documentSnapshot['Price'];
String Email = documentSnapshot['Email'];
String Desc = documentSnapshot['Description'];
String serviceid = documentSnapshot.id.toString();
List UnAvailableSlot =
documentSnapshot['UnAvailableSlot'];
List BookedSlot = documentSnapshot['BookedSlot'];
List UnBookedSlot =
documentSnapshot['UnBookedSlot'];
return GestureDetector(
child: ServiceTile(
serviceImage: Image,
serviceName: Title,
providerName: Name,
defaultSlot: Duration,
price: Price),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => productDetails(
serviceid,
Image,
Title,
Price,
Desc,
Duration,
Name,
Email,
UnBookedSlot,
BookedSlot,
UnAvailableSlot,
null))));
//else {
// return GestureDetector(
// child: ServiceTile(
// serviceImage: Image,
// serviceName: Title,
// providerName: Name,
// defaultSlot: Duration,
// price: Price),
// onTap: () => Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => productDetails(
// serviceid,
// Image,
// Title,
// Price,
// Desc,
// Duration,
// Name,
// Email,
// UnBookedSlot,
// BookedSlot,
// UnAvailableSlot,
// null))));
// }
});
}),
),
)
],
),
);
}
}
}
class ServiceTile extends StatelessWidget {
final String serviceImage;
final String serviceName;
final String providerName;
final String defaultSlot;
//final String productDesc;
final int price;
ServiceTile({
@required this.serviceImage,
@required this.serviceName,
@required this.providerName,
@required this.defaultSlot,
@required this.price,
//@required this.productDesc
});
@override
Widget build(BuildContext context) {
return Column(
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
border: Border.all(width: 1),
),
//margin: EdgeInsets.symmetric(vertical: 16),
padding: EdgeInsets.all(MediaQuery.of(context).size.width * 0.030),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(60),
child: Image.network(
serviceImage,
height: MediaQuery.of(context).size.height *
MediaQuery.of(context).size.width *
0.00019,
width: MediaQuery.of(context).size.height *
MediaQuery.of(context).size.width *
0.00019,
fit: BoxFit.cover,
),
),
SizedBox(
width: MediaQuery.of(context).size.width * 0.06,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
serviceName,
softWrap: true,
style: TextStyle(
color: Color.fromRGBO(6, 13, 217, 1),
fontSize: 17,
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.005,
),
Text(
providerName,
softWrap: true,
style: TextStyle(
color: Color.fromRGBO(6, 168, 217, 1),
fontSize: 15,
fontFamily: "Poppins"),
)
],
),
),
SizedBox(
width: MediaQuery.of(context).size.width * 0.04,
),
Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(6),
decoration: BoxDecoration(
color: Color.fromRGBO(6, 13, 217, 1),
borderRadius: BorderRadius.circular(40)),
width: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00020,
height: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00012,
child: FittedBox(
child: Text(
" ₹ $price",
style: TextStyle(color: Colors.white),
),
fit: BoxFit.fitWidth,
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.005,
),
Text(
"Slot - " + defaultSlot + " hr",
style: TextStyle(fontFamily: 'Poppins'),
)
],
),
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.03,
),
],
);
}
}
class AppDrawer extends StatefulWidget {
String username;
AppDrawer(String username) {
this.username = username;
}
@override
_AppDrawerState createState() => new _AppDrawerState();
}
class _AppDrawerState extends State<AppDrawer> {
@override
Widget build(BuildContext context) {
return new Drawer(
child: new ListView(
children: Variables().firebaseuser != null
? Variables().user_type != "admin"
? Variables().user_type != "provider"
? <Widget>[
Container(
child: Text(
widget.username,
style: TextStyle(
fontFamily: "Poppins",
fontWeight: FontWeight.bold),
),
alignment: Alignment.center,
margin: EdgeInsets.symmetric(
vertical:
MediaQuery.of(context).size.height * 0.025),
),
new DrawerHeader(
decoration: BoxDecoration(
//color: Color.fromRGBO(6, 13, 217, 1),
image: DecorationImage(
image: AssetImage(
'assets/images/setitup_final.png'))),
//child: new Text(Variables().firebaseuser.email),
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.account_circle,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"View Profile",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.calendar_today,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Scheduled Meets",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.history,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Meet History",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
Divider(),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.bug_report_sharp,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Report Bugs",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.rate_review,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Rate Us",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.share,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Share",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.info_outline,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"About",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.logout,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Log Out",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
onTap: () async {
await FirebaseAuth.instance.signOut();
Variables().setFIrebaseUser(null);
final prefs =
await SharedPreferences.getInstance();
prefs.remove('User');
Navigator.pop(context);
Fluttertoast.showToast(msg: "Logged Out");
},
),
]
: <Widget>[
Container(
child: Text(
widget.username,
style: TextStyle(
fontFamily: "Poppins",
fontWeight: FontWeight.bold),
),
alignment: Alignment.center,
margin: EdgeInsets.symmetric(
vertical:
MediaQuery.of(context).size.height * 0.025),
),
new DrawerHeader(
decoration: BoxDecoration(
//color: Color.fromRGBO(6, 13, 217, 1),
image: DecorationImage(
image: AssetImage(
'assets/images/setitup_final.png'))),
//child: new Text(Variables().firebaseuser.email),
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.add_to_photos_rounded,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Add Service",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.view_agenda_outlined,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"View Service",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.calendar_today,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Scheduled Meets",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.history,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Meet History",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
Divider(),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.bug_report_sharp,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Report Bugs",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.rate_review,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Rate Us",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.share,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Share",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.info_outline,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"About",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.logout,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Log Out",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
onTap: () async {
await FirebaseAuth.instance.signOut();
Variables().setFIrebaseUser(null);
final prefs =
await SharedPreferences.getInstance();
prefs.remove('User');
Navigator.pop(context);
Fluttertoast.showToast(msg: "Logged Out");
},
),
]
: <Widget>[
Container(
child: Text(
widget.username,
style: TextStyle(
fontFamily: "Poppins",
fontWeight: FontWeight.bold),
),
alignment: Alignment.center,
margin: EdgeInsets.symmetric(
vertical:
MediaQuery.of(context).size.height * 0.025),
),
new DrawerHeader(
decoration: BoxDecoration(
//color: Color.fromRGBO(6, 13, 217, 1),
image: DecorationImage(
image: AssetImage(
'assets/images/setitup_final.png'))),
//child: new Text(Variables().firebaseuser.email),
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.person_add_alt_1,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Add Service Provider",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProviderSignUp()));
},
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.highlight_remove_sharp,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Remove Service",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.person_remove_sharp,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Remove Service Provider",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
Divider(),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.bug_report_sharp,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Report Bugs",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.rate_review,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Rate Us",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.share,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Share",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.info_outline,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"About",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.logout,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.00008,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Log Out",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
onTap: () async {
await FirebaseAuth.instance.signOut();
Variables().setFIrebaseUser(null);
final prefs = await SharedPreferences.getInstance();
prefs.remove('User');
Variables().session_ID = null;
Navigator.pop(context);
Timer(Duration(seconds: 1), () {
print('Hello');
});
Variables().user_type = 'user';
Fluttertoast.showToast(msg: "Logged Out");
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
HomeScreen()));
},
),
]
: <Widget>[
Container(
child: Text(
"Guest User",
style: TextStyle(
fontFamily: "Poppins", fontWeight: FontWeight.bold),
),
alignment: Alignment.center,
margin: EdgeInsets.symmetric(
vertical: MediaQuery.of(context).size.height * 0.025),
),
new DrawerHeader(
//child: new Text("SetItUp"),
decoration: BoxDecoration(
//color: Color.fromRGBO(6, 13, 217, 1),
image: DecorationImage(
image: AssetImage('assets/images/setitup_final.png'),
)),
),
ListTile(
title: Row(
children: <Widget>[
Padding(padding: EdgeInsets.all(5)),
Icon(
Icons.account_circle,
size: MediaQuery.of(context).size.width *
MediaQuery.of(context).size.height *
0.0001,
),
Padding(padding: EdgeInsets.all(5)),
Text(
"Sign In",
style: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
)
],
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SignInOptions()));
},
),
]),
);
}
}
/*
class Tasks extends StatelessWidget {
//FirebaseFirestore firestore = FirebaseFirestore.instance;
//CollectionReference users = FirebaseFirestore.instance.collection('users');
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('users').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) return new Text('Loading...');
return new ListView(
children: snapshot.data.docs.map((DocumentSnapshot document) {
return new ListTile(
title: new Text(document['title']),
subtitle: new Text(document['type']),
);
}).toList(),
);
},
);
}
}*/
| 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/userSignUp.dart | import 'dart:async';
import './userEmailVerificaton.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:string_validator/string_validator.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'homescreen.dart';
import 'package:firebase_core/firebase_core.dart';
import 'globalVariables.dart';
import 'package:uuid/uuid.dart';
class SignUp extends StatefulWidget {
@override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
var uuid = Uuid();
User user;
int email_flag = 0, username_flag = 0, password_flag = 0;
String email_msg = '', username_msg = '', password_msg = '';
int register_flag = 0;
String email = '', username = '', password = '';
final email_controller = TextEditingController();
final username_controller = TextEditingController();
final password_controller = TextEditingController();
FirebaseAuth auth = FirebaseAuth.instance;
String user_id;
SetUser(userid, email, password, username, user_type) async {
final prefs = await SharedPreferences.getInstance();
await prefs
.setStringList('User', [userid, email, password, username, user_type]);
}
void Validator() {
if (email == '') {
setState(() {
email_flag = 1;
email_msg = 'Field Required';
});
} else if (!(RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(email))) {
setState(() {
email_flag = 1;
email_msg = 'Invalid Email';
});
} else {
email_flag = 0;
}
if (username == '') {
setState(() {
username_flag = 1;
username_msg = 'Field Required';
});
} else if (!(RegExp(r'^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$')
.hasMatch(username))) {
setState(() {
username_flag = 1;
username_msg = 'Invalid Username';
});
} else {
setState(() {
username_flag = 0;
//Fluttertoast.showToast(msg: username);
});
}
if (password == '') {
setState(() {
password_flag = 1;
password_msg = 'Field Required';
});
} else if (!(RegExp(
"^(?=.{8,32}\$)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#\$%^&*(),.?:{}|<>]).*")
.hasMatch(password))) {
setState(() {
password_flag = 1;
password_msg = 'Password is too weak!';
});
} else {
password_flag = 0;
}
}
createUser() async {
try {
UserCredential userCredential = await auth.createUserWithEmailAndPassword(
email: email, password: password);
user_id = uuid.v4();
SetUser(user_id, email, password, username, "user");
//user = userCredential.user;
Variables().setFIrebaseUser(userCredential.user);
Variables().setUsertype("user");
Variables().setUserId(user_id);
Fluttertoast.showToast(
msg: "Sign Up Succesful!",
textColor: Colors.white,
backgroundColor: Colors.green);
await Variables().firebaseuser.sendEmailVerification();
await Fluttertoast.showToast(
msg: "Verification link has been sent to your email");
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
Fluttertoast.showToast(msg: 'The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
Fluttertoast.showToast(
msg: 'The account already exists for that email.');
}
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
//crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
Container(
height: MediaQuery.of(context).size.height * 0.25,
width: MediaQuery.of(context).size.width,
child: Image.asset(
"assets/images/setitup_final.png",
fit: BoxFit.contain,
)),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
Container(
alignment: Alignment.center,
child: Text(
"Create Account",
style: TextStyle(
fontFamily: "Poppins",
fontSize: 20,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(6, 13, 217, 1)),
),
),
SizedBox(height: MediaQuery.of(context).size.height * 0.03),
Container(
margin: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width * 0.10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Email",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1)),
),
TextField(
controller: email_controller,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50))),
),
email_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + email_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.035,
),
Text(
"Username",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1)),
),
TextField(
controller: username_controller,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50))),
),
username_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + username_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.035,
),
Text(
"Password",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1)),
),
TextField(
controller: password_controller,
obscureText: true,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50))),
),
password_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + password_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
)
],
),
),
ButtonTheme(
height: MediaQuery.of(context).size.height * 0.05,
minWidth: MediaQuery.of(context).size.width * 0.25,
buttonColor: Color.fromRGBO(6, 13, 217, 1),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
child: RaisedButton(
onPressed: () async {
setState(() {
email = email_controller.text;
username = username_controller.text;
password = password_controller.text;
});
Validator();
if (email_flag == 0 &&
username_flag == 0 &&
password_flag == 0) {
await createUser();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
UserEmailVerification(user_id, email, username, password)));
//sendEmail();
// if (Variables().firebaseuser!=null) {
// //print("inside if");
// Timer(Duration(seconds: 10), () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) =>
// emailVerificationProgress()));
// });
// }
}
},
child: Text(
"Sign Up",
style: TextStyle(
color: Colors.white,
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.045,
fontWeight: FontWeight.bold,
),
),
),
),
Container(
margin: EdgeInsets.symmetric(
vertical: MediaQuery.of(context).size.height * 0.04),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Already a User?",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1)),
),
GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Text(" SignIn",
style: TextStyle(
fontFamily: "Poppins",
fontWeight: FontWeight.bold,
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1))),
)
],
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/providerSignIn.dart | import 'dart:async';
import 'package:SetItUp/addservice.dart';
import 'package:SetItUp/cart.dart';
import 'package:SetItUp/globalVariables.dart';
import 'package:SetItUp/homescreen.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:string_validator/string_validator.dart';
import 'providerSignUp.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'homescreen.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class ProviderSignIn extends StatefulWidget {
@override
_SignInState createState() => _SignInState();
}
class _SignInState extends State<ProviderSignIn> {
int email_flag = 0, password_flag = 0, provider_found = 0;
String email_msg = '', password_msg = '';
String email = '', password = '', username = '', provider_Email, userid = '';
final email_controller = TextEditingController();
final password_controller = TextEditingController();
SetUser(userid, email, password, username, user_type) async {
final prefs = await SharedPreferences.getInstance();
await prefs
.setStringList('User', [userid, email, password, username, user_type]);
}
List<String> ret_userids = [];
List<String> ret_emails = [];
List<String> ret_usernames = [];
void signinUser(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
SetUser(userid, email, password, username, "provider");
Variables().setFIrebaseUser(userCredential.user);
Variables().setUsertype("provider");
Fluttertoast.showToast(
msg: "Logged In",
textColor: Colors.white,
backgroundColor: Colors.green);
Variables().cartstatus != 1
? Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => HomeScreen(),
))
: Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Cart(),
));
// Timer(Duration(seconds: 2), () {
// Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => HomeScreen(),));
// });
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
Fluttertoast.showToast(
msg: 'No user found for that email.',
textColor: Colors.white,
backgroundColor: Colors.red);
} else if (e.code == 'wrong-password') {
Fluttertoast.showToast(
msg: 'Wrong password provided for that user.',
textColor: Colors.white,
backgroundColor: Colors.red);
}
}
}
void Validator() {
if (email == '') {
setState(() {
email_flag = 1;
email_msg = 'Field Required';
});
} else if (!(RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(email))) {
setState(() {
email_flag = 1;
email_msg = 'Invalid Email';
});
} else {
email_flag = 0;
}
if (password == '') {
setState(() {
password_flag = 1;
password_msg = 'Field Required';
});
} else if (!(RegExp(
"^(?=.{8,32}\$)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#\$%^&*(),.?:{}|<>]).*")
.hasMatch(password))) {
setState(() {
password_flag = 1;
password_msg = 'Invalid Password';
});
} else {
password_flag = 0;
}
}
// void checkData(DocumentSnapshot value){
// //Fluttertoast.showToast(msg: value);
// if(value.data()==null){
// //Fluttertoast.showToast(msg: value+'2');
// setState(() {
// email_flag=1;
// email_msg='No Provider found for this emai!';
// // Fluttertoast.showToast(msg: email_flag.toString() + "inside ");
// //print('test');
// });
// }
// else
// {
// setState(() {
// username = value.data()['Username'].toString();
// });
// }
// }
// void RetrieveUser()
// {
// String path = 'service_provider/'+email;
// FirebaseFirestore.instance.doc(path).get().then((value) => {
// //String uname = value.data()['Usename']
// checkData(value),
// //Fluttertoast.showToast(msg: value.data().toString()+'1')
// });
// //return 1;
// }
RetrieveProvider() async {
// List<String> ret_userids = [];
// List<String> ret_emails = [];
// List<String> ret_usernames = [];
// FirebaseFirestore.instance
// .collection('users')
// .get()
// .then((querySnapshot) => {
// querySnapshot.docs.forEach((document) {
// String userid = document.id.toString();
// String ret_email = document.data()['Email'].toString();
// String ret_usern = document.data()['Username'].toString();
// ret_emails.add(ret_email);
// ret_usernames.add(ret_usern);
// ret_userids.add(userid);
// print(ret_emails);
// print(ret_usernames);
// print(ret_userids);
// }),
// checkUser(ret_emails, ret_usernames, ret_userids)
// })
// .catchError(
// (error) => print('Error occured while retrieving user $error'));
try {
ret_userids = [];
ret_emails = [];
ret_usernames = [];
QuerySnapshot data =
await FirebaseFirestore.instance.collection('service_provider').get();
data.docs.forEach((document) {
String userid = document.id.toString();
String ret_email = document.data()['Email'].toString();
String ret_usern = document.data()['Username'].toString();
ret_emails.add(ret_email);
ret_usernames.add(ret_usern);
ret_userids.add(userid);
});
await checkProvider();
} catch (error) {
print("Error occured while retrieving provider DATA" + error.toString());
}
}
// checkUserInfo() async {
// checkUser(ret_emails, ret_usernames, ret_userids);
// }
checkProvider() async {
for (int i = 0; i < ret_emails.length; i++) {
print("HELLO");
if (email == ret_emails[i]) {
setState(() {
provider_found = 1;
username = ret_usernames[i];
userid = ret_userids[i];
});
break;
}
}
if (provider_found == 0) {
setState(() {
email_flag = 1;
email_msg = 'No Provider found for this email';
// print('test');
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
//crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
height: MediaQuery.of(context).size.height * 0.11,
),
Container(
height: MediaQuery.of(context).size.height * 0.25,
width: MediaQuery.of(context).size.width,
child: Image.asset(
"assets/images/setitup_final.png",
fit: BoxFit.contain,
)),
SizedBox(
height: MediaQuery.of(context).size.height * 0.03,
),
Container(
alignment: Alignment.center,
child: Text(
"Welcome Back!",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.055,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(6, 13, 217, 1)),
),
),
SizedBox(height: MediaQuery.of(context).size.height * 0.06),
Container(
margin: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width * 0.10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Username",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1)),
),
TextField(
controller: email_controller,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50)),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50))),
),
email_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + email_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.035,
),
Text(
"Password",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1)),
),
TextField(
controller: password_controller,
obscureText: true,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50)),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50))),
),
password_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + password_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
],
),
),
ButtonTheme(
height: MediaQuery.of(context).size.height * 0.05,
minWidth: MediaQuery.of(context).size.width * 0.25,
buttonColor: Color.fromRGBO(6, 13, 217, 1),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
child: RaisedButton(
onPressed: () async {
setState(() {
email = email_controller.text;
password = password_controller.text;
});
Validator();
await RetrieveProvider();
//Fluttertoast.showToast(msg: email_flag.toString());
if (email_flag == 0 && password_flag == 0) {
signinUser(email, password);
}
},
child: Text(
"Sign In",
style: TextStyle(
color: Colors.white,
fontFamily: "Poppins",
fontWeight: FontWeight.bold,
fontSize: MediaQuery.of(context).size.width * 0.045),
),
),
),
// Container(
// margin: EdgeInsets.symmetric(
// vertical: MediaQuery.of(context).size.height * 0.04),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.center,
// children: <Widget>[
// Text(
// "Not a User?",
// style: TextStyle(
// fontFamily: "Poppins",
// fontSize: MediaQuery.of(context).size.width * 0.035,
// color: Color.fromRGBO(6, 13, 217, 1)),
// ),
// GestureDetector(
// onTap: () {
// Navigator.push(context, MaterialPageRoute(builder: (context) => ProviderSignUp(),));
// },
// child: Text(" SignUp",
// style: TextStyle(
// fontFamily: "Poppins",
// fontWeight: FontWeight.bold,
// fontSize: MediaQuery.of(context).size.width * 0.035,
// color: Color.fromRGBO(6, 13, 217, 1))),
// )
// ],
// ),
// ),
],
),
));
}
}
| 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/adminSignIn.dart | import 'dart:async';
import 'package:SetItUp/globalVariables.dart';
import 'package:SetItUp/homescreen.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:string_validator/string_validator.dart';
import 'userSignUp.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'homescreen.dart';
FirebaseAuth admiauth = FirebaseAuth.instance;
class adminSignIn extends StatefulWidget {
@override
_SignInState createState() => _SignInState();
}
class _SignInState extends State<adminSignIn> {
int email_flag = 0, password_flag = 0;
String email_msg = '', password_msg = '';
String email = '', password = '', username = '';
final email_controller = TextEditingController();
final password_controller = TextEditingController();
checkAdmin() async {
if (email != "[email protected]") {
setState(() {
email_flag = 1;
email_msg = 'Invalid Email';
});
}
}
SetUser(email, password, username, user_type) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setStringList('User', [email, password, username, user_type]);
}
void signinUser(String email, String password) async {
try {
UserCredential userCredential = await admiauth.signInWithEmailAndPassword(
email: email, password: password);
SetUser(email, password, "Administrator", "admin");
Variables().setFIrebaseUser(userCredential.user);
Variables().setAdminAuth(admiauth);
Variables().setUsertype("admin");
Fluttertoast.showToast(
msg: "Logged In",
textColor: Colors.white,
backgroundColor: Colors.green);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => HomeScreen(),
));
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
Fluttertoast.showToast(
msg: 'No user found for that email.',
textColor: Colors.white,
backgroundColor: Colors.red);
} else if (e.code == 'wrong-password') {
Fluttertoast.showToast(
msg: 'Wrong password provided for that user.',
textColor: Colors.white,
backgroundColor: Colors.red);
}
}
}
void Validator() {
if (email == '') {
setState(() {
email_flag = 1;
email_msg = 'Field Required';
});
} else if (!(RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(email))) {
setState(() {
email_flag = 1;
email_msg = 'Invalid Email';
});
} else {
email_flag = 0;
}
if (password == '') {
setState(() {
password_flag = 1;
password_msg = 'Field Required';
});
} else if (!(RegExp(
"^(?=.{8,32}\$)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#\$%^&*(),.?:{}|<>]).*")
.hasMatch(password))) {
setState(() {
password_flag = 1;
password_msg = 'Invalid Password';
});
} else {
password_flag = 0;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
//crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
height: MediaQuery.of(context).size.height * 0.11,
),
Container(
height: MediaQuery.of(context).size.height * 0.25,
width: MediaQuery.of(context).size.width,
child: Image.asset(
"assets/images/setitup_final.png",
fit: BoxFit.contain,
)),
SizedBox(
height: MediaQuery.of(context).size.height * 0.03,
),
Container(
alignment: Alignment.center,
child: Text(
"Welcome Back!",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.055,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(6, 13, 217, 1)),
),
),
SizedBox(height: MediaQuery.of(context).size.height * 0.06),
Container(
margin: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width * 0.10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Username",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1)),
),
TextField(
controller: email_controller,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50)),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50))),
),
email_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + email_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.035,
),
Text(
"Password",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1)),
),
TextField(
controller: password_controller,
obscureText: true,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50)),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50))),
),
password_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + password_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
],
),
),
ButtonTheme(
height: MediaQuery.of(context).size.height * 0.05,
minWidth: MediaQuery.of(context).size.width * 0.25,
buttonColor: Color.fromRGBO(6, 13, 217, 1),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
child: RaisedButton(
onPressed: () async {
setState(() {
email = email_controller.text;
password = password_controller.text;
});
Validator();
await checkAdmin();
if (email_flag == 0 && password_flag == 0) {
signinUser(email, password);
}
},
child: Text(
"Sign In",
style: TextStyle(
color: Colors.white,
fontFamily: "Poppins",
fontWeight: FontWeight.bold,
fontSize: MediaQuery.of(context).size.width * 0.045),
),
),
),
// Container(
// margin: EdgeInsets.symmetric(
// vertical: MediaQuery.of(context).size.height * 0.04),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.center,
// children: <Widget>[
// Text(
// "Not a User?",
// style: TextStyle(
// fontFamily: "Poppins",
// fontSize: MediaQuery.of(context).size.width * 0.035,
// color: Color.fromRGBO(6, 13, 217, 1)),
// ),
// GestureDetector(
// onTap: () {
// Navigator.push(context, MaterialPageRoute(builder: (context) => SignUp(),));
// },
// child: Text(" SignUp",
// style: TextStyle(
// fontFamily: "Poppins",
// fontWeight: FontWeight.bold,
// fontSize: MediaQuery.of(context).size.width * 0.035,
// color: Color.fromRGBO(6, 13, 217, 1))),
// )
// ],
// ),
// ),
],
),
));
}
}
| 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/main.dart | import 'package:SetItUp/homescreen.dart';
import 'package:flutter/material.dart';
import './addservice.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async
{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
//final Future<FirebaseApp> _initialization = Firebase.initializeApp();
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
//body: SignIn(),
body: HomeScreen(),
);
}
} | 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/lib/userSignIn.dart | import 'dart:async';
import 'package:SetItUp/cart.dart';
import 'package:SetItUp/globalVariables.dart';
import 'package:SetItUp/homescreen.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:string_validator/string_validator.dart';
import 'userSignUp.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'homescreen.dart';
class userSignIn extends StatefulWidget {
@override
_SignInState createState() => _SignInState();
}
class _SignInState extends State<userSignIn> {
int email_flag = 0, password_flag = 0, user_found = 0;
String email_msg = '', password_msg = '';
String email = '', password = '', username = '', userid = '';
final email_controller = TextEditingController();
final password_controller = TextEditingController();
List<String> ret_userids = [];
List<String> ret_emails = [];
List<String> ret_usernames = [];
SetUser(userid, email, password, username, user_type) async {
final prefs = await SharedPreferences.getInstance();
await prefs
.setStringList('User', [userid, email, password, username, user_type]);
}
void signinUser(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
SetUser(userid, email, password, username, "user");
Variables().setFIrebaseUser(userCredential.user);
Variables().setUsertype("user");
Variables().setUserId(userid);
Fluttertoast.showToast(
msg: "Logged In",
textColor: Colors.white,
backgroundColor: Colors.green);
Variables().cartstatus != 1
? Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => HomeScreen(),
))
: Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Cart(),
));
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
Fluttertoast.showToast(
msg: 'No user found for that email.',
textColor: Colors.white,
backgroundColor: Colors.red);
} else if (e.code == 'wrong-password') {
Fluttertoast.showToast(
msg: 'Wrong password provided for that user.',
textColor: Colors.white,
backgroundColor: Colors.red);
}
}
}
// void checkData(DocumentSnapshot value) {
// //Fluttertoast.showToast(msg: value);
// if (value.data() == null) {
// //Fluttertoast.showToast(msg: value+'2');
// setState(() {
// email_flag = 1;
// email_msg = 'No User found for this email';
// // print('test');
// });
// } else {
// setState(() {
// username = value.data()['Username'].toString();
// });
// }
// }
// void RetrieveUser() {
// String path = 'users/' + email;
// FirebaseFirestore.instance.doc(path).get().then((value) => {
// //String uname = value.data()['Usename']
// checkData(value),
// //Fluttertoast.showToast(msg: value.data().toString()+'1')
// });
// }
RetrieveUser() async {
// List<String> ret_userids = [];
// List<String> ret_emails = [];
// List<String> ret_usernames = [];
// FirebaseFirestore.instance
// .collection('users')
// .get()
// .then((querySnapshot) => {
// querySnapshot.docs.forEach((document) {
// String userid = document.id.toString();
// String ret_email = document.data()['Email'].toString();
// String ret_usern = document.data()['Username'].toString();
// ret_emails.add(ret_email);
// ret_usernames.add(ret_usern);
// ret_userids.add(userid);
// print(ret_emails);
// print(ret_usernames);
// print(ret_userids);
// }),
// checkUser(ret_emails, ret_usernames, ret_userids)
// })
// .catchError(
// (error) => print('Error occured while retrieving user $error'));
try {
ret_userids = [];
ret_emails = [];
ret_usernames = [];
QuerySnapshot data =
await FirebaseFirestore.instance.collection('users').get();
data.docs.forEach((document) {
String userid = document.id.toString();
String ret_email = document.data()['Email'].toString();
String ret_usern = document.data()['Username'].toString();
ret_emails.add(ret_email);
ret_usernames.add(ret_usern);
ret_userids.add(userid);
});
await checkUser();
} catch (error) {
print("Error occured while retrieving user DATA" + error.toString());
}
}
// checkUserInfo() async {
// checkUser(ret_emails, ret_usernames, ret_userids);
// }
checkUser() async {
for (int i = 0; i < ret_emails.length; i++) {
print("HELLO");
if (email == ret_emails[i]) {
setState(() {
user_found = 1;
username = ret_usernames[i];
userid = ret_userids[i];
});
break;
}
}
if (user_found == 0) {
setState(() {
email_flag = 1;
email_msg = 'No User found for this email';
// print('test');
});
}
}
void Validator() {
if (email == '') {
setState(() {
email_flag = 1;
email_msg = 'Field Required';
});
} else if (!(RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(email))) {
setState(() {
email_flag = 1;
email_msg = 'Invalid Email';
});
} else {
email_flag = 0;
}
if (password == '') {
setState(() {
password_flag = 1;
password_msg = 'Field Required';
});
} else if (!(RegExp(
"^(?=.{8,32}\$)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#\$%^&*(),.?:{}|<>]).*")
.hasMatch(password))) {
setState(() {
password_flag = 1;
password_msg = 'Invalid Password';
});
} else {
password_flag = 0;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
//crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
height: MediaQuery.of(context).size.height * 0.11,
),
Container(
height: MediaQuery.of(context).size.height * 0.25,
width: MediaQuery.of(context).size.width,
child: Image.asset(
"assets/images/setitup_final.png",
fit: BoxFit.contain,
)),
SizedBox(
height: MediaQuery.of(context).size.height * 0.03,
),
Container(
alignment: Alignment.center,
child: Text(
"Welcome Back!",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.055,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(6, 13, 217, 1)),
),
),
SizedBox(height: MediaQuery.of(context).size.height * 0.06),
Container(
margin: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width * 0.10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Username",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1)),
),
TextField(
controller: email_controller,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50)),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50))),
),
email_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + email_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.035,
),
Text(
"Password",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1)),
),
TextField(
controller: password_controller,
obscureText: true,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50)),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Color.fromRGBO(6, 13, 217, 1)),
borderRadius: BorderRadius.circular(50))),
),
password_flag == 0
? SizedBox(height: 0)
: Container(
padding: EdgeInsets.all(
MediaQuery.of(context).size.width * 0.01),
child: Text('*' + password_msg,
style: TextStyle(color: Colors.red))),
SizedBox(
height: MediaQuery.of(context).size.height * 0.05,
),
],
),
),
ButtonTheme(
height: MediaQuery.of(context).size.height * 0.05,
minWidth: MediaQuery.of(context).size.width * 0.25,
buttonColor: Color.fromRGBO(6, 13, 217, 1),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
child: RaisedButton(
onPressed: () async {
setState(() {
email = email_controller.text;
password = password_controller.text;
});
Validator();
await RetrieveUser();
if (email_flag == 0 && password_flag == 0) {
signinUser(email, password);
}
},
child: Text(
"Sign In",
style: TextStyle(
color: Colors.white,
fontFamily: "Poppins",
fontWeight: FontWeight.bold,
fontSize: MediaQuery.of(context).size.width * 0.045),
),
),
),
Container(
margin: EdgeInsets.symmetric(
vertical: MediaQuery.of(context).size.height * 0.04),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Not a User?",
style: TextStyle(
fontFamily: "Poppins",
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1)),
),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SignUp(),
));
},
child: Text(" SignUp",
style: TextStyle(
fontFamily: "Poppins",
fontWeight: FontWeight.bold,
fontSize: MediaQuery.of(context).size.width * 0.035,
color: Color.fromRGBO(6, 13, 217, 1))),
)
],
),
),
],
),
));
}
}
| 0 |
mirrored_repositories/Set-It-Up | mirrored_repositories/Set-It-Up/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:SetItUp/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/simple-flutter-apps/useless_app | mirrored_repositories/simple-flutter-apps/useless_app/lib/main.dart | import 'package:flutter/material.dart';
import 'package:useless_app/api/api_handler.dart';
import 'package:useless_app/widgets/post_container.dart';
import 'models/post.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Useless App',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.orange,
),
home: const HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<Post>? posts;
bool isLoaded = false;
@override
void initState() {
super.initState();
//fetch data
fetchData();
}
fetchData() async {
posts = await ApiHandler().getPosts();
if (posts != null) {
setState(() {
isLoaded = true;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Dummy Data App",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
centerTitle: true,
),
body: Visibility(
visible: isLoaded,
replacement: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
CircularProgressIndicator(
color: Colors.orange,
),
//horizontal spacing
SizedBox(
height: 20,
),
Text(
"Loading Your Dummy Data",
style: TextStyle(
fontSize: 17,
),
),
],
),
),
child: ListView.builder(
itemCount: posts?.length,
itemBuilder: (context, index) {
return PostContainr(post: posts![index]);
},
),
),
);
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/useless_app/lib | mirrored_repositories/simple-flutter-apps/useless_app/lib/widgets/post_container.dart | import 'package:flutter/material.dart';
import '../models/post.dart';
class PostContainr extends StatelessWidget {
final Post post;
const PostContainr({required this.post, super.key});
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.only(right: 7, left: 3, top: 15, bottom: 15),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//first letter Avatar
CircleAvatar(
backgroundColor: post.color,
radius: 20,
child: Text(
post.title[0].toUpperCase(),
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
//vertical spacing
const SizedBox(
width: 10,
),
//post info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//title
Text(
post.title,
maxLines: 2,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
),
),
//post body
Text(
post.body ?? "",
maxLines: 3,
style: const TextStyle(
color: Color.fromARGB(255, 75, 72, 72),
fontSize: 17,
),
)
],
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/useless_app/lib | mirrored_repositories/simple-flutter-apps/useless_app/lib/models/post.dart | import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
List<Post> postFromJson(String str) =>
List<Post>.from(json.decode(str).map((x) => Post.fromJson(x)));
String postToJson(List<Post> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Post {
Post({
required this.userId,
required this.id,
required this.title,
this.body,
required this.color,
});
int userId;
int id;
String title;
String? body;
Color color;
factory Post.fromJson(Map<String, dynamic> json) {
List<Color> avatarColors = [
Colors.red,
const Color.fromARGB(255, 48, 117, 50),
Colors.brown,
Colors.black,
const Color.fromARGB(255, 133, 122, 27),
Colors.orange,
Colors.blue
];
return Post(
userId: json["userId"],
id: json["id"],
title: json["title"],
body: json["body"],
color: avatarColors[Random().nextInt(avatarColors.length)],
);
}
Map<String, dynamic> toJson() => {
"userId": userId,
"id": id,
"title": title,
"body": body,
"color": color,
};
}
| 0 |
mirrored_repositories/simple-flutter-apps/useless_app/lib | mirrored_repositories/simple-flutter-apps/useless_app/lib/api/api_handler.dart | import 'package:http/http.dart';
import '../models/post.dart';
class ApiHandler {
Future<List<Post>> getPosts() async {
Client client = Client();
Uri uri = Uri.parse("https://jsonplaceholder.typicode.com/posts");
//await response
Response response = await client.get(uri);
//if no response
if (response.statusCode != 200) {
throw Exception("API is not responding!");
}
// got response
return postFromJson(response.body);
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/todo_app | mirrored_repositories/simple-flutter-apps/todo_app/lib/tests.dart | import 'models/task.dart';
class TestData {
List<Map<String, dynamic>> data = [
{
"task": "task 1",
"isDone": false,
"doneDate": null,
},
{
"task": "task 2",
"isDone": false,
"doneDate": null,
},
{
"task": "task 3",
"isDone": true,
"doneDate": "20/10/2022",
},
{
"task": "task 4",
"isDone": false,
"doneDate": null,
},
{
"task": "task 5",
"isDone": true,
"doneDate": "15/10/2022",
},
{
"task": "task 6",
"isDone": true,
"doneDate": "15/10/2022",
},
{
"task": "task 7",
"isDone": true,
"doneDate": "15/10/2022",
},
{
"task": "task 8",
"isDone": false,
"doneDate": null,
},
{
"task": "task 9",
"isDone": true,
"doneDate": "1/10/2022",
},
{
"task": "task 10",
"isDone": true,
"doneDate": "28/9/2022",
},
];
List<Task> getDummyTasks() {
return List<Task>.from(data.map((taskMap) => Task.fromMap(taskMap)));
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/todo_app | mirrored_repositories/simple-flutter-apps/todo_app/lib/main.dart | import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:provider/provider.dart';
import 'package:todo_app/screens/list_screen.dart';
import '../providers/tasks_provider.dart';
void main() async {
await Hive.initFlutter();
await Hive.openBox("tasksBox");
runApp(
MultiProvider(
providers: [ChangeNotifierProvider(create: (_) => TasksProvider())],
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: "To-Do App",
theme: ThemeData(
primarySwatch: Colors.blueGrey,
),
home: const MainScreen(),
);
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/todo_app/lib | mirrored_repositories/simple-flutter-apps/todo_app/lib/widgets/tasks_list.dart | import 'package:flutter/material.dart';
import 'package:todo_app/widgets/task_row.dart';
import 'package:provider/provider.dart';
import '../providers/tasks_provider.dart';
import '../models/task.dart';
class TasksList extends StatelessWidget {
const TasksList({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
List<Task> tasks = context.watch<TasksProvider>().tasks;
return Expanded(
child: Container(
margin: const EdgeInsets.only(
top: 15,
),
decoration: BoxDecoration(
color: const Color.fromARGB(255, 52, 79, 161),
borderRadius: BorderRadius.circular(15),
),
child: ListView.builder(
itemCount: tasks.length,
itemBuilder: (context, index) {
return Column(
children: [
TaskRow(
taskId: index,
),
const Divider(
color: Colors.white,
),
],
);
},
),
),
);
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/todo_app/lib | mirrored_repositories/simple-flutter-apps/todo_app/lib/widgets/task_row.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/task.dart';
import '../providers/tasks_provider.dart';
class TaskRow extends StatelessWidget {
final int taskId;
const TaskRow({
required this.taskId,
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
Task task = context.watch<TasksProvider>().tasks[taskId];
return ListTile(
title: Text(
task.task,
style: TextStyle(
color: Colors.white,
fontSize: 20,
decoration: task.isDone ? TextDecoration.lineThrough : null,
),
),
leading: IconButton(
icon: const Icon(
Icons.delete,
color: Color.fromARGB(255, 221, 106, 39),
size: 25,
),
onPressed: () {
context.read<TasksProvider>().deleteTask(taskId);
},
splashRadius: 0.1,
),
trailing: Checkbox(
value: task.isDone,
onChanged: (_) {
context.read<TasksProvider>().toggleDoneState(taskId);
},
),
);
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/todo_app/lib | mirrored_repositories/simple-flutter-apps/todo_app/lib/widgets/top_bar.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/tasks_provider.dart';
class TopBar extends StatelessWidget {
const TopBar({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
int doneTasks = context.watch<TasksProvider>().doneTasksCount;
int allTasks = context.watch<TasksProvider>().tasksCount;
String today = context.read<TasksProvider>().todayDate;
return Container(
padding: const EdgeInsets.only(
top: 10,
bottom: 10,
right: 20,
left: 20,
),
margin: const EdgeInsets.only(
top: 10,
bottom: 10,
),
width: double.infinity,
decoration: BoxDecoration(
color: const Color.fromARGB(255, 52, 79, 161),
borderRadius: BorderRadius.circular(15),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
//date
Text(
today,
style: const TextStyle(
fontSize: 25,
color: Colors.white,
fontWeight: FontWeight.w500,
),
),
//tasks count
Row(
children: [
Text(
"$doneTasks/$allTasks",
style: const TextStyle(
fontSize: 25,
color: Colors.white,
fontWeight: FontWeight.w400),
),
const Icon(
Icons.task_alt_outlined,
size: 25,
color: Color.fromARGB(255, 221, 136, 39),
),
],
),
],
),
);
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/todo_app/lib | mirrored_repositories/simple-flutter-apps/todo_app/lib/widgets/date_history.dart | import 'package:flutter/material.dart';
import '../models/task.dart';
class DateHistory extends StatelessWidget {
final String date;
final List<Task> tasks;
const DateHistory({required this.date, required this.tasks, super.key});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(15),
color: const Color.fromARGB(255, 29, 52, 119),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//title
Text(
date,
style: const TextStyle(
fontSize: 28,
color: Colors.white,
fontWeight: FontWeight.bold,
decoration: TextDecoration.underline,
),
),
Column(
children: tasks
.map((e) => ListTile(
leading: const Icon(
Icons.done,
size: 25,
color: Colors.orange,
),
title: Text(
e.task,
style: const TextStyle(
color: Colors.white,
fontSize: 25,
),
),
))
.toList(),
),
const Divider(
thickness: 10,
),
],
),
);
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/todo_app/lib | mirrored_repositories/simple-flutter-apps/todo_app/lib/models/task.dart | // ignore_for_file: avoid_init_to_null
String encodeDate(DateTime date) {
return "${date.day}/${date.month}/${date.year}";
}
DateTime decodeDate(String date) {
List<String> dateInfo = date.split("/");
return DateTime(
int.parse(dateInfo[2]),
int.parse(dateInfo[1]),
int.parse(dateInfo[0]),
);
}
class Task {
final String _task;
bool _isDone = false;
dynamic _doneDate = null;
Task(this._task);
Task.fromMap(Map<String, dynamic> taskMap)
: _task = taskMap["task"],
_isDone = taskMap["isDone"],
_doneDate = taskMap["doneDate"] != null
? decodeDate(taskMap["doneDate"])
: null;
String get task => _task;
bool get isDone => _isDone;
dynamic get doneDate => _doneDate;
void toggleDoneState() {
if (_isDone) {
_isDone = false;
_doneDate = null;
} else {
_isDone = true;
_doneDate = DateTime.now();
}
}
Map<String, dynamic> toMap() => {
"task": _task,
"isDone": _isDone,
"doneDate": _doneDate != null ? encodeDate(_doneDate) : null,
};
}
| 0 |
mirrored_repositories/simple-flutter-apps/todo_app/lib | mirrored_repositories/simple-flutter-apps/todo_app/lib/screens/history_screen.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:todo_app/widgets/date_history.dart';
import '../models/task.dart';
import '../providers/tasks_provider.dart';
class HistoryScreen extends StatelessWidget {
const HistoryScreen({super.key});
String encodeDate(DateTime date) => "${date.day}-${date.month}-${date.year}";
Map<String, List<Task>> classifyHistory(List<Task> history) {
Map<String, List<Task>> results = {};
for (Task task in history) {
String doneDate = encodeDate(task.doneDate);
if (results.containsKey(doneDate)) {
results[doneDate]?.add(task);
} else {
results[doneDate] = <Task>[task];
}
}
return results;
}
@override
Widget build(BuildContext context) {
Map<String, List<Task>> history =
classifyHistory(context.watch<TasksProvider>().history);
return Scaffold(
backgroundColor: const Color.fromARGB(255, 25, 53, 135),
floatingActionButton: FloatingActionButton(
onPressed: () {
context.read<TasksProvider>().clearHistory();
},
backgroundColor: Colors.red,
child: const Icon(
Icons.delete,
size: 30,
color: Colors.white,
),
),
appBar: AppBar(
centerTitle: true,
backgroundColor: const Color.fromARGB(255, 211, 80, 4),
//title
title: const Text(
"History",
style: TextStyle(
fontSize: 40,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 29, 52, 119),
),
),
),
body: Visibility(
visible: history.keys.isNotEmpty,
replacement: const Center(
child: Text(
"No History To Show",
style: TextStyle(
fontSize: 23,
color: Colors.white54,
),
),
),
child: ListView(
children: history.entries.map((e) {
return DateHistory(date: e.key, tasks: e.value);
}).toList()),
),
);
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/todo_app/lib | mirrored_repositories/simple-flutter-apps/todo_app/lib/screens/list_screen.dart | import 'package:flutter/material.dart';
import 'package:todo_app/screens/add_screen.dart';
import 'package:todo_app/screens/history_screen.dart';
import '../widgets/tasks_list.dart';
import '../widgets/top_bar.dart';
class MainScreen extends StatelessWidget {
const MainScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromARGB(255, 25, 53, 135),
//floating add button
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
onPressed: () {
showModalBottomSheet(
isScrollControlled: true,
context: context,
builder: (context) => SingleChildScrollView(
child: Container(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
child: const AddScreen(),
),
),
);
},
backgroundColor: const Color.fromARGB(255, 211, 80, 4),
child: const Icon(
Icons.add,
size: 30,
color: Colors.white,
),
),
//app bar
appBar: AppBar(
centerTitle: true,
backgroundColor: const Color.fromARGB(255, 211, 80, 4),
//title
title: const Text(
"To Do",
style: TextStyle(
fontSize: 40,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 29, 52, 119),
),
),
actions: [
//history button
IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const HistoryScreen()));
},
icon: const Icon(
Icons.restore_outlined,
size: 40,
color: Color.fromARGB(255, 29, 52, 119),
),
),
//horizontal spacing
const SizedBox(
width: 5,
),
],
),
//body main container
body: Container(
padding: const EdgeInsets.only(
top: 20,
left: 20,
right: 20,
bottom: 45,
),
child: Column(
children: const [
//top bar
TopBar(),
//tasks list container
TasksList(),
],
),
),
);
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/todo_app/lib | mirrored_repositories/simple-flutter-apps/todo_app/lib/screens/add_screen.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/tasks_provider.dart';
class AddScreen extends StatelessWidget {
const AddScreen({super.key});
@override
Widget build(BuildContext context) {
TextEditingController taskController = TextEditingController();
return Container(
padding: const EdgeInsets.all(30),
color: const Color.fromARGB(255, 52, 79, 161),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
"New Task",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 35,
fontWeight: FontWeight.bold,
color: Colors.white,
decoration: TextDecoration.none,
),
),
TextField(
autofocus: true,
style: const TextStyle(
fontSize: 28,
color: Colors.white,
),
controller: taskController,
textAlign: TextAlign.center,
),
const SizedBox(height: 20),
TextButton(
onPressed: () {
String task = taskController.text;
//if input is empty
if (task == "") return;
//add the entered task
context.read<TasksProvider>().addNewTask(task: task);
//close the screen
Navigator.pop(context);
},
style: TextButton.styleFrom(
backgroundColor: Colors.orange,
),
child: const Text(
"Add",
style: TextStyle(
fontSize: 25,
color: Color.fromARGB(255, 29, 52, 119),
),
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/todo_app/lib | mirrored_repositories/simple-flutter-apps/todo_app/lib/providers/tasks_provider.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:intl/intl.dart';
import '../models/task.dart';
import '../tests.dart';
class TasksProvider with ChangeNotifier {
List<Task> _tasks = [];
List<Task> _history = [];
final Box _tasksBox = Hive.box("tasksBox");
TasksProvider() {
syncDataWithProvider();
}
//return active tasks
List<Task> get tasks => _tasks;
//return old done tasks
List<Task> get history => _history;
//return active tasks count
int get tasksCount => _tasks.length;
//return done active tasks count
int get doneTasksCount {
int count = 0;
for (var task in _tasks) {
if (task.isDone) count++;
}
return count;
}
//return today date in custom format
String get todayDate => DateFormat('EEEE, d MMM').format(DateTime.now());
//add new task to active tasks and update box
void addNewTask({required task}) {
_tasks.add(Task(task));
notifyListeners();
saveTasks();
}
//delete the task with given index from active tasks and update box
void deleteTask(int index) {
_tasks.removeAt(index);
notifyListeners();
saveTasks();
}
//check/unckeck the task with given index and update box
void toggleDoneState(int index) {
_tasks[index].toggleDoneState();
notifyListeners();
saveTasks();
}
//update data in box
void saveTasks() {
String encodedData =
json.encode((_tasks + _history).map((task) => task.toMap()).toList());
_tasksBox.put("tasks", encodedData);
}
//clear all old tasks from box
void clearHistory() {
_history = [];
notifyListeners();
saveTasks();
}
//load encodedData from box
List<Task> loadDataFromBox() {
String? encodedData = _tasksBox.get("tasks");
List<Task> tasks;
if (encodedData != null) {
tasks = List<Task>.from(
json.decode(encodedData).map((map) => Task.fromMap(map)));
} else {
tasks = [];
}
return tasks;
}
//load fake data for testing
List<Task> loadDataFromTest() {
TestData testData = TestData();
return testData.getDummyTasks();
}
//load data on initializing a TasksProvider object
void syncDataWithProvider() {
//load data
List<Task> tasks = loadDataFromBox();
//filter data
List<Task> todayTasks = [];
List<Task> oldTasks = [];
DateTime now = DateTime.now();
for (Task task in tasks) {
//if task is done in the past
if (task.isDone &&
task.doneDate.compareTo(DateTime(now.year, now.month, now.day)) < 0) {
oldTasks.add(task);
}
//if task is not done or done today
else {
todayTasks.add(task);
}
}
_tasks = todayTasks;
_history = oldTasks;
notifyListeners();
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/pomodoro_timer | mirrored_repositories/simple-flutter-apps/pomodoro_timer/lib/main.dart | import 'package:flutter/material.dart';
import 'pomodoro_page.dart';
void main() {
runApp(const PomodoroApp());
}
class PomodoroApp extends StatelessWidget {
const PomodoroApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: PmodoroPage(),
);
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/pomodoro_timer | mirrored_repositories/simple-flutter-apps/pomodoro_timer/lib/pomodoro_page.dart | import 'dart:async';
import 'package:flutter/material.dart';
// ignore: constant_identifier_names
const int SESSION_DURATION = 25; //minutes
// ignore: constant_identifier_names
const int NORMAL_BREAK_DURATION = 5; //minutes
// ignore: constant_identifier_names
const int SESSION_COUNT_TILL_LONG_BREAK = 4; //sessions counts
// ignore: constant_identifier_names
const int LONG_BREAK_DURATION = 15; //minutes
class PmodoroPage extends StatefulWidget {
const PmodoroPage({super.key});
@override
State<PmodoroPage> createState() => _PmodoroPageState();
}
class _PmodoroPageState extends State<PmodoroPage> {
int minutes = SESSION_DURATION;
int seconds = 0;
String status = "Focus"; // all options: ['Focus', 'Break', 'Long Break']
bool running = false;
int totalSessions = 0;
int streakSessions = 0;
Timer? _timer;
void _start() {
//if already running -> pause
if (running) return _pause();
//start running
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
setState(() {
running = true;
//if no time remaining
if (seconds == 0 && minutes == 0) {
if (status == "Focus") return _setBreak();
return _setFocus();
}
//time handling
if (seconds > 0) {
seconds--;
} else {
minutes--;
seconds = 59;
}
});
});
}
void _pause() {
setState(() {
_timer?.cancel();
running = false;
});
}
void _stop() {
setState(() {
_timer?.cancel();
running = false;
seconds = 0;
//reset minutes
if (status == "Focus") {
minutes = SESSION_DURATION;
} else if (status == "Long Break") {
minutes = LONG_BREAK_DURATION;
} else {
minutes = NORMAL_BREAK_DURATION;
}
});
}
void _setBreak() {
//set the break
setState(() {
totalSessions++;
streakSessions++;
seconds = 0;
//long break
if (streakSessions == SESSION_COUNT_TILL_LONG_BREAK) {
minutes = LONG_BREAK_DURATION;
streakSessions = 0;
status = "Long Break";
//normal break
} else {
minutes = NORMAL_BREAK_DURATION;
status = "Break";
}
_pause();
});
}
void _setFocus() {
//set focus time
setState(() {
minutes = SESSION_DURATION;
seconds = 0;
status = "Focus";
_pause();
});
}
void _resetApp() {
//reset all app vars
setState(() {
status = "Focus";
_stop();
totalSessions = 0;
streakSessions = 0;
});
}
String _getTotalFocusTime() {
int totalMinutes = SESSION_DURATION * totalSessions;
int hours = totalMinutes ~/ 60;
int remMinutes = totalMinutes - (hours * 60);
return "${hours.toString().length > 1 ? hours : '0$hours'}:${remMinutes.toString().length > 1 ? remMinutes : '0$remMinutes'}";
}
Color _specifyColor() {
return status == "Focus" ? Colors.redAccent : Colors.blueAccent;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: _specifyColor(),
title: const Text(
"POMODORO TIMER",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
actions: [
IconButton(
onPressed: () {
_resetApp();
},
icon: const Icon(
Icons.refresh_sharp,
size: 35,
color: Colors.white,
),
)
],
),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
//status
Center(
child: Text(
status,
style: TextStyle(
fontSize: 45,
fontWeight: FontWeight.bold,
color: _specifyColor(),
),
),
),
//timer cards
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
//minutes
Container(
width: 150,
height: 200,
decoration: BoxDecoration(
color: _specifyColor(),
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: Text(
"${minutes.toString().length > 1 ? minutes : '0$minutes'}",
style: const TextStyle(
color: Colors.white,
fontSize: 70,
fontWeight: FontWeight.bold,
),
),
),
),
const Text(
" : ",
style: TextStyle(fontSize: 75),
),
//seconds
Container(
width: 150,
height: 200,
decoration: BoxDecoration(
color: _specifyColor(),
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: Text(
"${seconds.toString().length > 1 ? seconds : '0$seconds'}",
style: const TextStyle(
color: Colors.white,
fontSize: 70,
fontWeight: FontWeight.bold,
),
),
),
),
],
),
//buttons row
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
//stop button
GestureDetector(
onTap: () {
_stop();
},
child: CircleAvatar(
backgroundColor: _specifyColor(),
radius: 30,
child: const Icon(
Icons.stop,
size: 40,
),
),
),
//vertical spacing
const SizedBox(width: 20),
//start button
GestureDetector(
onTap: () {
_start();
},
child: CircleAvatar(
backgroundColor: _specifyColor(),
radius: 30,
child: Icon(
running ? Icons.pause : Icons.play_arrow,
size: 40,
),
),
),
],
),
//stats
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Text(
"$totalSessions",
style: const TextStyle(
fontSize: 45,
),
),
const Text(
"sessions",
style: TextStyle(
fontSize: 25,
),
),
],
),
),
//focus time
Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Text(
_getTotalFocusTime(),
style: const TextStyle(
fontSize: 45,
),
),
const Text(
"focus time",
style: TextStyle(
fontSize: 25,
),
),
],
),
),
//streak sessions
Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Text(
"$streakSessions/$SESSION_COUNT_TILL_LONG_BREAK",
style: const TextStyle(
fontSize: 45,
),
),
const Text(
"streak",
style: TextStyle(
fontSize: 25,
),
),
],
),
),
],
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/bmi_calculator | mirrored_repositories/simple-flutter-apps/bmi_calculator/lib/main.dart | import 'package:flutter/material.dart';
import 'pages/input.dart';
void main() {
runApp(const BmiApp());
}
class BmiApp extends StatelessWidget {
const BmiApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: InputPage(),
);
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/bmi_calculator/lib | mirrored_repositories/simple-flutter-apps/bmi_calculator/lib/pages/output.dart | import 'dart:math';
import 'package:flutter/material.dart';
double _calculateBmi(int height, int weight) {
return weight / pow(height / 100, 2);
}
double _calulateIbw(int gender, int height) {
//convert height from cm to m
double heightM = height / 100;
//modify the height if the gender is Female
if (gender == 1) heightM -= 0.1;
//calulate the IBW
return 22.0 * pow(heightM, 2);
}
Map _analayzeBmi(double bmi, int gender, int height) {
String status;
Color color;
IconData icon;
String ideal;
//underweight
if (bmi < 18.5) {
status = "Underweight";
color = Colors.orange;
icon = Icons.error_outline;
}
//normal
else if (bmi <= 24) {
status = "Normal";
color = Colors.green;
icon = Icons.gpp_good_outlined;
}
//overweight
else if (bmi <= 29.9) {
status = "OverWeight";
color = Colors.orange;
icon = Icons.error_outline;
}
//obese
else {
status = "Obese";
color = Colors.red;
icon = Icons.dangerous_outlined;
}
//ideal weight
ideal = _calulateIbw(gender, height).toStringAsFixed(2);
return {
"status": status,
"color": color,
"ideal": "$ideal kg",
"icon": icon,
};
}
class OutputPage extends StatefulWidget {
final int weight;
final int height;
final int age;
final int gender;
const OutputPage(
{Key? key,
required this.weight,
required this.height,
required this.age,
required this.gender})
: super(key: key);
@override
State<OutputPage> createState() => _OutputPageState();
}
class _OutputPageState extends State<OutputPage> {
@override
Widget build(BuildContext context) {
double bmiDouble = _calculateBmi(widget.height, widget.weight);
String bmi = bmiDouble.toStringAsFixed(2);
Map info = _analayzeBmi(bmiDouble, widget.gender, widget.height);
return Scaffold(
appBar: AppBar(
title: const Text("Your Result"),
centerTitle: true,
),
body: Container(
height: double.infinity,
width: double.infinity,
color: Colors.blueGrey,
child: Center(
child: Container(
width: double.infinity,
height: 220,
margin: const EdgeInsets.all(15),
padding: const EdgeInsets.all(15),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: info["color"],
),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
info["icon"],
size: 60,
),
],
),
const SizedBox(
height: 5,
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
const Text(
"BMI: ",
style: TextStyle(
fontSize: 35,
decoration: TextDecoration.underline,
),
),
Text(
bmi,
style: const TextStyle(
fontSize: 30,
),
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
const Text(
"Status: ",
style: TextStyle(
fontSize: 35,
decoration: TextDecoration.underline,
),
),
Text(
info["status"],
style: const TextStyle(
fontSize: 30,
),
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
const Text(
"IBW: ",
style: TextStyle(
fontSize: 35,
decoration: TextDecoration.underline,
),
),
Text(
info["ideal"],
style: const TextStyle(
fontSize: 30,
),
)
],
),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/simple-flutter-apps/bmi_calculator/lib | mirrored_repositories/simple-flutter-apps/bmi_calculator/lib/pages/input.dart | import 'package:flutter/material.dart';
import 'output.dart';
class InputPage extends StatefulWidget {
const InputPage({super.key});
@override
State<InputPage> createState() => _InputPageState();
}
class _InputPageState extends State<InputPage> {
int? gender;
int height = 170;
int weight = 80;
int age = 30;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("BMI Calculator"),
centerTitle: true,
),
body: Column(
children: [
//genders row
Expanded(
child: Row(
children: [
//male card
Expanded(
child: GestureDetector(
onTap: () {
setState(() {
gender = 0;
});
},
child: Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color:
gender == 0 ? Colors.lightGreen : Colors.lightBlue,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Icon(
Icons.male,
size: 100,
color: Colors.white,
),
SizedBox(
height: 7,
),
Text(
"Male",
style: TextStyle(
fontSize: 22,
color: Colors.white,
),
),
],
),
),
),
),
//female card
Expanded(
child: GestureDetector(
onTap: () {
setState(() {
gender = 1;
});
},
child: Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color:
gender == 1 ? Colors.lightGreen : Colors.lightBlue,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Icon(
Icons.female,
size: 100,
color: Colors.white,
),
SizedBox(
height: 7,
),
Text(
"Female",
style: TextStyle(
fontSize: 22,
color: Colors.white,
),
),
],
),
),
),
),
],
),
),
//height row
Expanded(
child: Row(
children: [
Expanded(
child: Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: Colors.lightBlue,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"Height",
style: TextStyle(
fontSize: 21,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
height.toString(),
style: const TextStyle(
color: Colors.white,
fontSize: 50,
fontWeight: FontWeight.bold,
),
),
const Text(
" cm",
style: TextStyle(
color: Colors.white,
fontSize: 21,
),
),
],
),
Slider(
value: height.toDouble(),
min: 100.0,
max: 250.0,
onChanged: (value) {
setState(() {
height = value.toInt();
});
},
thumbColor: Colors.lightGreen,
activeColor: Colors.white,
inactiveColor:
const Color.fromARGB(255, 86, 183, 228),
),
],
),
),
),
],
),
),
//weight and age row
//weight card
Expanded(
child: Row(
children: [
Expanded(
child: Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: Colors.lightBlue,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"Weight",
style: TextStyle(
fontSize: 21,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
weight.toString(),
style: const TextStyle(
color: Colors.white,
fontSize: 40,
fontWeight: FontWeight.bold,
),
),
const Text(
" kg",
style: TextStyle(
color: Colors.white,
fontSize: 21,
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
GestureDetector(
onTap: () {
setState(() {
if (weight == 200) return;
weight++;
});
},
child: const CircleAvatar(
backgroundColor: Colors.white,
radius: 20,
child: Icon(Icons.add),
),
),
GestureDetector(
onTap: () {
setState(() {
if (weight == 20) return;
weight--;
});
},
child: const CircleAvatar(
backgroundColor: Colors.white,
radius: 20,
child: Icon(Icons.remove),
),
),
],
)
],
),
),
),
//age card
Expanded(
child: Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: Colors.lightBlue,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"Age",
style: TextStyle(
fontSize: 21,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
age.toString(),
style: const TextStyle(
color: Colors.white,
fontSize: 40,
fontWeight: FontWeight.bold,
),
),
const Text(
" yr",
style: TextStyle(
color: Colors.white,
fontSize: 21,
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
GestureDetector(
onTap: () {
setState(() {
if (age == 65) return;
age++;
});
},
child: const CircleAvatar(
backgroundColor: Colors.white,
radius: 20,
child: Icon(Icons.add),
),
),
GestureDetector(
onTap: () {
setState(() {
if (age == 18) return;
age--;
});
},
child: const CircleAvatar(
backgroundColor: Colors.white,
radius: 20,
child: Icon(Icons.remove),
),
),
],
)
],
),
),
),
],
),
),
//calculate button
GestureDetector(
onTap: () {
if (gender == null) return;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => OutputPage(
weight: weight,
height: height,
age: age,
gender: gender ?? 0,
)),
);
},
child: Container(
color: Colors.lightGreen,
width: double.infinity,
height: 50,
child: const Center(
child: Text(
"CALCULATE",
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/app_store | mirrored_repositories/app_store/lib/main.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:app_store/pages/landing.dart';
import 'package:app_store/pages/settings.dart';
import 'package:app_store/pages/updates.dart';
import 'package:app_store/providers/filter_provider.dart';
import 'package:app_store/providers/locale_provider.dart';
import 'package:app_store/providers/theme_provider.dart';
import 'package:app_store/theme/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/locale.dart' as intl;
import 'package:provider/provider.dart';
import 'package:yatl_flutter/yatl_flutter.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await initProviders();
await yatl.init();
runApp(
YatlApp(
core: yatl,
getLocale: () =>
intl.Locale.tryParse(preferences.locale ?? '')?.toFlutterLocale(),
setLocale: (locale) => preferences.locale = locale?.toString(),
child: MultiProvider(
providers: [
ChangeNotifierProvider<ThemeProvider>.value(
value: ThemeProvider(themeData: lightTheme, themeSwitched: false),
),
ChangeNotifierProvider<FilterProvider>.value(
value: FilterProvider(appItems.toSet()),
),
],
child: const AppStore(),
),
),
);
}
class AppStore extends StatelessWidget {
const AppStore({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'App Store',
theme: theme(context),
supportedLocales: context.supportedLocales,
locale: context.locale,
localizationsDelegates: [
GlobalWidgetsLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
context.localizationsDelegate,
],
debugShowCheckedModeBanner: false,
initialRoute: '/',
routes: {
'/': (context) => const Landing(),
'/updates': (context) => const Updates(),
'/settings': (context) => const Settings(),
},
);
}
}
| 0 |
mirrored_repositories/app_store/lib/widgets | mirrored_repositories/app_store/lib/widgets/cards/app_item.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:app_store/models/app/app_item_model.dart';
import 'package:app_store/pages/app_page.dart';
import 'package:flutter/material.dart';
import 'package:pub_semver/pub_semver.dart';
class AppItem extends StatelessWidget {
const AppItem({
required this.name,
required this.rating,
required this.categories,
required this.id,
required this.icon,
required this.version,
required this.briefDescription,
required this.description,
required this.developers,
required this.technologies,
required this.locales,
required this.appSize,
required this.source,
required this.donationLinks,
super.key,
});
final String name;
final double rating;
final Set<AppCategory> categories;
final int id;
final Image icon;
final Version version;
final String briefDescription;
final String description;
final List<String> developers;
final List<String> technologies;
final List<String> locales;
final int appSize;
final AppSources source;
final Map<String, String> donationLinks;
@override
Widget build(BuildContext context) {
return Container(
constraints: const BoxConstraints(
minHeight: 85,
minWidth: 175,
maxHeight: 85,
maxWidth: 250,
),
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(15)),
),
clipBehavior: Clip.antiAlias,
margin: const EdgeInsets.only(
bottom: 30,
right: 10,
),
child: Material(
child: InkWell(
splashColor: Theme.of(context).primaryColor,
onTap: () {
Navigator.push<void>(
context,
MaterialPageRoute<void>(
builder: (BuildContext context) => AppPage(
name: name,
rating: rating,
categories: categories,
id: id,
icon: icon,
version: version,
briefDescription: briefDescription,
description: description,
developers: developers,
technologies: technologies,
locales: locales,
appSize: appSize,
source: source,
donationLinks: donationLinks,
),
),
);
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const SizedBox(
width: 15,
),
SizedBox(
height: 50,
width: 50,
child: icon,
),
const SizedBox(
width: 15,
),
Wrap(
direction: Axis.vertical,
spacing: 3,
children: <Widget>[
Text(
name,
style: Theme.of(context).textTheme.headline2,
),
for (final item in categories)
Text(
AppCategory.translateString(item),
style: Theme.of(context).textTheme.subtitle2,
overflow: TextOverflow.clip,
),
Row(
children: [
Text(
rating.toString(),
style: Theme.of(context).textTheme.subtitle2,
),
const SizedBox(
width: 2,
),
Icon(
Icons.star,
size: 12,
color: Theme.of(context).iconTheme.color,
),
],
),
],
),
const SizedBox(
width: 15,
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/app_store/lib/widgets | mirrored_repositories/app_store/lib/widgets/cards/app_category_item.dart | import 'package:flutter/material.dart';
class AppCategoryItem extends StatelessWidget {
const AppCategoryItem({
required this.name,
required this.tooltip,
required this.icon,
super.key,
});
final String name;
final String tooltip;
final IconData icon;
@override
Widget build(BuildContext context) {
return Tooltip(
message: tooltip,
preferBelow: false,
verticalOffset: 35,
child: Column(
children: <Widget>[
SizedBox(
height: 60,
width: 60,
child: Card(
child: Icon(icon),
),
),
const SizedBox(
height: 10,
),
Text(
name,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodySmall!.apply(
color: Theme.of(context).textTheme.subtitle2!.color,
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/app_store/lib/widgets | mirrored_repositories/app_store/lib/widgets/text/app_review_item.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:flutter/material.dart';
class ReviewItem extends StatelessWidget {
const ReviewItem({
required this.name,
required this.comment,
required this.rating,
super.key,
});
final String name;
final String comment;
final int rating;
@override
Widget build(BuildContext context) {
return Container(
width: 145,
height: 60,
margin: const EdgeInsets.only(right: 10, bottom: 10),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Icon(
Icons.person,
color: Theme.of(context).iconTheme.color,
size: 30,
),
const SizedBox(
width: 10,
),
Wrap(
direction: Axis.vertical,
spacing: 1,
children: <Widget>[
Text(
name,
style: Theme.of(context).textTheme.headline2,
),
Text(
comment,
style: Theme.of(context).textTheme.bodySmall!.apply(
color: Theme.of(context).textTheme.subtitle2!.color,
),
),
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
rating.toString(),
style: Theme.of(context).textTheme.bodyMedium!.apply(
color: Theme.of(context).textTheme.subtitle2!.color,
),
),
Icon(
Icons.star,
size: 12,
color: Theme.of(context).iconTheme.color,
),
],
)
],
),
],
),
);
}
}
| 0 |
mirrored_repositories/app_store/lib/widgets | mirrored_repositories/app_store/lib/widgets/buttons/icon_button.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:flutter/material.dart';
class MyIconButton extends StatelessWidget {
const MyIconButton({
this.icon,
this.onPressed,
super.key,
});
final IconData? icon;
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) {
return Ink(
decoration: ShapeDecoration(
color: Theme.of(context).backgroundColor,
shape: const CircleBorder(),
),
child: IconButton(
hoverColor: Theme.of(context).hoverColor,
splashColor: Theme.of(context).primaryColor,
splashRadius: 20,
padding: const EdgeInsets.all(10),
iconSize: 20,
onPressed: () => onPressed?.call(),
icon: Icon(
icon,
color: Theme.of(context).iconTheme.color,
),
),
);
}
}
| 0 |
mirrored_repositories/app_store/lib/widgets | mirrored_repositories/app_store/lib/widgets/text_fields/search_bar.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:flutter/material.dart';
class SearchBar extends StatelessWidget {
const SearchBar({
this.hint,
this.icon,
super.key,
});
final String? hint;
final IconData? icon;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(bottom: 20),
height: 40,
width: 250,
child: TextField(
style: Theme.of(context)
.textTheme
.bodyMedium!
.apply(color: Theme.of(context).textTheme.subtitle2!.color),
decoration: InputDecoration(
isDense: true,
contentPadding: const EdgeInsets.fromLTRB(5, 1, 5, 1),
prefixIcon: Icon(icon),
prefixIconColor:
Theme.of(context).inputDecorationTheme.prefixIconColor,
hintText: hint,
hintStyle: Theme.of(context).textTheme.subtitle2,
enabledBorder: Theme.of(context).inputDecorationTheme.enabledBorder,
focusedBorder: Theme.of(context).inputDecorationTheme.focusedBorder,
),
),
);
}
}
| 0 |
mirrored_repositories/app_store/lib | mirrored_repositories/app_store/lib/pages/landing.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:app_store/models/app/app_item_model.dart';
import 'package:app_store/models/buttons/chip_button_model.dart';
import 'package:app_store/pages/featured_applications.dart';
import 'package:app_store/pages/new_applications.dart';
import 'package:app_store/pages/trending_applications.dart';
import 'package:app_store/pages/updates.dart';
import 'package:app_store/providers/filter_provider.dart';
import 'package:app_store/providers/locale_provider.dart';
import 'package:app_store/widgets/buttons/icon_button.dart';
import 'package:app_store/widgets/cards/app_item.dart';
import 'package:app_store/widgets/text_fields/search_bar.dart';
import 'package:badges/badges.dart';
import 'package:expandable_page_view/expandable_page_view.dart';
import 'package:flutter/material.dart' hide Badge;
import 'package:provider/provider.dart';
class Landing extends StatefulWidget {
const Landing({super.key});
static List<ChipButtonModel> get _chipButtons => <ChipButtonModel>[
ChipButtonModel(
name: strings.category.all,
icon: Icons.apps,
id: 1,
category: AppCategory.all,
),
ChipButtonModel(
name: strings.category.design,
icon: Icons.design_services,
id: 2,
category: AppCategory.design,
),
ChipButtonModel(
name: strings.category.games,
icon: Icons.games,
id: 3,
category: AppCategory.games,
),
ChipButtonModel(
name: strings.category.entertainment,
icon: Icons.movie,
id: 4,
category: AppCategory.entertainment,
),
ChipButtonModel(
name: strings.category.development,
icon: Icons.developer_mode,
id: 5,
category: AppCategory.development,
),
ChipButtonModel(
name: strings.category.music,
icon: Icons.audiotrack,
id: 6,
category: AppCategory.music,
),
ChipButtonModel(
name: strings.category.productivity,
icon: Icons.work,
id: 7,
category: AppCategory.productivity,
),
ChipButtonModel(
name: strings.category.tools,
icon: Icons.developer_board,
id: 8,
category: AppCategory.tools,
),
ChipButtonModel(
name: strings.category.finance,
icon: Icons.money,
id: 9,
category: AppCategory.finance,
),
ChipButtonModel(
name: strings.category.health,
icon: Icons.health_and_safety,
id: 10,
category: AppCategory.health,
),
ChipButtonModel(
name: strings.category.education,
icon: Icons.cast_for_education,
id: 11,
category: AppCategory.education,
),
ChipButtonModel(
name: strings.category.fitness,
icon: Icons.fitness_center,
id: 12,
category: AppCategory.fitness,
),
ChipButtonModel(
name: strings.category.communication,
icon: Icons.comment,
id: 13,
category: AppCategory.communication,
),
ChipButtonModel(
name: strings.category.business,
icon: Icons.business,
id: 14,
category: AppCategory.business,
),
];
@override
State<Landing> createState() => _LandingState();
}
class _LandingState extends State<Landing> {
final PageController _pageController = PageController();
final ScrollController _scrollController = ScrollController();
final Set<int> _selectedChipButtons = <int>{1};
@override
Widget build(BuildContext context) {
final _filterprovider = Provider.of<FilterProvider>(context);
final size = MediaQuery.of(context).size;
final width = size.width;
return Scaffold(
body: ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
child: SingleChildScrollView(
controller: _scrollController,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 30),
child: Column(
children: <Widget>[
SizedBox(
width: width,
child: Wrap(
alignment: WrapAlignment.spaceBetween,
children: <Widget>[
SearchBar(
hint: strings.searchbar.hint,
icon: Icons.search,
),
Wrap(
children: [
Badge(
badgeContent: Text(
needsUpdate.length.toString(),
style: const TextStyle(
color: Colors.white,
fontSize: 12,
),
),
badgeColor: Theme.of(context).iconTheme.color!,
elevation: 0,
child: MyIconButton(
icon: Icons.upgrade,
onPressed: () {
Navigator.pushNamed(context, '/updates');
},
),
),
const SizedBox(
width: 10,
),
MyIconButton(
icon: Icons.settings,
onPressed: () {
Navigator.pushNamed(context, '/settings');
},
),
],
),
],
),
),
const SizedBox(
height: 40,
),
ScrollConfiguration(
behavior: ScrollConfiguration.of(context)
.copyWith(scrollbars: false),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Wrap(
spacing: width / 80,
children: Landing._chipButtons
.map(
(e) => Container(
constraints: const BoxConstraints(maxHeight: 80),
child: ChoiceChip(
materialTapTargetSize:
MaterialTapTargetSize.shrinkWrap,
label: Text(
e.name,
style: TextStyle(
color: _selectedChipButtons.contains(e.id)
? Colors.white
: null,
),
),
avatar: Icon(
e.icon,
size: 20,
color: _selectedChipButtons.contains(e.id)
? Colors.white
: Theme.of(context).iconTheme.color,
),
labelPadding:
Theme.of(context).chipTheme.labelPadding,
elevation:
Theme.of(context).chipTheme.elevation,
backgroundColor:
Theme.of(context).chipTheme.backgroundColor,
labelStyle:
Theme.of(context).textTheme.subtitle2,
pressElevation:
Theme.of(context).chipTheme.pressElevation,
selectedColor:
Theme.of(context).chipTheme.selectedColor,
onSelected: (value) {
setState(() {
if (value == true &&
_selectedChipButtons.contains(1) &&
_selectedChipButtons.length < 2) {
_selectedChipButtons
..remove(1)
..add(e.id);
_filterprovider.retainInAppFilter(e);
} else if (value == true && e.id == 1) {
_selectedChipButtons
..clear()
..add(1);
_filterprovider.clearAddAllInFilter(e);
} else if (value == true &&
_selectedChipButtons.length == 12) {
_selectedChipButtons
..clear()
..add(1);
_filterprovider.addInAppFilter(e);
} else if (value == false &&
_selectedChipButtons.length < 2) {
_selectedChipButtons
..remove(e.id)
..add(1);
_filterprovider.clearAddAllInFilter(e);
} else if (value == false) {
_selectedChipButtons.remove(e.id);
_filterprovider.removeInAppFilter(e);
} else if (value == true) {
_selectedChipButtons.add(e.id);
_filterprovider.addInAppFilter(e);
}
});
},
selected: _selectedChipButtons.contains(e.id),
),
),
)
.toList(),
),
),
),
const SizedBox(
height: 40,
),
ExpandablePageView(
physics: const NeverScrollableScrollPhysics(),
controller: _pageController,
children: <Widget>[
Column(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: <Widget>[
const Icon(Icons.trending_up),
const SizedBox(
width: 10,
),
Text(
strings.topic.trending,
style: Theme.of(context).textTheme.headline2,
),
IconButton(
onPressed: () {
loadPage(1);
scrollToTop();
},
icon: const Icon(Icons.navigate_next),
splashRadius: 18,
padding: EdgeInsets.zero,
color: Theme.of(context).iconTheme.color,
hoverColor: Theme.of(context).hoverColor,
splashColor: Theme.of(context).splashColor,
focusColor: Theme.of(context).focusColor,
highlightColor:
Theme.of(context).highlightColor,
tooltip: strings.topic.trendingHint,
)
],
),
const SizedBox(
height: 10,
),
Wrap(
spacing: width / 80,
children: <Widget>[
for (final item
in _filterprovider.getAppFilter())
AppItem(
name: item.name,
rating: item.rating,
categories: item.categories,
id: item.id,
icon: item.icon,
version: item.version,
briefDescription: item.briefDescription,
description: item.description,
developers: item.developers,
technologies: item.technologies,
locales: item.locales,
appSize: item.appSize,
source: item.source,
donationLinks: item.donationLinks,
),
],
),
],
),
const SizedBox(
height: 40,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: <Widget>[
const Icon(Icons.person_search),
const SizedBox(
width: 10,
),
Text(
strings.topic.featured,
style: Theme.of(context).textTheme.headline2,
),
IconButton(
onPressed: () {
loadPage(2);
scrollToTop();
},
icon: const Icon(Icons.navigate_next),
splashRadius: 18,
padding: EdgeInsets.zero,
color: Theme.of(context).iconTheme.color,
hoverColor: Theme.of(context).hoverColor,
splashColor: Theme.of(context).splashColor,
focusColor: Theme.of(context).focusColor,
highlightColor:
Theme.of(context).highlightColor,
tooltip: strings.topic.featuredHint,
)
],
),
const SizedBox(
height: 10,
),
Wrap(
spacing: width / 80,
children: <Widget>[
for (final item
in _filterprovider.getAppFilter())
AppItem(
name: item.name,
rating: item.rating,
categories: item.categories,
id: item.id,
icon: item.icon,
version: item.version,
briefDescription: item.briefDescription,
description: item.description,
developers: item.developers,
technologies: item.technologies,
locales: item.locales,
appSize: item.appSize,
source: item.source,
donationLinks: item.donationLinks,
),
],
),
],
),
const SizedBox(
height: 40,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: <Widget>[
const Icon(Icons.library_add),
const SizedBox(
width: 10,
),
Text(
strings.topic.newTopic,
style: Theme.of(context).textTheme.headline2,
),
IconButton(
onPressed: () {
loadPage(3);
scrollToTop();
},
icon: const Icon(Icons.navigate_next),
splashRadius: 18,
padding: EdgeInsets.zero,
color: Theme.of(context).iconTheme.color,
hoverColor: Theme.of(context).hoverColor,
splashColor: Theme.of(context).splashColor,
focusColor: Theme.of(context).focusColor,
highlightColor:
Theme.of(context).highlightColor,
tooltip: strings.topic.newHint,
)
],
),
const SizedBox(
height: 10,
),
Wrap(
spacing: width / 80,
children: <Widget>[
for (final item
in _filterprovider.getAppFilter())
AppItem(
name: item.name,
rating: item.rating,
categories: item.categories,
id: item.id,
icon: item.icon,
version: item.version,
briefDescription: item.briefDescription,
description: item.description,
developers: item.developers,
technologies: item.technologies,
locales: item.locales,
appSize: item.appSize,
source: item.source,
donationLinks: item.donationLinks,
),
],
),
],
),
],
),
TrendingApplications(loadPage, scrollToTop),
FeaturedApplications(loadPage, scrollToTop),
NewApplications(loadPage, scrollToTop),
],
),
],
),
),
),
),
);
}
void scrollToTop() {
if (_scrollController.offset > 30) {
_scrollController.animateTo(
0,
duration: const Duration(
milliseconds: 700,
),
curve: Curves.fastOutSlowIn,
);
}
}
void loadPage(int index) {
_pageController.jumpToPage(
index,
);
}
}
| 0 |
mirrored_repositories/app_store/lib | mirrored_repositories/app_store/lib/pages/updates.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:app_store/models/app/app_item_model.dart';
import 'package:app_store/providers/filter_provider.dart';
import 'package:app_store/providers/locale_provider.dart';
import 'package:flutter/material.dart';
class Updates extends StatefulWidget {
const Updates({super.key});
@override
State<Updates> createState() => _UpdatesState();
}
final Set<AppItemModel> needsUpdate = Set.from(appItems.take(5));
class _UpdatesState extends State<Updates> {
final Set<int> _isAppUpdating = {};
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.navigate_before),
onPressed: () {
Navigator.pop(context);
},
tooltip: MaterialLocalizations.of(context).backButtonTooltip,
),
title: Text(
strings.updates.title,
),
),
body: ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
child: SingleChildScrollView(
child: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 30),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
runSpacing: 5,
spacing: 10,
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
children: <Widget>[
Text(
strings.updates.title,
style: Theme.of(context).textTheme.headline2,
),
TextButton(
style: ButtonStyle(
minimumSize: MaterialStateProperty.all(
const Size(170, 36),
),
),
onPressed: () {
setState(() {
_isAppUpdating.length == needsUpdate.length
? _isAppUpdating.clear()
: _isAppUpdating.addAll({1, 2, 3, 4, 5});
});
},
child: Text(
_isAppUpdating.length == needsUpdate.length
? strings.updates.updateCancelAllButton
: strings.updates.updateAllButton,
overflow: TextOverflow.visible,
textAlign: TextAlign.center,
),
),
Wrap(
runSpacing: 15,
children: <Widget>[
for (final item in needsUpdate)
ListTile(
leading: SizedBox(
height: 40,
width: 40,
child: item.icon,
),
title: Text(
item.name,
style: Theme.of(context).textTheme.headline2,
),
subtitle: Text(
strings.updates.updateAvailable,
style: Theme.of(context)
.textTheme
.bodySmall!
.apply(
color: Theme.of(context)
.textTheme
.subtitle2!
.color,
),
),
trailing: TextButton(
style: ButtonStyle(
minimumSize: MaterialStateProperty.all(
const Size(110, 36),
),
),
onPressed: () {
setState(() {
_isAppUpdating.contains(item.id)
? _isAppUpdating.remove(item.id)
: _isAppUpdating.add(item.id);
});
},
child: Padding(
padding: const EdgeInsets.all(5),
child: _isAppUpdating.contains(item.id)
? Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
const SizedBox(
height: 15,
width: 15,
child:
CircularProgressIndicator(),
),
const SizedBox(
width: 5,
),
Text(
strings
.updates.updateCancelButton,
)
],
)
: Text(strings.updates.updateButton),
),
),
)
],
)
],
),
],
),
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/app_store/lib | mirrored_repositories/app_store/lib/pages/settings.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:app_store/providers/locale_provider.dart';
import 'package:app_store/providers/theme_provider.dart';
import 'package:app_store/theme/theme.dart';
import 'package:app_store/utils/native_names.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:yatl_flutter/yatl_flutter.dart';
class Settings extends StatelessWidget {
const Settings({super.key});
@override
Widget build(BuildContext context) {
final _themeprovider = Provider.of<ThemeProvider>(context);
final size = MediaQuery.of(context).size;
final width = size.width;
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.navigate_before),
onPressed: () {
Navigator.pop(context);
},
tooltip: MaterialLocalizations.of(context).backButtonTooltip,
),
title: Text(
strings.settings.title,
),
),
body: ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
child: SingleChildScrollView(
child: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 30),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
strings.settings.themeMode,
style: Theme.of(context).textTheme.headline2,
),
const SizedBox(
height: 15,
),
SwitchListTile(
title: Text(
strings.settings.darkMode,
style: Theme.of(context).textTheme.headline2,
),
subtitle: Text(
strings.settings.darkModeDescription,
style: Theme.of(context).textTheme.bodySmall!.apply(
color: Theme.of(context).textTheme.subtitle2!.color,
),
),
shape: Theme.of(context).listTileTheme.shape,
tileColor: Theme.of(context).listTileTheme.tileColor,
activeColor:
Theme.of(context).listTileTheme.selectedTileColor,
secondary: Icon(
Icons.dark_mode,
color: Theme.of(context).listTileTheme.iconColor,
size: 30,
),
onChanged: (bool value) {
_themeprovider.setThemeSwitched(value: value);
_themeprovider.getThemeSwitched()
? _themeprovider.setTheme(darkTheme)
: _themeprovider.setTheme(lightTheme);
},
value: _themeprovider.getThemeSwitched(),
),
const SizedBox(
height: 20,
),
Text(
strings.settings.locale,
style: Theme.of(context).textTheme.headline2,
),
const SizedBox(
height: 15,
),
Theme(
data: Theme.of(context)
.copyWith(dividerColor: Colors.transparent),
child: ExpansionTile(
childrenPadding: const EdgeInsets.only(top: 30),
expandedAlignment: Alignment.center,
expandedCrossAxisAlignment: CrossAxisAlignment.start,
title: Text(
strings.settings.localeTitle,
style: Theme.of(context).textTheme.headline2,
),
subtitle: Text(
strings.settings.localeDescription,
style: Theme.of(context).textTheme.bodySmall!.apply(
color:
Theme.of(context).textTheme.subtitle2!.color,
),
),
leading: Icon(
Icons.language,
color: Theme.of(context).listTileTheme.iconColor,
size: 30,
),
children: <Widget>[
Wrap(
spacing: width / 83,
children: [
for (final item in locales.supportedLocales)
Wrap(
spacing: 5,
direction: Axis.vertical,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
SizedBox(
width: 80,
height: 80,
child: InkWell(
borderRadius: BorderRadius.circular(15),
onTap: () {
context.locale = item.toFlutterLocale();
final snackBar = SnackBar(
clipBehavior: Clip.antiAlias,
content: Text(
'Locale successfully set to ${localeNativeNames[item.languageCode]} (${item.toLanguageTag()})',
style: Theme.of(context)
.textTheme
.headline2,
),
behavior: SnackBarBehavior.floating,
width: 400,
duration: const Duration(seconds: 1),
action: SnackBarAction(
textColor: Theme.of(context)
.textTheme
.subtitle2!
.color,
label: 'Close',
onPressed: () {},
),
);
ScaffoldMessenger.of(context)
.showSnackBar(snackBar);
},
splashColor:
Theme.of(context).primaryColor,
child: Center(
child: Text(
item.countryCode!.replaceAllMapped(
RegExp('[A-Z]'),
(match) => String.fromCharCode(
match.group(0)!.codeUnitAt(0) +
127397,
),
),
style: const TextStyle(
fontSize: 50,
),
),
),
),
),
Text(
localeNativeNames[item.languageCode] ??
'Language code not found',
style:
Theme.of(context).textTheme.headline2,
),
Text(
item.toLanguageTag(),
style:
Theme.of(context).textTheme.subtitle2,
),
Container(
margin: const EdgeInsets.only(bottom: 10),
child: Text(
'${locales.progressData[item.toLanguageTag()]} / ${locales.progressData[context.fallbackLocale.toLanguageTag()]}',
style:
Theme.of(context).textTheme.subtitle2,
),
),
],
),
],
),
],
),
),
],
),
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/app_store/lib | mirrored_repositories/app_store/lib/pages/app_page.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:app_store/models/app/app_item_model.dart';
import 'package:app_store/models/text/app_review_model.dart';
import 'package:app_store/providers/filter_provider.dart';
import 'package:app_store/providers/locale_provider.dart';
import 'package:app_store/widgets/cards/app_category_item.dart';
import 'package:app_store/widgets/cards/app_item.dart';
import 'package:app_store/widgets/text/app_review_item.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pub_semver/pub_semver.dart';
import 'package:url_launcher/url_launcher.dart';
final _reviewItems = <ReviewItemModel>[
ReviewItemModel(name: 'Marin Heđeš', comment: 'Good app.', rating: 4),
ReviewItemModel(name: 'Noah Cain', comment: 'Decent.', rating: 3),
ReviewItemModel(name: 'Davide Bianco', comment: 'Awesome!', rating: 1),
ReviewItemModel(name: 'Blake Leonard', comment: 'Not bad.', rating: 4),
ReviewItemModel(name: 'Camden Bruce', comment: 'Splendid.', rating: 5),
];
class AppPage extends StatelessWidget {
const AppPage({
required this.name,
required this.rating,
required this.categories,
required this.id,
required this.icon,
required this.version,
required this.briefDescription,
required this.description,
required this.developers,
required this.technologies,
required this.locales,
required this.appSize,
required this.source,
required this.donationLinks,
super.key,
});
final String name;
final double rating;
final Set<AppCategory> categories;
final int id;
final Image icon;
final Version version;
final String briefDescription;
final String description;
final List<String> developers;
final List<String> technologies;
final List<String> locales;
final int appSize;
final AppSources source;
final Map<String, String> donationLinks;
@override
Widget build(BuildContext context) {
final _filterprovider = Provider.of<FilterProvider>(context);
final size = MediaQuery.of(context).size;
final width = size.width;
final height = size.height;
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.navigate_before),
onPressed: () {
Navigator.pop(context);
},
tooltip: MaterialLocalizations.of(context).backButtonTooltip,
),
title: Text(
name,
),
),
body: ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 30),
child: Column(
children: <Widget>[
SizedBox(
width: width,
child: Wrap(
alignment: WrapAlignment.spaceBetween,
children: [
Wrap(
spacing: width / 90,
children: [
Container(
height: 140,
width: 140,
margin: const EdgeInsets.only(bottom: 20),
child: icon,
),
const SizedBox(
width: 5,
),
Wrap(
direction: Axis.vertical,
spacing: 5,
children: <Widget>[
Text(
name,
style: Theme.of(context).textTheme.headline1,
),
SizedBox(
width: width / 3,
child: Text(
briefDescription,
style: Theme.of(context).textTheme.subtitle1,
overflow: TextOverflow.clip,
),
),
Text(
categories
.map(AppCategory.translateString)
.toList()
.join(', '),
style: Theme.of(context).textTheme.subtitle1,
),
Text(
version.toString(),
style: Theme.of(context).textTheme.subtitle1,
),
],
),
],
),
const SizedBox(
width: 20,
),
Wrap(
children: <Widget>[
Container(
margin: const EdgeInsets.only(bottom: 20),
child: ElevatedButton(
onPressed: () {
showDialog<Dialog>(
context: context,
builder: (BuildContext context) {
return Dialog(
child: SizedBox(
height: 300,
width: 400,
child: Padding(
padding: const EdgeInsets.only(
right: 10,
bottom: 10,
top: 30,
left: 30,
),
child: Column(
mainAxisAlignment:
MainAxisAlignment.end,
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Text(
strings.appPage
.downloadDialogTitle,
style: Theme.of(context)
.textTheme
.headline1,
overflow: TextOverflow.clip,
),
const SizedBox(
height: 10,
),
Text(
strings.appPage
.downloadDialogDescription,
style: Theme.of(context)
.textTheme
.subtitle1,
overflow: TextOverflow.clip,
),
const Spacer(),
Row(
mainAxisAlignment:
MainAxisAlignment.end,
children: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(
strings.appPage
.downloadDialogConfirmInstallation,
),
),
const SizedBox(
width: 10,
),
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(
strings.appPage
.downloadDialogCancelInstallation,
),
)
],
),
],
),
),
),
);
},
);
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Icon(
Icons.download,
color: Colors.white,
size: 18,
),
const SizedBox(
width: 5,
),
Text(
strings.appPage.download,
style: const TextStyle(color: Colors.white),
),
],
),
),
),
const SizedBox(
width: 15,
),
if (donationLinks.isNotEmpty)
OutlinedButton(
onPressed: () {
showDialog<Dialog>(
context: context,
builder: (BuildContext context) {
return Dialog(
backgroundColor: Theme.of(context)
.dialogTheme
.backgroundColor,
child: SizedBox(
height: 300,
width: 400,
child: Padding(
padding: const EdgeInsets.only(
right: 10,
bottom: 10,
top: 30,
left: 30,
),
child: Column(
mainAxisAlignment:
MainAxisAlignment.end,
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Text(
strings
.appPage.donateDialogTitle,
style: Theme.of(context)
.textTheme
.headline1,
overflow: TextOverflow.clip,
),
const SizedBox(
height: 10,
),
Text(
strings.appPage
.donateDialogDescription,
style: Theme.of(context)
.textTheme
.subtitle1,
overflow: TextOverflow.clip,
),
const Spacer(),
SizedBox(
width: width,
child: Wrap(
alignment: WrapAlignment.end,
children: <Widget>[
Wrap(
children: donationLinks
.entries
.map(
(e) => TextButton(
onPressed: () {
launchUrl(
Uri.parse(
e.value,
),
);
},
child: Text(
e.key,
overflow:
TextOverflow
.clip,
),
),
)
.toList(),
),
const SizedBox(
width: 10,
),
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(
strings.appPage
.donateDialogClose,
),
)
],
),
),
],
),
),
),
);
},
);
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Icon(
Icons.payment,
color: Colors.deepOrange,
size: 18,
),
const SizedBox(
width: 5,
),
Text(
strings.appPage.donate,
style: const TextStyle(
color: Colors.deepOrange,
),
),
],
),
)
else
const SizedBox.shrink(),
],
),
],
),
),
const SizedBox(
height: 50,
),
SizedBox(
width: width,
child: Wrap(
alignment: WrapAlignment.spaceBetween,
children: <Widget>[
AppCategoryItem(
name: developers.join(', '),
tooltip: strings.appPage.informationDeveloperHint,
icon: Icons.person,
),
AppCategoryItem(
name: technologies.join('\n'),
tooltip: strings.appPage.informationTechnologyHint,
icon: Icons.code,
),
AppCategoryItem(
name: '#1',
tooltip: strings.appPage.informationTrendingHint,
icon: Icons.leaderboard,
),
AppCategoryItem(
name: locales.join(', '),
tooltip: strings.appPage.informationLocaleHint,
icon: Icons.language,
),
AppCategoryItem(
name: '$appSize' 'MB',
tooltip: strings.appPage.informationSizeHint,
icon: Icons.sd_storage,
),
AppCategoryItem(
name: AppSources.sourceName(source),
tooltip: strings.appPage.informationSourceHint,
icon: Icons.source,
),
],
),
),
const SizedBox(
height: 50,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
const Icon(Icons.description),
const SizedBox(
width: 10,
),
Text(
strings.appPage.longDescriptionTitle,
style: Theme.of(context).textTheme.headline2,
)
],
),
const SizedBox(
height: 20,
),
Text(
description,
style: Theme.of(context).textTheme.bodyMedium!.apply(
color: Theme.of(context).textTheme.subtitle2!.color,
),
overflow: TextOverflow.clip,
)
],
),
const SizedBox(
height: 50,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
const Icon(Icons.image),
const SizedBox(
width: 10,
),
Text(
strings.appPage.images,
style: Theme.of(context).textTheme.headline2,
)
],
),
const SizedBox(
height: 20,
),
SizedBox(
width: width,
child: Wrap(
alignment: WrapAlignment.spaceBetween,
children: <Widget>[
SizedBox(
width: width / 5,
height: height / 5,
child: const Card(),
),
SizedBox(
width: width / 5,
height: height / 5,
child: const Card(),
),
SizedBox(
width: width / 5,
height: height / 5,
child: const Card(),
),
SizedBox(
width: width / 5,
height: height / 5,
child: const Card(),
),
],
),
)
],
),
const SizedBox(
height: 50,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
const Icon(Icons.reviews),
const SizedBox(
width: 10,
),
Text(
strings.appPage.reviews,
style: Theme.of(context).textTheme.headline2,
)
],
),
const SizedBox(
height: 20,
),
SizedBox(
width: width,
child: Wrap(
alignment: WrapAlignment.spaceBetween,
children: <Widget>[
for (final item in _reviewItems)
ReviewItem(
name: item.name,
comment: item.comment,
rating: item.rating,
),
],
),
),
const SizedBox(
height: 50,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
const Icon(Icons.control_point_duplicate),
const SizedBox(
width: 10,
),
Text(
strings.appPage.similarApplications,
style: Theme.of(context).textTheme.headline2,
)
],
),
const SizedBox(
height: 20,
),
Wrap(
spacing: width / 80,
children: <Widget>[
for (final item in _filterprovider.getAppFilter())
AppItem(
name: item.name,
rating: item.rating,
categories: item.categories,
id: item.id,
icon: item.icon,
version: item.version,
briefDescription: item.briefDescription,
description: item.description,
developers: item.developers,
technologies: item.technologies,
locales: item.locales,
appSize: item.appSize,
source: item.source,
donationLinks: item.donationLinks,
),
],
),
],
)
],
),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/app_store/lib | mirrored_repositories/app_store/lib/pages/trending_applications.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:app_store/providers/filter_provider.dart';
import 'package:app_store/providers/locale_provider.dart';
import 'package:app_store/widgets/cards/app_item.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class TrendingApplications extends StatelessWidget {
const TrendingApplications(
this.loadPage,
this.scrollToTop, {
super.key,
});
final void Function(int) loadPage;
final void Function() scrollToTop;
@override
Widget build(BuildContext context) {
final _filterprovider = Provider.of<FilterProvider>(context);
final size = MediaQuery.of(context).size;
final width = size.width;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: <Widget>[
const Icon(Icons.trending_up),
const SizedBox(
width: 10,
),
Text(
strings.topic.trending,
style: Theme.of(context).textTheme.headline2,
),
IconButton(
onPressed: () {
loadPage(0);
scrollToTop();
},
icon: const Icon(Icons.navigate_before),
splashRadius: 18,
padding: EdgeInsets.zero,
color: Theme.of(context).iconTheme.color,
hoverColor: Theme.of(context).hoverColor,
splashColor: Theme.of(context).splashColor,
focusColor: Theme.of(context).focusColor,
highlightColor: Theme.of(context).highlightColor,
tooltip: strings.topic.showAll,
)
],
),
const SizedBox(
height: 10,
),
Wrap(
spacing: width / 80,
children: <Widget>[
for (final item in _filterprovider.getAppFilter())
AppItem(
name: item.name,
rating: item.rating,
categories: item.categories,
id: item.id,
icon: item.icon,
version: item.version,
briefDescription: item.briefDescription,
description: item.description,
developers: item.developers,
technologies: item.technologies,
locales: item.locales,
appSize: item.appSize,
source: item.source,
donationLinks: item.donationLinks,
),
],
),
],
);
}
}
| 0 |
mirrored_repositories/app_store/lib | mirrored_repositories/app_store/lib/pages/new_applications.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:app_store/providers/filter_provider.dart';
import 'package:app_store/providers/locale_provider.dart';
import 'package:app_store/widgets/cards/app_item.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class NewApplications extends StatelessWidget {
const NewApplications(
this.loadPage,
this.scrollToTop, {
super.key,
});
final void Function(int) loadPage;
final void Function() scrollToTop;
@override
Widget build(BuildContext context) {
final _filterprovider = Provider.of<FilterProvider>(context);
final size = MediaQuery.of(context).size;
final width = size.width;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: <Widget>[
const Icon(Icons.library_add),
const SizedBox(
width: 10,
),
Text(
strings.topic.newTopic,
style: Theme.of(context).textTheme.headline2,
),
IconButton(
onPressed: () {
loadPage(0);
scrollToTop();
},
icon: const Icon(Icons.navigate_before),
splashRadius: 18,
padding: EdgeInsets.zero,
color: Theme.of(context).iconTheme.color,
hoverColor: Theme.of(context).hoverColor,
splashColor: Theme.of(context).splashColor,
focusColor: Theme.of(context).focusColor,
highlightColor: Theme.of(context).highlightColor,
tooltip: strings.topic.showAll,
)
],
),
const SizedBox(
height: 10,
),
Wrap(
spacing: width / 80,
children: <Widget>[
for (final item in _filterprovider.getAppFilter())
AppItem(
name: item.name,
rating: item.rating,
categories: item.categories,
id: item.id,
icon: item.icon,
version: item.version,
briefDescription: item.briefDescription,
description: item.description,
developers: item.developers,
technologies: item.technologies,
locales: item.locales,
appSize: item.appSize,
source: item.source,
donationLinks: item.donationLinks,
),
],
),
],
);
}
}
| 0 |
mirrored_repositories/app_store/lib | mirrored_repositories/app_store/lib/pages/featured_applications.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:app_store/providers/filter_provider.dart';
import 'package:app_store/providers/locale_provider.dart';
import 'package:app_store/widgets/cards/app_item.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class FeaturedApplications extends StatelessWidget {
const FeaturedApplications(
this.loadPage,
this.scrollToTop, {
super.key,
});
final void Function(int) loadPage;
final void Function() scrollToTop;
@override
Widget build(BuildContext context) {
final _filterprovider = Provider.of<FilterProvider>(context);
final size = MediaQuery.of(context).size;
final width = size.width;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: <Widget>[
const Icon(Icons.person_search),
const SizedBox(
width: 10,
),
Text(
strings.topic.featured,
style: Theme.of(context).textTheme.headline2,
),
IconButton(
onPressed: () {
loadPage(0);
scrollToTop();
},
icon: const Icon(Icons.navigate_before),
splashRadius: 18,
padding: EdgeInsets.zero,
color: Theme.of(context).iconTheme.color,
hoverColor: Theme.of(context).hoverColor,
splashColor: Theme.of(context).splashColor,
focusColor: Theme.of(context).focusColor,
highlightColor: Theme.of(context).highlightColor,
tooltip: strings.topic.showAll,
)
],
),
const SizedBox(
height: 10,
),
Wrap(
spacing: width / 80,
children: <Widget>[
for (final item in _filterprovider.getAppFilter())
AppItem(
name: item.name,
rating: item.rating,
categories: item.categories,
id: item.id,
icon: item.icon,
version: item.version,
briefDescription: item.briefDescription,
description: item.description,
developers: item.developers,
technologies: item.technologies,
locales: item.locales,
appSize: item.appSize,
source: item.source,
donationLinks: item.donationLinks,
),
],
),
],
);
}
}
| 0 |
mirrored_repositories/app_store/lib/models | mirrored_repositories/app_store/lib/models/app/app_item_model.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:app_store/providers/locale_provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:pub_semver/pub_semver.dart';
@immutable
class AppItemModel {
const AppItemModel({
required this.name,
required this.rating,
required this.categories,
required this.id,
required this.icon,
required this.version,
required this.briefDescription,
required this.description,
required this.developers,
required this.technologies,
required this.locales,
required this.appSize,
required this.source,
required this.donationLinks,
});
final String name;
final double rating;
final Set<AppCategory> categories;
final int id;
final Image icon;
final Version version;
final String briefDescription;
final String description;
final List<String> developers;
final List<String> technologies;
final List<String> locales;
final int appSize;
final AppSources source;
final Map<String, String> donationLinks;
@override
int get hashCode => Object.hash(
name,
rating,
categories,
id,
icon,
version,
briefDescription,
description,
developers,
technologies,
locales,
appSize,
source,
donationLinks,
);
@override
bool operator ==(Object other) {
if (other is AppItemModel) {
return name == other.name &&
rating == other.rating &&
setEquals(categories, other.categories) &&
id == other.id &&
icon == other.icon &&
version == other.version &&
briefDescription == other.briefDescription &&
description == other.description &&
developers == other.developers &&
technologies == other.technologies &&
locales == other.locales &&
appSize == other.appSize &&
source == other.source &&
donationLinks == other.donationLinks;
}
return false;
}
}
enum AppCategory {
all,
design,
games,
entertainment,
development,
music,
productivity,
tools,
finance,
health,
education,
fitness,
communication,
business;
static String translateString(AppCategory category) {
switch (category) {
case all:
{
return strings.category.all;
}
case design:
{
return strings.category.design;
}
case games:
{
return strings.category.games;
}
case entertainment:
{
return strings.category.entertainment;
}
case development:
{
return strings.category.development;
}
case music:
{
return strings.category.music;
}
case productivity:
{
return strings.category.productivity;
}
case tools:
{
return strings.category.tools;
}
case finance:
{
return strings.category.finance;
}
case health:
{
return strings.category.health;
}
case education:
{
return strings.category.education;
}
case fitness:
{
return strings.category.fitness;
}
case communication:
{
return strings.category.communication;
}
case business:
{
return strings.category.business;
}
}
}
}
enum AppSources {
foss,
oss,
proprietary;
static String sourceName(AppSources source) {
switch (source) {
case foss:
{
return 'FOSS';
}
case oss:
{
return 'OSS';
}
case proprietary:
{
return 'Proprietary';
}
}
}
}
| 0 |
mirrored_repositories/app_store/lib/models | mirrored_repositories/app_store/lib/models/text/app_review_model.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
class ReviewItemModel {
ReviewItemModel({
required this.name,
required this.comment,
required this.rating,
});
final String name;
final String comment;
final int rating;
}
| 0 |
mirrored_repositories/app_store/lib/models | mirrored_repositories/app_store/lib/models/buttons/chip_button_model.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:app_store/models/app/app_item_model.dart';
import 'package:flutter/material.dart';
class ChipButtonModel {
ChipButtonModel({
required this.name,
required this.icon,
required this.id,
required this.category,
});
final String name;
final IconData icon;
final int id;
final AppCategory category;
}
| 0 |
mirrored_repositories/app_store/lib | mirrored_repositories/app_store/lib/theme/theme.dart | /*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:flutter/material.dart';
final ThemeData darkTheme = ThemeData(
useMaterial3: true,
hoverColor: Colors.white24,
primaryColor: Colors.deepOrange,
backgroundColor: Colors.white10,
colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.deepOrange)
.copyWith(secondary: const Color(0xFF212121)),
iconTheme: const IconThemeData(color: Colors.deepOrange),
highlightColor: Colors.deepOrangeAccent,
focusColor: Colors.deepOrangeAccent,
splashColor: Colors.deepOrangeAccent,
snackBarTheme: const SnackBarThemeData(
backgroundColor: Colors.white10,
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(15)),
),
),
textTheme: const TextTheme(
button: TextStyle(
color: Colors.white,
fontSize: 11,
fontWeight: FontWeight.normal,
overflow: TextOverflow.ellipsis,
),
headline1: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w500,
fontSize: 17,
overflow: TextOverflow.ellipsis,
),
subtitle1: TextStyle(
color: Colors.white,
fontWeight: FontWeight.normal,
fontSize: 15,
overflow: TextOverflow.ellipsis,
),
headline2: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w500,
fontSize: 12,
overflow: TextOverflow.ellipsis,
),
subtitle2: TextStyle(
color: Colors.white,
fontWeight: FontWeight.normal,
fontSize: 11,
overflow: TextOverflow.ellipsis,
),
),
canvasColor: const Color(0xFF212121),
cardColor: Colors.white10,
cardTheme: const CardTheme(
color: Colors.white10,
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(15)),
),
margin: EdgeInsets.all(5),
),
inputDecorationTheme: const InputDecorationTheme(
filled: true,
fillColor: Colors.white10,
prefixIconColor: Colors.deepOrange,
labelStyle: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w500,
fontSize: 12,
overflow: TextOverflow.ellipsis,
),
hintStyle: TextStyle(
color: Colors.white,
fontWeight: FontWeight.normal,
fontSize: 12,
overflow: TextOverflow.ellipsis,
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.all(Radius.circular(10)),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.deepOrangeAccent),
borderRadius: BorderRadius.all(Radius.circular(10)),
),
),
appBarTheme: const AppBarTheme(
elevation: 0,
titleTextStyle: TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.w500,
overflow: TextOverflow.ellipsis,
),
centerTitle: true,
backgroundColor: Color(0xFF212121),
iconTheme: IconThemeData(color: Colors.deepOrange),
),
chipTheme: const ChipThemeData(
pressElevation: 0,
labelPadding: EdgeInsets.all(4),
checkmarkColor: Colors.white,
showCheckmark: true,
elevation: 0,
backgroundColor: Colors.white10,
disabledColor: Colors.grey,
selectedColor: Colors.deepOrange,
secondarySelectedColor: Colors.orange,
padding: EdgeInsets.all(8),
labelStyle: TextStyle(
color: Colors.white,
fontWeight: FontWeight.normal,
fontSize: 13,
overflow: TextOverflow.ellipsis,
),
secondaryLabelStyle: TextStyle(
color: Colors.white,
fontWeight: FontWeight.normal,
fontSize: 12,
overflow: TextOverflow.ellipsis,
),
brightness: Brightness.dark,
),
listTileTheme: const ListTileThemeData(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(15)),
),
iconColor: Colors.deepOrange,
textColor: Colors.black,
tileColor: Colors.white10,
selectedColor: Colors.deepOrangeAccent,
),
dialogTheme: const DialogTheme(
backgroundColor: Color(0xFF212121),
elevation: 20,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(15)),
),
),
outlinedButtonTheme: OutlinedButtonThemeData(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Colors.deepOrange),
side: MaterialStateProperty.all<BorderSide>(
const BorderSide(color: Colors.deepOrange, width: 2),
),
textStyle: MaterialStateProperty.all<TextStyle>(
const TextStyle(
fontWeight: FontWeight.normal,
fontSize: 13,
overflow: TextOverflow.ellipsis,
),
),
fixedSize: MaterialStateProperty.all<Size>(const Size(120, 45)),
elevation: MaterialStateProperty.all(0),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(15),
),
),
),
),
),
textButtonTheme: TextButtonThemeData(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Colors.deepOrange),
textStyle: MaterialStateProperty.all<TextStyle>(
const TextStyle(
fontWeight: FontWeight.normal,
fontSize: 13,
overflow: TextOverflow.ellipsis,
),
),
fixedSize: MaterialStateProperty.all<Size>(const Size(90, 45)),
elevation: MaterialStateProperty.all(0),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(15),
),
),
),
),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ButtonStyle(
textStyle: MaterialStateProperty.all<TextStyle>(
const TextStyle(
color: Colors.white,
fontWeight: FontWeight.normal,
fontSize: 13,
overflow: TextOverflow.ellipsis,
),
),
fixedSize: MaterialStateProperty.all<Size>(const Size(120, 45)),
backgroundColor: MaterialStateProperty.all<Color>(Colors.deepOrange),
elevation: MaterialStateProperty.all(0),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(15),
),
),
),
),
),
);
final ThemeData lightTheme = ThemeData(
useMaterial3: true,
hoverColor: Colors.grey.shade400,
primaryColor: Colors.deepOrange,
backgroundColor: Colors.grey.shade200,
colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.deepOrange)
.copyWith(secondary: Colors.white),
iconTheme: const IconThemeData(color: Colors.deepOrange),
highlightColor: Colors.deepOrangeAccent,
focusColor: Colors.deepOrangeAccent,
splashColor: Colors.deepOrangeAccent,
snackBarTheme: SnackBarThemeData(
backgroundColor: Colors.grey.shade200,
elevation: 0,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(15)),
),
),
textTheme: const TextTheme(
button: TextStyle(
color: Colors.white,
fontSize: 11,
fontWeight: FontWeight.normal,
overflow: TextOverflow.ellipsis,
),
headline1: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 17,
overflow: TextOverflow.ellipsis,
),
subtitle1: TextStyle(
color: Colors.black,
fontWeight: FontWeight.normal,
fontSize: 15,
overflow: TextOverflow.ellipsis,
),
headline2: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 12,
overflow: TextOverflow.ellipsis,
),
subtitle2: TextStyle(
color: Colors.black,
fontWeight: FontWeight.normal,
fontSize: 11,
overflow: TextOverflow.ellipsis,
),
),
canvasColor: const Color.fromRGBO(255, 255, 255, 1),
cardColor: Colors.grey.shade200,
cardTheme: CardTheme(
color: Colors.grey.shade200,
elevation: 0,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(15)),
),
margin: const EdgeInsets.all(5),
),
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: Colors.grey.shade200,
prefixIconColor: Colors.deepOrange,
labelStyle: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 12,
overflow: TextOverflow.ellipsis,
),
hintStyle: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.normal,
fontSize: 12,
overflow: TextOverflow.ellipsis,
),
enabledBorder: const OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.all(Radius.circular(10)),
),
focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.deepOrangeAccent),
borderRadius: BorderRadius.all(Radius.circular(10)),
),
),
appBarTheme: const AppBarTheme(
elevation: 0,
titleTextStyle: TextStyle(
color: Colors.black,
fontSize: 15,
fontWeight: FontWeight.w500,
overflow: TextOverflow.ellipsis,
),
centerTitle: true,
backgroundColor: Color.fromRGBO(255, 255, 255, 1),
iconTheme: IconThemeData(color: Colors.deepOrange),
),
chipTheme: ChipThemeData(
pressElevation: 0,
labelPadding: const EdgeInsets.all(4),
checkmarkColor: Colors.black,
showCheckmark: true,
elevation: 0,
backgroundColor: Colors.grey.withAlpha(45),
disabledColor: Colors.grey.shade100,
selectedColor: Colors.deepOrange,
secondarySelectedColor: Colors.orange,
padding: const EdgeInsets.all(8),
labelStyle: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.normal,
fontSize: 13,
overflow: TextOverflow.ellipsis,
),
secondaryLabelStyle: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.normal,
fontSize: 12,
overflow: TextOverflow.ellipsis,
),
brightness: Brightness.light,
),
listTileTheme: ListTileThemeData(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(15)),
),
iconColor: Colors.deepOrange,
textColor: Colors.black,
tileColor: Colors.grey.shade200,
selectedColor: Colors.deepOrangeAccent,
),
dialogTheme: const DialogTheme(
backgroundColor: Color.fromRGBO(255, 255, 255, 1),
elevation: 20,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(15)),
),
),
outlinedButtonTheme: OutlinedButtonThemeData(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Colors.deepOrange),
side: MaterialStateProperty.all<BorderSide>(
const BorderSide(color: Colors.deepOrange, width: 2),
),
textStyle: MaterialStateProperty.all<TextStyle>(
const TextStyle(
fontWeight: FontWeight.normal,
fontSize: 13,
overflow: TextOverflow.ellipsis,
),
),
fixedSize: MaterialStateProperty.all<Size>(const Size(120, 45)),
elevation: MaterialStateProperty.all(0),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(15),
),
),
),
),
),
textButtonTheme: TextButtonThemeData(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Colors.deepOrange),
textStyle: MaterialStateProperty.all<TextStyle>(
const TextStyle(
fontWeight: FontWeight.normal,
fontSize: 13,
overflow: TextOverflow.ellipsis,
),
),
fixedSize: MaterialStateProperty.all<Size>(const Size(90, 45)),
elevation: MaterialStateProperty.all(0),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(15),
),
),
),
),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ButtonStyle(
textStyle: MaterialStateProperty.all<TextStyle>(
const TextStyle(
color: Colors.white,
fontWeight: FontWeight.normal,
fontSize: 13,
overflow: TextOverflow.ellipsis,
),
),
fixedSize: MaterialStateProperty.all<Size>(const Size(120, 45)),
backgroundColor: MaterialStateProperty.all<Color>(Colors.deepOrange),
elevation: MaterialStateProperty.all(0),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(15),
),
),
),
),
),
);
| 0 |
mirrored_repositories/app_store/lib | mirrored_repositories/app_store/lib/generated/locale.dart | export './locale/data.dart';
export './locale/strings.dart';
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.