repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
mirrored_repositories/raffle-flutter/lib
|
mirrored_repositories/raffle-flutter/lib/screen/home.dart
|
import 'dart:async';
import 'package:raffle/screen/account.dart';
import 'package:raffle/screen/me.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:raffle/widget/ticket.dart';
import 'package:raffle/screen/winners.dart';
import 'package:raffle/screen/raffles.dart';
import 'package:raffle/constant/variable.dart';
import 'package:raffle/widget/notifications.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
HomeScreenState createState() => HomeScreenState();
}
class HomeScreenState extends State<HomeScreen> {
int _selectedIndex = 0;
@override
Widget build(BuildContext context) {
return Consumer<RaffleProvider>(builder: (context, provider, _) {
if (provider.user == null) {
return const Account();
} else {
return WillPopScope(
onWillPop: _onWillPop,
child: Scaffold(
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xFF188F52),
Color(0xFFFFFFFF),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
stops: [0.0, 1.0],
tileMode: TileMode.clamp,
),
),
child: SafeArea(
child: Column(
children: [
Expanded(
child: IndexedStack(
index: _selectedIndex,
children: const [
HomePage(),
RaffleScreen(),
WinnerList(),
AccountScreen(),
],
),
),
BottomNavigationBar(
unselectedItemColor: Colors.grey,
selectedItemColor: const Color(0xFF188F52),
currentIndex: _selectedIndex,
showUnselectedLabels: true,
onTap: (index) {
setState(() {
_selectedIndex = index;
});
},
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.filter_list),
label: 'Raffles',
),
BottomNavigationBarItem(
icon: Icon(Icons.emoji_events),
label: 'Winners',
),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle_outlined),
label: 'Me',
),
],
),
],
),
),
),
),
);
}
});
}
Future<bool> _onWillPop() async {
// This dialog will exit your app on saying yes
if (_selectedIndex != 0) {
// User is on a page other than the home page, so navigate to home page
setState(() {
_selectedIndex = 0;
});
return false;
} else {
return (await showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.black,
title: const Text('Are you sure?'),
content: const Text('Do you really wanna exit'),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('No'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Yes', style: TextStyle(color: Colors.red)),
),
],
),
)) ??
false;
}
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider.value(
value: Provider.of<RaffleProvider>(context),
child: Consumer<RaffleProvider>(
builder: (context, provider, _) {
if (provider.user == null) {
return const Account();
} else if (provider.raffle == null ||
provider.raffles.isEmpty ||
provider.userTickets == null ||
provider.notificationsList!.isEmpty) {
provider.fetchRaffle();
provider.fetchRaffles();
provider.getNotifications(
username: provider.user!.username,
password: provider.user!.password);
provider.getUserTickets(
username: provider.user!.username,
password: provider.user!.password);
return const Center(child: CircularProgressIndicator());
} else {
final raffle = provider.raffle!;
final raffles = provider.raffles;
final usertickets = provider.userTickets!;
final notifications = provider.notificationsList;
int notPaidCount = 0;
for (UserTickets ticket in usertickets) {
if (!ticket.paid) {
notPaidCount++;
}
}
return Padding(
padding: const EdgeInsets.all(10),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Stack(
children: [
IconButton(
icon: const Icon(Icons.notifications),
onPressed: () {
Navigator.pushNamed(
context,
'/notifications',
arguments: 'hot',
);
},
),
Positioned(
top: 0,
right: 0,
child: Container(
padding: const EdgeInsets.all(2),
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.red,
),
child: Text(
notifications!.length.toString(),
style: const TextStyle(
fontSize: 12,
color: Colors.white,
),
),
),
),
],
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Open Raffle'),
const SizedBox(height: 12),
Text(
raffles.length.toString(),
style: const TextStyle(fontSize: 10),
),
],
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('My Tickets'),
const SizedBox(height: 12),
Text(
usertickets.length.toString(),
style: const TextStyle(fontSize: 10),
),
],
),
Stack(
children: [
IconButton(
icon: const Icon(Icons.shopping_cart),
onPressed: () {
// Navigate to shopping cart screen
},
),
Positioned(
top: 0,
right: 0,
child: Container(
padding: const EdgeInsets.all(2),
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.red,
),
child: Text(
notPaidCount.toString(),
style: const TextStyle(
fontSize: 12,
color: Colors.white,
),
),
),
),
],
),
],
),
TicketWidget(
raffle: raffle,
show: true,
),
const NotificationStreameWidget(),
],
),
);
}
},
),
);
}
}
| 0
|
mirrored_repositories/raffle-flutter/lib
|
mirrored_repositories/raffle-flutter/lib/widget/notifications.dart
|
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:raffle/constant/variable.dart';
import 'package:raffle/main.dart';
class NotificationStreameWidget extends StatefulWidget {
const NotificationStreameWidget({Key? key}) : super(key: key);
@override
NotificationStreameWidgetState createState() =>
NotificationStreameWidgetState();
}
class NotificationStreameWidgetState extends State<NotificationStreameWidget> {
@override
Widget build(BuildContext context) {
return SizedBox(
height: MediaQuery.of(context).size.height / 4,
child: Consumer<RaffleProvider>(
builder: (context, provider, _) {
if (provider.notificationsList == null) {
provider.getNotifications();
return const Center(child: CircularProgressIndicator());
} else {
final notifications = provider.notificationsList;
return RefreshIndicator(
onRefresh: provider.getNotifications,
child: ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: notifications!.length,
itemBuilder: (context, index) {
final notification = notifications[index];
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 10),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
blurRadius: 10,
offset: const Offset(0, 5),
),
],
),
child: ListTile(
title: Text(
notification.createdAt.toString().substring(0, 19),
style: const TextStyle(
fontWeight: FontWeight.bold, color: Colors.black),
),
subtitle: Text(
notification.message.replaceFirst("You", "Someone"),
style: TextStyle(color: primaryColor.shade900),
),
trailing: const Icon(Icons.notifications),
onTap: () {
// Handle notification tap here
},
),
),
);
},
),
);
}
},
),
);
}
}
| 0
|
mirrored_repositories/raffle-flutter/lib
|
mirrored_repositories/raffle-flutter/lib/widget/ticket.dart
|
import 'package:flutter/material.dart';
import 'package:raffle/constant/variable.dart';
import 'package:raffle/page/raffle.dart';
import 'package:cached_network_image/cached_network_image.dart';
class TicketWidget extends StatelessWidget {
final Raffle raffle;
final bool show;
const TicketWidget({Key? key, required this.raffle, required this.show})
: super(key: key);
@override
Widget build(BuildContext context) {
return show
? InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RafflePage(
raffle: raffle,
),
),
);
},
child: ticket(context),
)
: ticket(context);
}
Widget ticket(context) {
return Container(
width: MediaQuery.of(context).size.width,
height: 300,
margin: const EdgeInsets.all(20),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.black.withOpacity(0.2),
width: 1,
),
borderRadius: BorderRadius.circular(20),
),
child: Stack(
alignment: Alignment.center,
children: [
Container(
width: 200,
height: 250,
alignment: Alignment.center,
decoration: BoxDecoration(
image: DecorationImage(
image: CachedNetworkImageProvider(raffle.image),
fit: BoxFit.contain,
),
borderRadius: BorderRadius.circular(20),
),
),
if (show)
Container(
padding: const EdgeInsets.fromLTRB(20, 20, 20, 5),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Container(
decoration: const BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.black,
blurRadius: 5,
offset: Offset(0, 2),
),
],
),
child: LinearProgressIndicator(
value: raffle.ticketsSold /
(raffle.ticketsAvailable + raffle.ticketsSold),
backgroundColor: Colors.white,
valueColor: const AlwaysStoppedAnimation<Color>(
Color.fromARGB(255, 0, 255, 8),
),
semanticsLabel:
"${(raffle.ticketsSold / raffle.ticketsAvailable) * 100}%",
),
),
],
),
),
],
),
);
}
}
| 0
|
mirrored_repositories/raffle-flutter/lib
|
mirrored_repositories/raffle-flutter/lib/constant/variable.dart
|
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
SystemUiOverlayStyle system = const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarBrightness: Brightness.light,
statusBarIconBrightness: Brightness.light,
systemNavigationBarColor: Colors.transparent,
systemNavigationBarIconBrightness: Brightness.light,
);
BoxDecoration background = const BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xFF188F52),
Color(0xFFFFFFFF),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
stops: [0.0, 1.0],
tileMode: TileMode.clamp,
),
);
Future<void> signout() async {}
class Notification {
final int id;
final String message;
final DateTime createdAt;
final int user;
Notification({
required this.id,
required this.message,
required this.createdAt,
required this.user,
});
factory Notification.fromJson(Map<String, dynamic> json) {
return Notification(
id: json['id'],
message: json['message'],
createdAt: DateTime.parse(json['created_at']),
user: json['user'],
);
}
}
class UserTickets {
final int id;
final Raffle raffle;
final String key;
final DateTime createdAt;
final bool paid;
final String reference;
UserTickets({
required this.id,
required this.raffle,
required this.key,
required this.createdAt,
required this.paid,
required this.reference,
});
factory UserTickets.fromJson(Map<String, dynamic> json) {
return UserTickets(
id: json['id'],
raffle: Raffle.fromJson(json['raffle']),
key: json['key'],
paid: json['paid'],
reference: json['paystack_reference'],
createdAt: DateTime.parse(json['created_at']),
);
}
}
class Raffle {
final int id;
final String name;
final String description;
final double ticketPrice;
final DateTime startDate;
final DateTime endDate;
final String image;
final int ticketsAvailable;
final int ticketsSold;
final DateTime createdAt;
int? winner;
Raffle({
required this.id,
required this.name,
required this.description,
required this.ticketPrice,
required this.startDate,
required this.endDate,
required this.image,
required this.ticketsAvailable,
required this.ticketsSold,
required this.createdAt,
this.winner,
});
factory Raffle.fromJson(Map<String, dynamic> json) {
return Raffle(
id: json['id'],
name: json['name'],
description: json['description'],
ticketPrice: json['ticket_price'].toDouble(),
startDate: DateTime.parse(json['start_date']),
endDate: DateTime.parse(json['end_date']),
image: json['image'],
ticketsAvailable: json['tickets_available'],
ticketsSold: json['tickets_sold'],
createdAt: DateTime.parse(json['created_at']),
winner: json['winner'] != null ? int.parse(json['winner']) : null,
);
}
}
class User {
final int id;
final String username;
final String email;
final String firstName;
final String lastName;
final String password;
User({
required this.id,
required this.username,
required this.email,
required this.firstName,
required this.lastName,
required this.password,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
username: json['username'],
password: json['password'],
email: json['email'],
firstName: json['first_name'],
lastName: json['last_name'],
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'username': username,
'password': password,
'email': email,
'first_name': firstName,
'last_name': lastName,
};
}
}
class RaffleProvider with ChangeNotifier {
User? _user;
Raffle? _raffle;
List<Raffle> _raffles = [];
List<UserTickets>? _userTickets;
List<Notification>? _userNotifications;
List<Notification>? _notificationsList;
User? get user => _user;
Raffle? get raffle => _raffle;
List<Raffle> get raffles => _raffles;
List<UserTickets>? get userTickets => _userTickets;
List<Notification>? get userNotifications => _userNotifications;
List<Notification>? get notificationsList => _notificationsList;
Future<void> fetchRaffles() async {
try {
final headers = {
'Authorization': 'Token 1e9b9be80157b3ef736e6ddf975e4ca72f66b25b',
};
final response = await http.get(
Uri.parse(
'http://127.0.0.1:8880/api/raffles/?format=json&_=${DateTime.now().millisecondsSinceEpoch}'),
headers: headers,
);
final data = jsonDecode(response.body) as List<dynamic>;
_raffles = data.map((item) => Raffle.fromJson(item)).toList();
} catch (e) {
//
}
notifyListeners();
}
Future<void> fetchRaffle() async {
try {
final headers = {
'Authorization': 'Token 1e9b9be80157b3ef736e6ddf975e4ca72f66b25b',
};
final response = await http.get(
Uri.parse(
'http://127.0.0.1:8880/api/raffles/hot/?format=json&_=${DateTime.now().millisecondsSinceEpoch}'),
headers: headers,
);
final data = jsonDecode(response.body);
_raffle = Raffle.fromJson(data);
notifyListeners();
} catch (e) {
//
}
notifyListeners();
}
Future<Object?> getUserProfile({String? username, String? password}) async {
try {
final currentUser = user;
String? usern = username ?? currentUser?.username;
String? paswd = password ?? currentUser?.password;
final response = await http.get(
Uri.parse('http://127.0.0.1:8880/api/user/profile/'),
headers: {
'Authorization': 'Basic ${base64Encode(utf8.encode('$usern:$paswd'))}'
},
);
final data = jsonDecode(response.body);
data['password'] = paswd;
_user = User.fromJson(data);
notifyListeners();
return _user;
} on HttpException {
return 'Failed to retrieve data from the server';
} on SocketException {
return 'Unable to Connect to the Internet';
} catch (e) {
return 'Invalid username or password';
}
}
Future<void> getUserTickets({String? username, String? password}) async {
try {
final currentUser = user;
String? usern = username ?? currentUser?.username;
String? paswd = password ?? currentUser?.password;
final response = await http.get(
Uri.parse('http://127.0.0.1:8880/api/user/profile/tickets/'),
headers: {
'Authorization': 'Basic ${base64Encode(utf8.encode('$usern:$paswd'))}'
},
);
final data = jsonDecode(response.body) as List<dynamic>;
_userTickets = data.map((item) => UserTickets.fromJson(item)).toList();
} catch (e) {
//
}
notifyListeners();
}
Future<void> getUserNotifications(
{String? username, String? password}) async {
try {
final currentUser = user;
String? usern = username ?? currentUser?.username;
String? paswd = password ?? currentUser?.password;
final response = await http.get(
Uri.parse('http://127.0.0.1:8880/api/user/notifications/'),
headers: {
'Authorization': 'Basic ${base64Encode(utf8.encode('$usern:$paswd'))}'
},
);
final data = jsonDecode(response.body) as List<dynamic>;
_userNotifications =
data.map((item) => Notification.fromJson(item)).toList();
} catch (e) {
//
}
notifyListeners();
}
Future<void> getNotifications({String? username, String? password}) async {
try {
final currentUser = user;
String? usern = username ?? currentUser?.username;
String? paswd = password ?? currentUser?.password;
final response = await http.get(
Uri.parse('http://127.0.0.1:8880/api/notifications/'),
headers: {
'Authorization': 'Basic ${base64Encode(utf8.encode('$usern:$paswd'))}'
},
);
final data = jsonDecode(response.body) as List<dynamic>;
_notificationsList =
data.map((item) => Notification.fromJson(item)).toList();
} catch (e) {
//
}
notifyListeners();
}
}
| 0
|
mirrored_repositories/raffle-flutter
|
mirrored_repositories/raffle-flutter/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:raffle/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0
|
mirrored_repositories/GmailClone-Flutter
|
mirrored_repositories/GmailClone-Flutter/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:gmail_clone/Screens/Home.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Gmail Clone',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
body: HomePage(),
floatingActionButton: Material(
elevation: 10,
borderRadius: BorderRadius.circular(25),
child: Container(
width: 160,
child: FlatButton(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Icon(MdiIcons.pencil, color: Color(0XFFFF0000),size: 17,),
Text('Compose', style: TextStyle(color: Color(0XFFFF0000), fontSize: 16, fontWeight: FontWeight.normal),),
],
),
)
),
),
);
}
}
| 0
|
mirrored_repositories/GmailClone-Flutter/lib
|
mirrored_repositories/GmailClone-Flutter/lib/Data/Mail.dart
|
import 'package:gmail_clone/Model/Mail.dart';
List<Mail> mailList = [
Mail(
username: "Tony",
useravatar:
"https://upload.wikimedia.org/wikipedia/en/thumb/3/3c/Chris_Hemsworth_as_Thor.jpg/220px-Chris_Hemsworth_as_Thor.jpg",
subject: "Job | Software Developer",
timeago: "Aug 26",
seen: true,
file: true,
filename: "Assignment",
body:
"https://images.unsplash.com/photo-1593642634524-b40b5baae6bb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2689&q=80",
starred: true ),
Mail(
username: "Anoty Start",
useravatar:
"https://i.pinimg.com/236x/2a/b8/a0/2ab8a008659b6ca9be7f43ef0c2791ca--loki-avengers-loki-marvel.jpg",
subject: "Freshworl",
timeago: "Aug 23",
seen: false,
file: false,
filename: "Screenshot_2020",
body:
"https://images.unsplash.com/photo-1593642634524-b40b5baae6bb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2689&q=80",
starred: false ),
Mail(
username: "Joan Louji",
useravatar:
"https://www.pinkvilla.com/files/styles/contentpreview/public/Tony%20Stark%20main.jpg?itok=dOOaowa0",
subject: "(no subject)",
timeago: "Aug 23",
seen: true,
file: true,
filename: "Screenshot_2020",
body: "no Body",
starred: false ),
Mail(
username: "Rion",
useravatar:null,
subject: "me, Mail",
timeago: "Aug 21",
seen: false,
file: false,
filename: "Screenshot_2020",
body:"Address not Found",
starred: true ),
Mail(
username: "Louji",
useravatar: null,
subject: "Twitter",
timeago: "Aug 20",
seen: true,
file: false,
filename: "Screenshot_2020",
body:
"Verification sent",
starred: false ),
Mail(
username: "Racheal",
useravatar:
"https://static.toiimg.com/thumb/msid-69065952,imgsize-90497,width-800,height-600,resizemode-75/69065952.jpg",
subject: "Hangout Chat",
timeago: "Aug 26",
seen: false,
file: false,
filename: "Screenshot_2020",
body:
"Chats Archieve",
starred: false ),
Mail(
username: "Isac",
useravatar: null,
subject: "Intern Chat",
timeago: "Aug 26",
seen: false,
file: false,
filename: "Screenshot_2020",
body:
"Chat with us. visit this mail",
starred: true ),
Mail(
username: "Johanna",
useravatar:
"https://i.insider.com/5cbe0ab30ff30d1fd1092726",
subject: "Status of your Job Application",
timeago: "Aug 26",
seen: false,
file: false,
filename: "Screenshot_2020",
body:
"We have updated your status of Job Applicationn",
starred: false ),
Mail(
username: "Freshers",
useravatar:
null,
subject: "me, Susmithani",
timeago: "Aug 26",
seen: true,
file: true,
filename: "Screenshot_2020",
body:
"Hi, I am sending this mail to make you know that you didn't",
starred: false ),
Mail(
username: "UGC",
useravatar:
"https://upload.wikimedia.org/wikipedia/en/thumb/3/3c/Chris_Hemsworth_as_Thor.jpg/220px-Chris_Hemsworth_as_Thor.jpg",
subject: "Plus",
timeago: "Aug 26",
seen: true,
file: true,
filename: "Screenshot_2020",
body:
"DB Config",
starred: false ),
Mail(
username: "Alka University",
useravatar:
"https://i.pinimg.com/236x/2a/b8/a0/2ab8a008659b6ca9be7f43ef0c2791ca--loki-avengers-loki-marvel.jpg",
subject: "Job | Software Developer",
timeago: "Aug 26",
seen: false,
file: false,
filename: "Screenshot_2020",
body:
"https://images.unsplash.com/photo-1593642634524-b40b5baae6bb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2689&q=80",
starred: false ),
Mail(
username: "Find me",
useravatar:
"https://www.pinkvilla.com/files/styles/contentpreview/public/Tony%20Stark%20main.jpg?itok=dOOaowa0",
subject: "Job | Software Developer Job | Software Developer Job | Software Developer Job | Software Developer Job | Software Developer",
timeago: "Aug 26",
seen: false,
file: true,
filename: "Screenshot_2020",
body:
"https://images.unsplash.com/photo-1593642634524-b40b5baae6bb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2689&q=80",
starred: false ),
Mail(
username: "hacker earth",
useravatar:null,
subject: "Job | Software Developer",
timeago: "Aug 26",
seen: false,
file: false,
filename: "Screenshot_2020",
body:
"https://images.unsplash.com/photo-1593642634524-b40b5baae6bb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2689&q=80",
starred: true ),
Mail(
username: "Tony Start",
useravatar: null,
subject: "Job | Software Developer",
timeago: "Aug 26",
seen: false,
file: false,
filename: "Screenshot_2020",
body:
"https://images.unsplash.com/photo-1593642634524-b40b5baae6bb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2689&q=80",
starred: false ),
Mail(
username: "Spidy",
useravatar:
"https://static.toiimg.com/thumb/msid-69065952,imgsize-90497,width-800,height-600,resizemode-75/69065952.jpg",
subject: "Job | Software Developer",
timeago: "Aug 26",
seen: false,
file: false,
filename: "Screenshot_2020",
body:
"https://images.unsplash.com/photo-1593642634524-b40b5baae6bb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2689&q=80",
starred: false ),
Mail(
username: "Rion Louji",
useravatar: null,
subject: "Job | Software Developer",
timeago: "Aug 26",
seen: false,
file: false,
filename: "Screenshot_2020",
body:
"https://images.unsplash.com/photo-1593642634524-b40b5baae6bb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2689&q=80",
starred: false ),
Mail(
username: "Joan Louji",
useravatar:
"https://i.insider.com/5cbe0ab30ff30d1fd1092726",
subject: "Job | Software Developer",
timeago: "Aug 26",
seen: false,
file: false,
filename: "Screenshot_2020",
body:
"https://images.unsplash.com/photo-1593642634524-b40b5baae6bb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2689&q=80",
starred: true ),
Mail(
username: "Anntony",
useravatar:
null,
subject: "Job | Software Developer Job | Software Developer Job | Software Developer Job | Software Developer Job | Software Developer",
timeago: "Aug 26",
seen: true,
file: true,
filename: "Screenshot_2020",
body:
"https://images.unsplash.com/photo-1593642634524-b40b5baae6bb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2689&q=80",
starred: false ),
];
| 0
|
mirrored_repositories/GmailClone-Flutter/lib
|
mirrored_repositories/GmailClone-Flutter/lib/Screens/Home.dart
|
import 'package:flutter/material.dart';
import 'package:gmail_clone/Data/Mail.dart';
import 'package:gmail_clone/Widget/Primary.dart';
void main() {
runApp(HomePage());
}
class HomePage extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Gmail Clone',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: new SafeArea(
child: NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
PreferredSize(
preferredSize: Size.fromHeight(70.0),
child: SliverAppBar(
toolbarHeight: 80,
pinned: false,
backgroundColor: Colors.white,
title: Container(
child: Material(
elevation: 8,
borderRadius: BorderRadius.all(Radius.circular(10)),
child: Container(
height: 50,
child: TextFormField(
decoration: InputDecoration(
hintText: "Search in Mail",
border: InputBorder.none,
icon: Container(
margin: EdgeInsets.only(left: 10),
child: Icon(Icons.dehaze)
),
suffixIcon: Container(
height: 5,
width: 5,
margin: EdgeInsets.all(5),
child: CircleAvatar(
radius: 14.0,
backgroundColor: Colors.white,
child: CircleAvatar(
radius: 14.0,
backgroundColor: Colors.grey[200],
backgroundImage: NetworkImage("https://qph.fs.quoracdn.net/main-qimg-11ef692748351829b4629683eff21100.webp"),
),
),
)
),
),
),
),
),
),
)
];
},
body: SingleChildScrollView(
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: EdgeInsets.only(left: 20,),
child: Text('Primary'),
),
Container(
child: ListView.builder(
padding: EdgeInsets.all(0),
physics: NeverScrollableScrollPhysics(),
itemCount: mailList.length,
shrinkWrap: true,
itemBuilder: (context, index){
return Container(
child: PrimaryWidget(mail: mailList[index],),
);
}
),
),
],
),
),
)
),
)
);
}
}
| 0
|
mirrored_repositories/GmailClone-Flutter/lib
|
mirrored_repositories/GmailClone-Flutter/lib/Widget/Primary.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gmail_clone/Model/Mail.dart';
import 'package:gmail_clone/Screens/Home.dart';
void main() {
runApp(PrimaryWidget());
}
class PrimaryWidget extends StatelessWidget {
// This widget is the root of your application.
PrimaryWidget({Key key, this.mail}) : super(key: key);
Mail mail;
@override
Widget build(BuildContext context) {
return PrimaryWidgetPage(mail: mail,);
}
}
class PrimaryWidgetPage extends StatefulWidget {
PrimaryWidgetPage({Key key, this.title, this.mail}) : super(key: key);
final String title;
Mail mail;
@override
_PrimaryWidgetState createState() => _PrimaryWidgetState();
}
class _PrimaryWidgetState extends State<PrimaryWidgetPage> {
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Container(
padding: EdgeInsets.only(left: 10,right: 10, top: 15),
child: Row(
children: <Widget>[
widget.mail.useravatar!=null?
Container(
padding: EdgeInsets.symmetric(horizontal: 8.0),
child: CircleAvatar(
radius: 25.0,
backgroundImage: NetworkImage(widget.mail.useravatar),
),
)
:
Container(
padding: EdgeInsets.symmetric(horizontal: 8.0),
child: CircleAvatar(
backgroundColor: colorDecider(widget.mail.username[0]),
radius: 25.0,
child: Text(widget.mail.username[0], style: TextStyle(fontSize: 27, color: Colors.white,),),
),
),
Expanded(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
child: Text(
widget.mail.username!=null?widget.mail.username:"Unknow user",
style: Theme.of(context).textTheme.display1.copyWith(
fontSize: 16.0,
color: Colors.grey[800],
fontWeight: widget.mail.seen?FontWeight.normal:FontWeight.bold
),
),
),
Container(
child: Text(
widget.mail.subject,
maxLines: 1,
style: Theme.of(context).textTheme.body1.copyWith(
fontSize: 14.0,
fontWeight: widget.mail.seen?FontWeight.normal:FontWeight.bold,
color: widget.mail.seen?Colors.grey:Colors.grey[800],
),
),
),
Container(
child: Text(
widget.mail.body,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.body1.copyWith(
fontSize: 14.0,
color: Colors.grey,
),
),
),
widget.mail.file?
Container(
width: 150,
height: 30,
margin: EdgeInsets.only(top: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
shape: BoxShape.rectangle,
border: Border.all(color: Colors.grey[300])
),
child: Container(
padding: EdgeInsets.all(5),
child: Row(
children: <Widget>[
Icon(Icons.image, size: 16,color: Color(0XFFFF0000),),
SizedBox(width: 10,),
Text(widget.mail.filename, maxLines: 1, style: TextStyle(color: Colors.grey[700]), overflow: TextOverflow.ellipsis,)
],
),
),
)
:
SizedBox.shrink()
],
),
),
),
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Text(widget.mail.timeago,style: TextStyle( fontWeight: widget.mail.seen?FontWeight.normal:FontWeight.bold),),
IconButton(
icon: widget.mail.starred?Icon(Icons.star, color: Colors.amber):Icon(Icons.star_border)
),
],
),
],
),
)
],
);
}
}
colorDecider(String name){
if(name == "R"){
return Colors.yellow;
}else if(name == "L"){
return Colors.redAccent;
}else if(name == "I"){
return Colors.orangeAccent;
}else if(name == "F"){
return Colors.greenAccent;
}else {
return Colors.blueAccent;
}
}
| 0
|
mirrored_repositories/GmailClone-Flutter/lib
|
mirrored_repositories/GmailClone-Flutter/lib/Model/Mail.dart
|
class Mail {
final String useravatar;
final String username;
final String subject;
final String body;
final bool starred;
final String timeago;
final bool seen;
final bool file;
final String filename;
Mail({
this.useravatar,
this.username,
this.subject,
this.body,
this.starred,
this.timeago,
this.seen,
this.file,
this.filename
});
}
| 0
|
mirrored_repositories/GmailClone-Flutter
|
mirrored_repositories/GmailClone-Flutter/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:gmail_clone/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/jogo_da_forca
|
mirrored_repositories/jogo_da_forca/lib/main.dart
|
import 'package:flutter/material.dart';
import 'src/appwidget.dart';
void main() => runApp(const MyApp());
| 0
|
mirrored_repositories/jogo_da_forca/lib
|
mirrored_repositories/jogo_da_forca/lib/src/appwidget.dart
|
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'features/game/store/game_store.dart';
//screens
import 'features/game/game.dart';
import 'features/home/home_page.dart';
//routes
import 'shared/utils/app_routes.dart';
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
Provider<GameStore>(
create: (_) => GameStore(),
),
],
child: MaterialApp(
title: 'Home Page',
debugShowCheckedModeBanner: false,
theme: ThemeData(
fontFamily: '',
), //theme
routes: {
AppRoutes.HOME: (ctx) => HomePage(),
AppRoutes.GAME: (ctx) => const GamePage(),
}),
);
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/shared
|
mirrored_repositories/jogo_da_forca/lib/src/shared/models/ad_helper.dart
|
import 'dart:io';
class AdHelper {
static String get bannerAdUnitId {
if (Platform.isAndroid) {
return 'ca-app-pub-6218817239680955/5038604498';
} /*else if (Platform.isIOS) {
return '<YOUR_IOS_BANNER_AD_UNIT_ID>';
} */ else {
throw UnsupportedError('Unsupported platform');
}
}
static String get interstitialAdUnitId {
if (Platform.isAndroid) {
return 'ca-app-pub-6218817239680955/5038604498';
} /*else if (Platform.isIOS) {
return '<YOUR_IOS_INTERSTITIAL_AD_UNIT_ID>';
} else*/ {
throw UnsupportedError('Unsupported platform');
}
}
static String get rewardedAdUnitId {
if (Platform.isAndroid) {
return 'ca-app-pub-6218817239680955/5038604498';
} /*else if (Platform.isIOS) {
// return '<YOUR_IOS_INTERSTITIAL_AD_UNIT_ID>';
}*/ else {
throw UnsupportedError('Unsupported platform');
}
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/shared
|
mirrored_repositories/jogo_da_forca/lib/src/shared/utils/textstyle.dart
|
import 'package:flutter/material.dart';
TextStyle kButtonPrincipal = const TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.w500,
fontSize: 22.0,
color: Color(0xFFFFFFFF),
);
TextStyle kButtonSecondary = const TextStyle(
fontFamily: 'Montserrat',
fontSize: 22.0,
color: Colors.black,
);
TextStyle kHeadline1 = const TextStyle(
fontSize: 30.0,
fontFamily: 'Montserrat',
color: Colors.black,
fontWeight: FontWeight.normal,
);
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/shared
|
mirrored_repositories/jogo_da_forca/lib/src/shared/utils/app_routes.dart
|
class AppRoutes {
static const HOME = '/';
static const GAME = '/game';
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/shared
|
mirrored_repositories/jogo_da_forca/lib/src/shared/utils/constants.dart
|
const List<String> alfabeto = [
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'x',
'w',
'y',
'z'
];
const List<String> wordData = [
'bicicleta',
'sino',
'passeio',
'escritor',
'bolo',
'balão',
'pé',
'chuveiro',
'vilão',
'porco',
'inglês',
'coração'
];
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/features
|
mirrored_repositories/jogo_da_forca/lib/src/features/game/game_controller.dart
|
import 'dart:math';
//utils
import 'package:flutter/foundation.dart';
import '../../shared/utils/constants.dart';
abstract class IGameController {
void novaPalavra() {}
iniciarJogo() {}
testarEntrada(String letra) {}
replaceTiras ({required String letra}) {}
gameIsWinner() {}
lostLife({required int vida}) {}
}
class GameController extends IGameController{
List<String> banco = wordData; //palavra do banco do dados
Random random = Random();
late String palavraSorteada;
late String _tiras;
int _vidas = 0;
List<String> _g = [];
List<dynamic> tro = [];
List<String> o = ['__ '];
final List<String> entries = alfabeto;
@override
String iniciarJogo() {
palavraSorteada = banco[random.nextInt(banco.length - 1)];
_tiras = novaPalavra();
_vidas = 5;
_g.clear();
return _tiras;
}
@override
bool testarEntrada(String letra) {
bool n = _g.contains(letra);
debugPrint('print n ${n.toString()}');
bool resultado = false;
if (n == false) {
// se g não tiver letra que o usuario digitou
for (int k = 0; k < palavraSorteada.length; k++) {
if (letra == palavraSorteada[k]) {
_g.add(letra);
debugPrint(_g.toString());
resultado = true;
} else if (letra.replaceAll('a', 'ã') == palavraSorteada[k]) {
_g.add(letra.replaceAll('a', 'ã'));
debugPrint(_g.toString());
resultado = true;
} else if (letra.replaceAll('e', 'ê') == palavraSorteada[k]) {
_g.add(letra.replaceAll('e', 'ê'));
debugPrint(_g.toString());
resultado = true;
} else if (letra.replaceAll('e', 'é') == palavraSorteada[k]) {
_g.add(letra.replaceAll('e', 'é'));
debugPrint(_g.toString());
resultado = true;
} else if (letra.replaceAll('c', 'ç') == palavraSorteada[k]) {
_g.add(letra.replaceAll('c', 'ç'));
debugPrint(_g.toString());
resultado = true;
}
debugPrint(_g.toString());
//resultado = false;
} //for
}
return resultado;
}
@override
String replaceTiras({required String letra}) {
if (_g.isNotEmpty) {
for (int x = 0; x < palavraSorteada.length; x++) {
for (int m = 0; m < _g.length; m++) {
if (_g[m] == palavraSorteada[x]) {
tro[x] = tro[x].replaceAll(tro[x], palavraSorteada[x]);
} // if
} //for 2
} //for 1
}
_tiras = tro.join('');
return _tiras;
} // _testando
@override
int lostLife({required int vida}) {
_vidas--;
return _vidas;
}
@override
bool gameIsWinner() {
if (_g.length == palavraSorteada.length) {
return true;
} else {
return false;
}
}
@override
String novaPalavra() {
for (int l = 0; l < palavraSorteada.length; l++) {
tro += o;
}
String a = tro.join();
return a;
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/features
|
mirrored_repositories/jogo_da_forca/lib/src/features/game/game.dart
|
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
//store
import 'store/game_store.dart';
//components
import 'components/teclas.dart';
import 'components/hearts.dart';
import 'components/texto.dart';
//utils
class GamePage extends StatefulWidget {
const GamePage({Key? key}) : super(key: key);
@override
_GamePageState createState() => _GamePageState();
}
class _GamePageState extends State<GamePage> {
late GameStore gameStore;
@override
void initState() {
gameStore = context.read<GameStore>();
gameStore.startGame();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFF8F9FD),
appBar: AppBar(
backgroundColor: const Color(0xFFF8F9FD),
elevation: 0,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
const Hearts(),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: const <Widget>[
Texto(),
],
),
const Teclas(),
],
),
);
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/features/game
|
mirrored_repositories/jogo_da_forca/lib/src/features/game/components/game_over_popup.dart
|
import 'package:flutter/material.dart';
import 'popup_model.dart';
class GameOver extends StatelessWidget {
final String word;
const GameOver({Key? key, required this.word}) : super(key: key);
@override
Widget build(BuildContext context) {
return PopUpModel(
frase: 'Game Over',
word: 'A palavra era $word',
color: const Color(0xffd24977),
);
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/features/game
|
mirrored_repositories/jogo_da_forca/lib/src/features/game/components/button.dart
|
import 'package:flutter/material.dart';
//utils
import '../../../shared/utils/textstyle.dart';
class Button extends StatelessWidget {
final String letra;
final bool isPressed;
final void Function()? onPressed;
const Button({Key? key, required this.letra, required this.isPressed, required this.onPressed,}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(vertical: 3.0, horizontal: 3.0),
child: SizedBox(
height: 40,
width: 40,
child: TextButton(
child: Text(
letra,
style: kButtonSecondary,
),
style: TextButton.styleFrom(
backgroundColor: Colors.white,
elevation: isPressed //false
? 0 //if true
: 4, //if false
shadowColor: const Color(0xFFEDEEF1),
padding: const EdgeInsets.all(2.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(3),
),
),
onPressed: onPressed,
),
),
);
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/features/game
|
mirrored_repositories/jogo_da_forca/lib/src/features/game/components/popup_model.dart
|
import 'package:flutter/material.dart';
//utils
import '../../../shared/utils/app_routes.dart';
class PopUpModel extends StatelessWidget {
final String frase;
final String word;
final Color color;
const PopUpModel({
Key? key,
required this.frase,
required this.word,
required this.color,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(
frase,
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 22.0,
color: color,
),
),
content: Text(
word,
style: const TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.w500,
fontSize: 20.0,
color: Colors.black87,
),
),
actions: <Widget>[
TextButton(
style: TextButton.styleFrom(
backgroundColor: color,
shape: const CircleBorder(),
),
child: const Text(
'x',
style: TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.w500,
fontSize: 20.0,
color: Color(0XFFFFFFFF),
),
),
onPressed: () {
Navigator.pushReplacementNamed(context, AppRoutes.HOME);
},
),
],
);
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/features/game
|
mirrored_repositories/jogo_da_forca/lib/src/features/game/components/teclas.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:provider/provider.dart';
//components
import 'button.dart';
//store
import '../store/game_store.dart';
//utils
import '../../../shared/utils/constants.dart';
class Teclas extends StatelessWidget {
const Teclas({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final gameStore = Provider.of<GameStore>(context);
return Observer(
builder: (_) => ConstrainedBox(
constraints: const BoxConstraints(
maxWidth: 800,
),
child: Container(
width: MediaQuery.of(context).size.width,
margin: const EdgeInsets.only(left: 15.0, right: 15, bottom: 15.0),
child: Wrap(
spacing: 0.0,
runSpacing: 0.0,
alignment: WrapAlignment.center,
children: <Widget>[
Button(
letra: alfabeto[0],
isPressed: gameStore.status[0],
onPressed: () => gameStore.adcionarEntrada(
alfabeto[0],
0,
),
),
Button(
letra: alfabeto[1],
isPressed: gameStore.status[1],
onPressed: () => gameStore.adcionarEntrada(alfabeto[1], 1),
),
Button(
letra: alfabeto[2],
isPressed: gameStore.status[2],
onPressed: () => gameStore.adcionarEntrada(alfabeto[2], 2),
),
Button(
letra: alfabeto[3],
isPressed: gameStore.status[3],
onPressed: () => gameStore.adcionarEntrada(alfabeto[3], 3)),
Button(
letra: alfabeto[4],
isPressed: gameStore.status[4],
onPressed: () => gameStore.adcionarEntrada(alfabeto[4], 4),
),
Button(
letra: alfabeto[5],
isPressed: gameStore.status[5],
onPressed: () => gameStore.adcionarEntrada(alfabeto[5], 5),
),
Button(
letra: alfabeto[6],
isPressed: gameStore.status[6],
onPressed: () => gameStore.adcionarEntrada(alfabeto[6], 6),
),
Button(
letra: alfabeto[7],
isPressed: gameStore.status[7],
onPressed: () => gameStore.adcionarEntrada(alfabeto[7], 7),
),
Button(
letra: alfabeto[8],
isPressed: gameStore.status[8],
onPressed: () => gameStore.adcionarEntrada(alfabeto[8], 8),
),
Button(
letra: alfabeto[9],
isPressed: gameStore.status[9],
onPressed: () => gameStore.adcionarEntrada(alfabeto[9], 8),
),
Button(
letra: alfabeto[10],
isPressed: gameStore.status[10],
onPressed: () => gameStore.adcionarEntrada(alfabeto[10], 10),
),
Button(
letra: alfabeto[11],
isPressed: gameStore.status[11],
onPressed: () => gameStore.adcionarEntrada(alfabeto[11], 11),
),
Button(
letra: alfabeto[12],
isPressed: gameStore.status[12],
onPressed: () => gameStore.adcionarEntrada(alfabeto[12], 12),
),
Button(
letra: alfabeto[13],
isPressed: gameStore.status[13],
onPressed: () => gameStore.adcionarEntrada(alfabeto[13], 13),
),
Button(
letra: alfabeto[14],
isPressed: gameStore.status[14],
onPressed: () => gameStore.adcionarEntrada(alfabeto[14], 14),
),
Button(
letra: alfabeto[15],
isPressed: gameStore.status[15],
onPressed: () => gameStore.adcionarEntrada(alfabeto[15], 15),
),
Button(
letra: alfabeto[16],
isPressed: gameStore.status[16],
onPressed: () => gameStore.adcionarEntrada(alfabeto[16], 16),
),
Button(
letra: alfabeto[17],
isPressed: gameStore.status[17],
onPressed: () => gameStore.adcionarEntrada(alfabeto[17], 17),
),
Button(
letra: alfabeto[18],
isPressed: gameStore.status[18],
onPressed: () => gameStore.adcionarEntrada(alfabeto[18], 18),
),
Button(
letra: alfabeto[19],
isPressed: gameStore.status[19],
onPressed: () => gameStore.adcionarEntrada(alfabeto[19], 19),
),
Button(
letra: alfabeto[20],
isPressed: gameStore.status[20],
onPressed: () => gameStore.adcionarEntrada(alfabeto[20], 20),
),
Button(
letra: alfabeto[21],
isPressed: gameStore.status[21],
onPressed: () => gameStore.adcionarEntrada(alfabeto[21], 21),
),
Button(
letra: alfabeto[22],
isPressed: gameStore.status[22],
onPressed: () => gameStore.adcionarEntrada(alfabeto[22], 22),
),
Button(
letra: alfabeto[23],
isPressed: gameStore.status[23],
onPressed: () => gameStore.adcionarEntrada(alfabeto[23], 23),
),
Button(
letra: alfabeto[24],
isPressed: gameStore.status[24],
onPressed: () => gameStore.adcionarEntrada(alfabeto[24], 24),
),
Button(
letra: alfabeto[25],
isPressed: gameStore.status[25],
onPressed: () => gameStore.adcionarEntrada(alfabeto[25], 25),
),
], //Children
), // Wrap
),
), // Child
);
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/features/game
|
mirrored_repositories/jogo_da_forca/lib/src/features/game/components/hearts.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:jogo_da_forca/src/features/game/components/popup_model.dart';
import 'package:provider/provider.dart';
//components
import 'page_winner_popup.dart';
//controller
import '../game_controller.dart';
//utils
import 'package:jogo_da_forca/src/features/game/store/game_store.dart';
import 'game_over_popup.dart';
class Hearts extends StatelessWidget {
const Hearts({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final gameStore = Provider.of<GameStore>(context);
return Observer(
builder: (_) => Column(
children: <Widget>[
if (gameStore.life == 0) GameOver(word: gameStore.palavraSorteada),
if (gameStore.winner) const GameWinner(),
Container(
margin: const EdgeInsets.only(top: 20),
alignment: Alignment.center,
width: double.infinity,
height: 50,
child: Image.asset(
'imagens/lifes_${gameStore.life}.png',
fit: BoxFit.cover,
gaplessPlayback: true, //new line
),
),
],
),
);
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/features/game
|
mirrored_repositories/jogo_da_forca/lib/src/features/game/components/page_winner_popup.dart
|
import 'package:flutter/material.dart';
import 'popup_model.dart';
class GameWinner extends StatelessWidget {
const GameWinner({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const PopUpModel(
frase: 'Parabéns, ',
word: 'Você acertou a palavra',
color: Color(0xff49d2a4),
);
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/features/game
|
mirrored_repositories/jogo_da_forca/lib/src/features/game/components/texto.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:jogo_da_forca/src/features/game/store/game_store.dart';
import 'package:provider/provider.dart';
//utils
import '../../../shared/utils/textstyle.dart';
class Texto extends StatefulWidget {
const Texto({
Key? key,
}) : super(key: key);
@override
State<Texto> createState() => _TextoState();
}
class _TextoState extends State<Texto> {
@override
Widget build(BuildContext context) {
final gameStore = Provider.of<GameStore>(context);
return Observer(
builder: (_) => Expanded(
flex: 2,
child: Container(
padding: const EdgeInsets.all(20.0),
alignment: Alignment.center,
child: Center(
child: Text(
gameStore.tiras,
style: kHeadline1,
overflow: TextOverflow.visible,
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/features/game
|
mirrored_repositories/jogo_da_forca/lib/src/features/game/store/game_store.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'game_store.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, no_leading_underscores_for_local_identifiers
mixin _$GameStore on _GameStore, Store {
late final _$palavraSorteadaAtom =
Atom(name: '_GameStore.palavraSorteada', context: context);
@override
String get palavraSorteada {
_$palavraSorteadaAtom.reportRead();
return super.palavraSorteada;
}
@override
set palavraSorteada(String value) {
_$palavraSorteadaAtom.reportWrite(value, super.palavraSorteada, () {
super.palavraSorteada = value;
});
}
late final _$tirasAtom = Atom(name: '_GameStore.tiras', context: context);
@override
String get tiras {
_$tirasAtom.reportRead();
return super.tiras;
}
@override
set tiras(String value) {
_$tirasAtom.reportWrite(value, super.tiras, () {
super.tiras = value;
});
}
late final _$statusAtom = Atom(name: '_GameStore.status', context: context);
@override
ObservableList<bool> get status {
_$statusAtom.reportRead();
return super.status;
}
@override
set status(ObservableList<bool> value) {
_$statusAtom.reportWrite(value, super.status, () {
super.status = value;
});
}
late final _$lifeAtom = Atom(name: '_GameStore.life', context: context);
@override
int get life {
_$lifeAtom.reportRead();
return super.life;
}
@override
set life(int value) {
_$lifeAtom.reportWrite(value, super.life, () {
super.life = value;
});
}
late final _$winnerAtom = Atom(name: '_GameStore.winner', context: context);
@override
bool get winner {
_$winnerAtom.reportRead();
return super.winner;
}
@override
set winner(bool value) {
_$winnerAtom.reportWrite(value, super.winner, () {
super.winner = value;
});
}
late final _$_GameStoreActionController =
ActionController(name: '_GameStore', context: context);
@override
void startGame() {
final _$actionInfo =
_$_GameStoreActionController.startAction(name: '_GameStore.startGame');
try {
return super.startGame();
} finally {
_$_GameStoreActionController.endAction(_$actionInfo);
}
}
@override
void adcionarEntrada(String letra, int index) {
final _$actionInfo = _$_GameStoreActionController.startAction(
name: '_GameStore.adcionarEntrada');
try {
return super.adcionarEntrada(letra, index);
} finally {
_$_GameStoreActionController.endAction(_$actionInfo);
}
}
@override
String toString() {
return '''
palavraSorteada: ${palavraSorteada},
tiras: ${tiras},
status: ${status},
life: ${life},
winner: ${winner}
''';
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/features/game
|
mirrored_repositories/jogo_da_forca/lib/src/features/game/store/game_store.dart
|
import 'dart:developer';
import '../game_controller.dart';
import 'package:mobx/mobx.dart';
part 'game_store.g.dart';
class GameStore = _GameStore with _$GameStore;
// The store-class
abstract class _GameStore with Store {
GameController gameController = GameController();
@observable
String palavraSorteada = '';
@observable
String tiras = '';
@observable
ObservableList<bool> status = ObservableList<bool>();
@observable
int life = 0;
@observable
bool winner = false;
@action
void startGame() {
status.clear();
status.addAll([
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
]);
tiras = '';
gameController = GameController();
tiras = gameController.iniciarJogo();
life = 5;
log('Start Game');
palavraSorteada = gameController.palavraSorteada;
winner = false;
}
@action
void adcionarEntrada(String letra, int index) {
status[index] = !status[index];
final entradaValida = gameController.testarEntrada(letra);
if (entradaValida) {
tiras = gameController.replaceTiras(letra: letra);
winner = gameController.gameIsWinner();
} else {
life = gameController.lostLife(vida: life);
log(life.toString());
}
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/features
|
mirrored_repositories/jogo_da_forca/lib/src/features/home/home_page.dart
|
import 'package:flutter/material.dart';
//routes
//ads Mobile
import 'package:google_mobile_ads/google_mobile_ads.dart';
import '../../shared/models/ad_helper.dart';
import '../../shared/utils/app_routes.dart';
//components
import 'components/button.dart';
import 'components/imagem.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late BannerAd _bannerAd;
bool _isBannerAdReady = false;
InterstitialAd? _interstitialAd;
bool _isInterstitialAdReady = false;
RewardedAd? _rewardedAd;
bool _isRewardedAdReady = false;
@override
void initState() {
super.initState();
_bannerAd = BannerAd(
adUnitId: AdHelper.bannerAdUnitId,
request: const AdRequest(),
size: AdSize.banner,
listener: BannerAdListener(
onAdLoaded: (_) {
setState(() {
_isBannerAdReady = true;
});
},
onAdFailedToLoad: (ad, err) {
print('Failed to load a banner ad: ${err.message}');
_isBannerAdReady = false;
ad.dispose();
},
),
);
_bannerAd.load();
}
@override
void dispose() {
// COMPLETE: Dispose a BannerAd object
_bannerAd.dispose();
// COMPLETE: Dispose an InterstitialAd object
_interstitialAd?.dispose();
// COMPLETE: Dispose a RewardedAd object
_rewardedAd?.dispose();
//QuizManager.instance.listener = null;
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFF8F9FD),
body: FutureBuilder<void>(
//future: _initGoogleMobileAds(),
builder: (context, snapshot) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Center(child: Imagem()),
Center(
child: CustomButton(onPressed: () {
Navigator.pushNamed(
//adciona essa tela a pilha de navegação
context,
AppRoutes.GAME,
);
}),
),
if (_isBannerAdReady)
Align(
alignment: Alignment.topCenter,
child: SizedBox(
width: _bannerAd.size.width.toDouble(),
height: _bannerAd.size.height.toDouble(),
child: AdWidget(ad: _bannerAd),
),
),
],
);
}),
);
}
// COMPLETE: Change return type to Future<InitializationStatus>
Future<InitializationStatus> _initGoogleMobileAds() {
// TODO: Initialize Google Mobile Ads SDK
return MobileAds.instance.initialize();
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/features/home
|
mirrored_repositories/jogo_da_forca/lib/src/features/home/components/imagem.dart
|
import 'package:flutter/material.dart';
class Imagem extends StatelessWidget {
const Imagem({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 50),
child: Image.asset(
'imagens/imagem_inicial.png',
height: 250,
width: MediaQuery.of(context).size.width * .7,
),
);
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib/src/features/home
|
mirrored_repositories/jogo_da_forca/lib/src/features/home/components/button.dart
|
import 'package:flutter/material.dart';
import 'package:jogo_da_forca/src/shared/utils/textstyle.dart';
//utils
import '../../../shared/utils/textstyle.dart';
class CustomButton extends StatelessWidget {
final void Function()? onPressed;
const CustomButton({
Key? key,
required this.onPressed,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width * .7,
height: 55,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
gradient: const LinearGradient(
colors: [
Color.fromRGBO(124, 181, 248, 1),
Color.fromRGBO(148, 135, 253, 1),
],
),
),
child: TextButton(
child: Text(
'Jogar',
style: kButtonPrincipal,
),
onPressed: onPressed,
),
);
}
}
| 0
|
mirrored_repositories/jogo_da_forca/lib
|
mirrored_repositories/jogo_da_forca/lib/controller/funcoes.dart
|
bool dentro(var contem, var contido) {
//verifica se a palavra tem a letra
contem = contem.toString();
contido = contido.toString();
for (int of = 0; of < contem.length; of++) {
for (int o = 0; o < contido.length; o++) {
if (contido[o] == contem[of]) {
return true;
} //if
} // for2
} // for 1
return false;
} //dentro
| 0
|
mirrored_repositories/SqFLite-Sample-Flutter-Project/sqflite_sample
|
mirrored_repositories/SqFLite-Sample-Flutter-Project/sqflite_sample/lib/sqflite_islemleri.dart
|
import 'package:flutter/material.dart';
import 'package:sqflite_sample/models/ogrenci.dart';
import 'package:sqflite_sample/utils/database_helper.dart';
class SqfliteIslemleri extends StatefulWidget {
@override
_SqfliteIslemleriState createState() => _SqfliteIslemleriState();
}
class _SqfliteIslemleriState extends State<SqfliteIslemleri> {
DatabaseHelper _databaseHelper;
List<Ogrenci> tumOgrencilerListesi;
var _formKey = GlobalKey<FormState>();
bool aktiflik = false;
var _controller = TextEditingController();
var _scaffoldKey = GlobalKey<ScaffoldState>();
int tiklanilanOgrenciIndeksi;
int tiklanilanOgrenciIDsi;
@override
void initState() {
// TODO: implement initState
super.initState();
tumOgrencilerListesi = List<Ogrenci>();
_databaseHelper = DatabaseHelper();
_databaseHelper.tumOgrenciler().then((tumOgrencileriTutanMapListesi) {
for (Map okunanOgrenciMapi in tumOgrencileriTutanMapListesi) {
tumOgrencilerListesi
.add(Ogrenci.dbdenOkudugunMapiObjeyeDonustur(okunanOgrenciMapi));
}
print("Ogrenci Sayisi : " + tumOgrencilerListesi.length.toString());
}).catchError((hata) => print('Hata Yapildi'));
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text("Sqflite Kullanımı"),
centerTitle: true,
),
body: Container(
child: Column(
children: [
Form(
key: _formKey,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
autofocus: false,
controller: _controller,
validator: (kontrolEdilecekIsimDegeri) {
if (kontrolEdilecekIsimDegeri.length < 3) {
return "En az 3 karakter olmali";
} else
return null;
},
decoration: InputDecoration(
labelText: "Ogrenci ismini giriniz : ",
border: OutlineInputBorder(),
),
),
),
SwitchListTile(
title: Text("Aktif"),
value: aktiflik,
onChanged: (aktifMi) {
setState(() {
aktiflik = aktifMi;
});
},
),
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
RaisedButton(
child: Text("Kaydet"),
color: Colors.green,
onPressed: () {
if (_formKey.currentState.validate()) {
ogrenciEkle(
Ogrenci(_controller.text, aktiflik == true ? 1 : 0));
}
},
),
RaisedButton(
child: Text("Guncelle"),
color: Colors.blue,
onPressed: () {
if (_formKey.currentState.validate()) {
_ogrenciGuncelle(Ogrenci.withID(tiklanilanOgrenciIDsi,
_controller.text, aktiflik == true ? 1 : 0));
}
}),
RaisedButton(
child: Text("Tum Tabloyu Sil"),
color: Colors.red,
onPressed: () {
_tumTabloyuTemizle();
}),
],
),
Expanded(
child: ListView.builder(
itemCount: tumOgrencilerListesi.length,
itemBuilder: (context, index) {
return Card(
color: tumOgrencilerListesi[index].aktif == 1
? Colors.green.shade200
: Colors.red.shade200,
child: ListTile(
onTap: () {
setState(() {
_controller.text = tumOgrencilerListesi[index].isim;
aktiflik = tumOgrencilerListesi[index].aktif == 1
? true
: false;
tiklanilanOgrenciIndeksi = index;
tiklanilanOgrenciIDsi = tumOgrencilerListesi[index].id;
});
},
title: Text(tumOgrencilerListesi[index].isim),
subtitle: Text(tumOgrencilerListesi[index].id.toString()),
trailing: GestureDetector(
onTap: () {
_ogrenciSil(tumOgrencilerListesi[index].id, index);
},
child: Icon(Icons.delete),
),
),
);
},
),
),
],
),
),
);
}
void ogrenciEkle(Ogrenci ogrenci) async {
var eklenenYeniOgrencininIDsi = await _databaseHelper.ogrenciEkle(ogrenci);
ogrenci.id = eklenenYeniOgrencininIDsi;
if (eklenenYeniOgrencininIDsi > 0) {
setState(() {
tumOgrencilerListesi.insert(0, ogrenci);
});
}
}
void _tumTabloyuTemizle() async {
var silinenElemanSayisi = await _databaseHelper.tumOgrenciTablosunuSil();
if (silinenElemanSayisi > 0) {
_scaffoldKey.currentState.showSnackBar(SnackBar(
duration: Duration(seconds: 2),
content: Text(silinenElemanSayisi.toString() + " kayıt silindi"),
));
setState(() {
tumOgrencilerListesi.clear();
});
}
}
void _ogrenciSil(
int dbdenSilmeyeYarayacakID, int listedenSilmeyeYarayacakIndex) async {
var sonuc = await _databaseHelper.ogrenciSil(dbdenSilmeyeYarayacakID);
if (sonuc == 1) {
_scaffoldKey.currentState.showSnackBar(SnackBar(
duration: Duration(seconds: 2),
content: Text("Kayit Silindi"),
));
setState(() {
tumOgrencilerListesi.removeAt(listedenSilmeyeYarayacakIndex);
});
} else {
_scaffoldKey.currentState.showSnackBar(SnackBar(
duration: Duration(seconds: 2),
content: Text("Silerken Hata Cikti"),
));
}
}
void _ogrenciGuncelle(Ogrenci ogrenci) async {
print(ogrenci.toString());
var sonuc = await _databaseHelper.ogrenciGuncelle(ogrenci);
if (sonuc == 1) {
_scaffoldKey.currentState.showSnackBar(SnackBar(
duration: Duration(seconds: 2),
content: Text("Kayit Guncellendi"),
));
setState(() {
tumOgrencilerListesi[tiklanilanOgrenciIndeksi] = ogrenci;
});
}
}
}
| 0
|
mirrored_repositories/SqFLite-Sample-Flutter-Project/sqflite_sample
|
mirrored_repositories/SqFLite-Sample-Flutter-Project/sqflite_sample/lib/dosya_islemleri.dart
|
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
class DosyaIslemleri extends StatefulWidget {
@override
_DosyaIslemleriState createState() => _DosyaIslemleriState();
}
class _DosyaIslemleriState extends State<DosyaIslemleri> {
var myTextController = TextEditingController();
//olusturulacak dosyanin klasor yolu
Future<String> get getKlasorYolu async {
Directory klasor = await getApplicationDocumentsDirectory();
debugPrint("Klasor Yolu : " + klasor.path);
return klasor.path;
}
//dosya olustur
Future<File> get dosyaOlustur async {
var olusturulacakDosyaninKlasorununYolu = await getKlasorYolu;
return File(olusturulacakDosyaninKlasorununYolu + "/myDosya.txt");
}
//dosya okuma islemleri
Future<String> dosyaOku() async {
try {
var myDosya = await dosyaOlustur;
String dosyaIcerigi = await myDosya.readAsString();
return dosyaIcerigi;
} catch (exception) {
return "Hata : $exception";
}
}
//dosya yazma islemleri
Future<File> dosyayaYaz(String yazilacakString) async {
var myDosya = await dosyaOlustur;
return myDosya.writeAsString(yazilacakString);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Dosya İşlemleri"),
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: myTextController,
maxLines: 4,
decoration: InputDecoration(
hintText: "Buraya yazılacak değerler dosyaya kaydedilir",
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
onPressed: _dosyaYaz,
color: Colors.blue,
child: Text("Dosyaya Yaz"),
),
RaisedButton(
onPressed: _dosyaOku,
color: Colors.green,
child: Text("Dosyadan Oku"),
),
],
)
],
),
),
);
}
void _dosyaYaz() {
dosyayaYaz(myTextController.text.toString());
}
void _dosyaOku() async {
//debugPrint(await dosyaOku());
dosyaOku().then((icerik) {
debugPrint(icerik);
});
}
}
| 0
|
mirrored_repositories/SqFLite-Sample-Flutter-Project/sqflite_sample
|
mirrored_repositories/SqFLite-Sample-Flutter-Project/sqflite_sample/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:sqflite_sample/dosya_islemleri.dart';
import 'package:sqflite_sample/shared_pref_kullanimi.dart';
import 'package:sqflite_sample/dosya_islemleri.dart';
import 'package:sqflite_sample/sqflite_islemleri.dart';
import 'package:sqflite_sample/utils/database_helper.dart';
import 'models/ogrenci.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
//DatabaseHelper dbh1 = DatabaseHelper();
@override
Widget build(BuildContext context) {
//dbh1.ogrenciEkle(Ogrenci("Sevdanur",1));
//dbdenVerilerGetir();
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
//home: SharedPrefKullanimi(),
//home: DosyaIslemleri(),
home: SqfliteIslemleri(),
debugShowCheckedModeBanner: false,
);
}
// void dbdenVerilerGetir() async {
// var sonuc = await dbh1.tumOgrenciler();
// print(sonuc.toString());
// }
}
| 0
|
mirrored_repositories/SqFLite-Sample-Flutter-Project/sqflite_sample
|
mirrored_repositories/SqFLite-Sample-Flutter-Project/sqflite_sample/lib/shared_pref_kullanimi.dart
|
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SharedPrefKullanimi extends StatefulWidget {
@override
_SharedPrefKullanimiState createState() => _SharedPrefKullanimiState();
}
class _SharedPrefKullanimiState extends State<SharedPrefKullanimi> {
String isim;
int id;
bool cinsiyet;
var formKey = GlobalKey<FormState>();
var mySharedPrefences;
@override
void initState() {
// TODO: implement initState
super.initState();
// SharedPreferences.getInstance().then((sf)=>mySharedPrefences=sf);
SharedPreferences.getInstance().then((sf) {
mySharedPrefences = sf;
});
}
@override
void dispose() {
mySharedPrefences.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Shared Pref Kullanımı"),
centerTitle: true,
),
body: SingleChildScrollView(
child: Form(
key: formKey,
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
onSaved: (deger) {
isim = deger;
},
decoration: InputDecoration(
labelText: "Isminizi giriniz",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
onSaved: (deger) {
id = int.parse(deger);
},
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: "ID giriniz",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: RadioListTile(
value: true,
groupValue: cinsiyet,
onChanged: (secildi) {
setState(() {
cinsiyet = secildi;
});
},
title: Text("Erkek"),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: RadioListTile(
value: false,
groupValue: cinsiyet,
onChanged: (secildi) {
setState(() {
cinsiyet = secildi;
});
},
title: Text("Kadın"),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
onPressed: _ekle,
child: Text("Kaydet"),
color: Colors.green,
),
RaisedButton(
onPressed: _goster,
child: Text("Göster"),
color: Colors.blue,
),
RaisedButton(
onPressed: _sil,
child: Text("Sil"),
color: Colors.red,
),
],
)
],
)),
),
);
}
void _ekle() async {
formKey.currentState.save();
await (mySharedPrefences as SharedPreferences).setString("myIsim", isim);
await (mySharedPrefences as SharedPreferences).setInt("myId", id);
await (mySharedPrefences as SharedPreferences).setBool("myCinsiyet", cinsiyet);
}
void _goster() {
debugPrint("Okunan isim "+(mySharedPrefences as SharedPreferences).getString("myIsim")?? "NULL");
debugPrint("Okunan id "+(mySharedPrefences as SharedPreferences).getInt("myId").toString() ?? "NULL");
debugPrint("Cinsiyet erkek mi "+(mySharedPrefences as SharedPreferences).getBool("myCinsiyet").toString() ?? "NULL");
}
void _sil() {
(mySharedPrefences as SharedPreferences).remove("myIsim");
(mySharedPrefences as SharedPreferences).remove("myId");
(mySharedPrefences as SharedPreferences).remove("myCinsiyet");
}
}
| 0
|
mirrored_repositories/SqFLite-Sample-Flutter-Project/sqflite_sample/lib
|
mirrored_repositories/SqFLite-Sample-Flutter-Project/sqflite_sample/lib/models/ogrenci.dart
|
class Ogrenci{
int _id;
String _isim;
int _aktif;
int get id => _id;
set id(int value) {
_id = value;
}
String get isim => _isim;
int get aktif => _aktif;
set aktif(int value) {
_aktif = value;
}
set isim(String value) {
_isim = value;
}
Ogrenci(this._isim, this._aktif);
Ogrenci.withID(this._id, this._isim, this._aktif);
Map<String, dynamic> dbyeYazmakIcinMapeDonustur(){
var map = Map<String, dynamic>();
map['id'] = _id;
map['isim'] = _isim;
map['aktif'] = _aktif;
return map;
}
Ogrenci.dbdenOkudugunMapiObjeyeDonustur(Map<String, dynamic> map){
this._id = map['id'];
this._isim = map['isim'];
this._aktif = map['aktif'];
}
@override
String toString() {
return 'Ogrenci{_id: $_id, _isim: $_isim, _aktif: $_aktif}';
}
}
| 0
|
mirrored_repositories/SqFLite-Sample-Flutter-Project/sqflite_sample/lib
|
mirrored_repositories/SqFLite-Sample-Flutter-Project/sqflite_sample/lib/utils/database_helper.dart
|
import 'dart:async';
import 'dart:io';
import 'package:sqflite_sample/models/ogrenci.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
class DatabaseHelper {
static DatabaseHelper _databaseHelper;
static Database _database;
String _ogrenciTablo = 'ogrenci';
String _columnID = 'id';
String _columnIsim = 'isim';
String _columnAktif = 'aktif';
factory DatabaseHelper() {
if (_databaseHelper == null) {
_databaseHelper = DatabaseHelper._internal();
print("DBHelper Null, olusturuldu");
return _databaseHelper;
} else {
print("DBHelper Null degil, var olan kullanilacak");
return _databaseHelper;
}
}
DatabaseHelper._internal();
Future<Database> _getDatabase() async {
if (_database == null) {
print("DB nulldi olusturulacak");
_database = await _initializeDatabase();
return _database;
} else {
print("DB null degildi var olan kullanilacak");
return _database;
}
}
_initializeDatabase() async {
Directory klasor = await getApplicationDocumentsDirectory();
String dbPath = join(klasor.path, "ogrenci.db");
print("DB Pathi:" + dbPath);
var ogrenciDB = openDatabase(dbPath, version: 1, onCreate: _createDB);
return ogrenciDB;
}
Future<void> _createDB(Database db, int version) async {
print("Create DB metotu calisti, tablo olusturulacak");
await db.execute(
"CREATE TABLE $_ogrenciTablo ($_columnID INTEGER PRIMARY KEY AUTOINCREMENT, "
"$_columnIsim TEXT, $_columnAktif INTEGER )");
}
Future<int> ogrenciEkle(Ogrenci ogrenci) async {
var db = await _getDatabase();
var sonuc = await db.insert(
_ogrenciTablo, ogrenci.dbyeYazmakIcinMapeDonustur(),
nullColumnHack: "$_columnID");
print("ogrenci db'ye eklendi : " + sonuc.toString());
return sonuc;
}
Future<List<Map<String, dynamic>>> tumOgrenciler() async {
var db = await _getDatabase();
var sonuc = await db.query(_ogrenciTablo, orderBy: '$_columnID');
print("Ogrencilerin Listesi : " + sonuc.toString());
return sonuc;
}
Future<int> ogrenciGuncelle(Ogrenci ogrenci) async {
var db = await _getDatabase();
var sonuc = await db.update(
_ogrenciTablo, ogrenci.dbyeYazmakIcinMapeDonustur(),
where: '$_columnID = ?', whereArgs: [ogrenci.id]);
print("Ogrenci guncellendi : " + sonuc.toString());
return sonuc;
}
Future<int> ogrenciSil(int id) async{
var db = await _getDatabase();
var sonuc = await db.delete(_ogrenciTablo, where: '$_columnID = ?', whereArgs: [id]);
print("Ogrenci silindi : " + sonuc.toString());
return sonuc;
}
Future<int> tumOgrenciTablosunuSil() async {
var db = await _getDatabase();
var sonuc = await db.delete(_ogrenciTablo);
print("Tablo silindi : " + sonuc.toString());
return sonuc;
}
}
| 0
|
mirrored_repositories/SqFLite-Sample-Flutter-Project/sqflite_sample
|
mirrored_repositories/SqFLite-Sample-Flutter-Project/sqflite_sample/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:sqflite_sample/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/pokedumb
|
mirrored_repositories/pokedumb/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pokemonapp/modules/views/Detail.dart';
import 'package:pokemonapp/modules/views/Home.dart';
import 'package:pokemonapp/modules/views/MainMenu.dart';
import 'package:pokemonapp/utils/Introduction.dart';
import 'package:pokemonapp/utils/Login.dart';
import 'package:pokemonapp/utils/SplashScreen.dart';
void main() {
runApp(
GetMaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: '/',
routes: {
'/': (context) => const SplashScreen(),
'/main': (context) => const MainMenu(),
'/home': (context) => const HomeView(),
'/start': (context) => const LoginView(),
'/intro': (context) => const IntroductionView(),
'/detail': (context) => const DetailView(),
},
),
);
}
| 0
|
mirrored_repositories/pokedumb/lib/modules
|
mirrored_repositories/pokedumb/lib/modules/views/MainMenu.dart
|
// ignore_for_file: file_names
import 'package:flutter/material.dart';
import 'package:pokemonapp/modules/views/Home.dart';
import 'package:pokemonapp/modules/views/Pokedex.dart';
class MainMenu extends StatefulWidget {
const MainMenu({super.key});
@override
State<MainMenu> createState() => _MainMenuState();
}
class _MainMenuState extends State<MainMenu> {
int _selectedIndex = 0;
final List<Widget> _screens = [
const HomeView(),
const PokeDataView(),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: _screens[_selectedIndex],
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Beranda',
),
BottomNavigationBarItem(
icon: Icon(Icons.catching_pokemon_rounded),
label: 'Pokedex',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.red,
onTap: _onItemTapped,
),
);
}
}
| 0
|
mirrored_repositories/pokedumb/lib/modules
|
mirrored_repositories/pokedumb/lib/modules/views/Home.dart
|
// ignore_for_file: file_names
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:pokemonapp/modules/controllers/GlobalController.dart';
import 'package:pokemonapp/modules/controllers/PokemonController.dart';
import 'package:pokemonapp/utils/Greeting.dart';
import 'package:recase/recase.dart';
import 'package:carousel_slider/carousel_slider.dart';
class HomeView extends StatefulWidget {
const HomeView({Key? key}) : super(key: key);
@override
State<HomeView> createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
final gController = Get.put(GlobalController());
final poke = Get.put(PokemonController());
final CarouselController _controller = CarouselController();
@override
Widget build(BuildContext context) {
Widget heading() {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
RichText(
text: TextSpan(
text: 'Poke',
style: GoogleFonts.poppins(
fontSize: 26,
fontWeight: FontWeight.bold,
color: Colors.red,
),
children: [
TextSpan(
text: 'dumb',
style: GoogleFonts.poppins(
fontSize: 26,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
],
),
),
Container(
margin: const EdgeInsets.only(right: 5),
child: Image.asset(
'assets/images/pokeball.png',
scale: 15,
),
),
],
);
}
Widget greet() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Halo, ${gController.name.value.titleCase}',
style: GoogleFonts.poppins(
fontSize: 17,
fontWeight: FontWeight.w500,
color: Colors.red,
),
),
Text(
greeting(),
style: GoogleFonts.poppins(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
],
);
}
Widget carousel() {
return Obx(
() {
if (poke.isLoading.value) {
return const CircularProgressIndicator();
} else {
return Column(
children: [
Container(
alignment: Alignment.centerLeft,
margin: const EdgeInsets.only(top: 40, right: 20),
child: SizedBox(
width: 150,
child: Text(
'Temukan pokemon andalan kalian',
style: GoogleFonts.poppins(
fontSize: 13,
fontWeight: FontWeight.w500,
color: Colors.grey,
),
),
),
),
Container(
margin: const EdgeInsets.symmetric(vertical: 20),
child: CarouselSlider.builder(
itemCount: poke.pokeList.length,
itemBuilder: (context, index, realIndex) {
var getPoke = poke.pokeList[index];
var hexa = int.parse(getPoke.color);
return Column(
children: [
Expanded(
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: Color(hexa),
borderRadius: BorderRadius.circular(12),
),
child: Column(
children: [
Image.asset(
getPoke.image,
scale: 2.5,
),
Text(
getPoke.name,
style: GoogleFonts.poppins(
fontSize: 14,
fontWeight: FontWeight.w600,
color: Colors.white,
),
),
],
),
),
),
],
);
},
options: CarouselOptions(
aspectRatio: 2.0,
autoPlay: true,
enableInfiniteScroll: true,
enlargeCenterPage: true,
onPageChanged: (index, reason) {
setState(() {
poke.current.value = index;
});
},
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: poke.pokeList.asMap().entries.map((val) {
return GestureDetector(
onTap: () => _controller.animateToPage(val.key),
child: Container(
height: 8,
width: 8,
margin: const EdgeInsets.symmetric(
horizontal: 4, vertical: 8),
decoration: BoxDecoration(
shape: BoxShape.circle,
color:
(Theme.of(context).brightness == Brightness.dark
? Colors.black
: Colors.red)
.withOpacity(
poke.current.value == val.key ? 0.9 : 0.4,
),
),
),
);
}).toList(),
)
],
);
}
},
);
}
void dialogPop(
BuildContext context, String selectedTitle, String contentBody) async {
await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(selectedTitle),
content: Text(contentBody),
);
},
);
}
Widget features() {
return Container(
margin: const EdgeInsets.symmetric(vertical: 30),
child: Column(
children: [
Container(
alignment: Alignment.centerLeft,
margin: const EdgeInsets.symmetric(vertical: 15),
child: Text(
'Fitur',
style: GoogleFonts.poppins(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.grey,
),
),
),
SizedBox(
height: 180,
child: Obx(() {
if (poke.isLoading.value) {
return const CircularProgressIndicator();
} else {
return RefreshIndicator(
onRefresh: poke.getFitur,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: poke.fiturList.length,
itemBuilder: (context, index) {
var fitur = poke.fiturList[index];
var hexax = int.parse(fitur.color);
return Container(
width: 300,
margin: const EdgeInsets.symmetric(horizontal: 20),
decoration: BoxDecoration(
color: Color(hexax),
borderRadius: BorderRadius.circular(12),
),
child: ListTile(
title: Container(
margin: const EdgeInsets.symmetric(vertical: 10),
child: Text(
'Temukan berdasarkan',
style: GoogleFonts.poppins(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
subtitle: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
InkWell(
onTap: () {
String selectedTitle = fitur.title;
String contentBody = fitur.content;
return dialogPop(
context, selectedTitle, contentBody);
},
child: Container(
alignment: Alignment.center,
width: 100,
height: 40,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
),
child: Text(
fitur.title,
style: GoogleFonts.poppins(
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
),
),
Image.asset(
fitur.img,
height: 130,
width: 130,
alignment: Alignment.center,
),
],
),
),
);
},
),
);
}
}),
),
],
),
);
}
return Scaffold(
body: SafeArea(
child: Container(
width: double.infinity,
margin: const EdgeInsets.only(
top: 20,
right: 30,
left: 30,
),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
heading(),
const SizedBox(height: 15),
greet(),
carousel(),
features(),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/pokedumb/lib/modules
|
mirrored_repositories/pokedumb/lib/modules/views/Pokedex.dart
|
// ignore_for_file: file_names
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:pokemonapp/modules/controllers/GlobalController.dart';
import 'package:pokemonapp/modules/controllers/PokemonController.dart';
class PokeDataView extends StatefulWidget {
const PokeDataView({super.key});
@override
State<PokeDataView> createState() => _PokeDataViewState();
}
class _PokeDataViewState extends State<PokeDataView> {
final pokeController = Get.put(PokemonController());
final gController = Get.put(GlobalController());
@override
Widget build(BuildContext context) {
Widget heading() {
return Container(
margin: const EdgeInsets.symmetric(vertical: 20, horizontal: 30),
alignment: Alignment.centerLeft,
child: Row(
children: [
RichText(
text: TextSpan(
text: 'Poke',
style: GoogleFonts.poppins(
fontSize: 25,
fontWeight: FontWeight.bold,
color: Colors.red),
children: [
TextSpan(
text: 'dex',
style: GoogleFonts.poppins(
fontSize: 25,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
],
),
),
const SizedBox(
width: 10,
),
const Icon(
Icons.catching_pokemon_rounded,
color: Colors.red,
size: 30,
)
],
),
);
}
Widget pokedex() {
return Expanded(
child: Obx(
() {
if (pokeController.isLoading.value) {
return const CircularProgressIndicator();
} else {
return RefreshIndicator(
onRefresh: pokeController.getDataPokemon,
child: ListView.builder(
itemCount: pokeController.pokeList.length,
itemBuilder: (context, index) {
var pokemon = pokeController.pokeList[index];
var hexa = int.parse(pokemon.color);
return InkWell(
onTap: () {
Get.toNamed('/detail', arguments: pokemon);
},
child: Container(
margin: const EdgeInsets.symmetric(
horizontal: 40, vertical: 20),
width: double.infinity,
height: 150,
decoration: BoxDecoration(
color: Color(hexa),
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 5,
blurRadius: 7,
offset: const Offset(0, 3),
),
],
),
child: Column(
children: [
Container(
margin: const EdgeInsets.symmetric(
horizontal: 10, vertical: 10),
alignment: Alignment.centerLeft,
child: Text(
pokemon.name,
style: GoogleFonts.poppins(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
Container(
margin: const EdgeInsets.symmetric(
horizontal: 10,
),
child: Row(
children: [
Container(
alignment: Alignment.center,
height: 45,
width: 120,
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.4),
borderRadius: BorderRadius.circular(12),
),
child: Text(
pokemon.category,
style: GoogleFonts.poppins(
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
),
Container(
margin: const EdgeInsets.only(left: 60),
height: 100,
width: 100,
child: Image.asset(pokemon.image),
),
],
),
)
],
),
),
);
},
),
);
}
},
),
);
}
return Scaffold(
body: SafeArea(
child: Column(
children: [
heading(),
pokedex(),
],
),
),
);
}
}
| 0
|
mirrored_repositories/pokedumb/lib/modules
|
mirrored_repositories/pokedumb/lib/modules/views/Detail.dart
|
// ignore_for_file: file_names
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
class DetailView extends StatefulWidget {
const DetailView({super.key});
@override
State<DetailView> createState() => _DetailViewState();
}
class _DetailViewState extends State<DetailView> {
final dynamic pokemon = Get.arguments;
@override
Widget build(BuildContext context) {
var hexa = int.parse(pokemon.color);
Widget nav() {
return Container(
alignment: Alignment.topLeft,
margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
child: IconButton(
onPressed: () {
Get.back();
},
icon: const Icon(
Icons.arrow_back_ios_new_rounded,
),
),
);
}
Widget head() {
return Expanded(
child: Container(
alignment: Alignment.centerLeft,
margin: const EdgeInsets.only(
left: 30,
bottom: 60,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
alignment: Alignment.centerLeft,
child: Text(
pokemon.name,
style: GoogleFonts.poppins(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
Container(
alignment: Alignment.centerLeft,
child: Container(
alignment: Alignment.center,
width: 90,
height: 25,
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.5),
borderRadius: BorderRadius.circular(12),
),
child: Text(
pokemon.category,
style: GoogleFonts.poppins(
fontSize: 14,
fontWeight: FontWeight.w500,
color: Colors.black,
),
),
),
),
],
),
),
);
}
Widget body() {
return Expanded(
flex: 2,
child: SingleChildScrollView(
child: Container(
decoration: const BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30),
),
color: Colors.white,
),
child: Container(
margin: const EdgeInsets.only(left: 30, top: 140),
alignment: Alignment.topLeft,
child: Column(
children: [
Align(
alignment: Alignment.centerLeft,
child: Text(
'Deskripsi Pokemon',
style: GoogleFonts.poppins(
fontSize: 17,
fontWeight: FontWeight.w500,
color: Colors.black,
),
),
),
const SizedBox(height: 30),
Align(
alignment: Alignment.centerLeft,
child: RichText(
text: TextSpan(
text: 'Berat : ',
style: GoogleFonts.poppins(
fontSize: 17,
fontWeight: FontWeight.w500,
color: Colors.black,
),
children: [
TextSpan(text: '${pokemon.weight}'),
],
),
),
),
const SizedBox(height: 20),
Align(
alignment: Alignment.centerLeft,
child: RichText(
text: TextSpan(
text: 'Tinggi : ',
style: GoogleFonts.poppins(
fontSize: 17,
fontWeight: FontWeight.w500,
color: Colors.black,
),
children: [
TextSpan(text: '${pokemon.height} ft'),
],
),
),
),
const SizedBox(height: 20),
Align(
alignment: Alignment.centerLeft,
child: RichText(
text: TextSpan(
text: 'Ultimate : ',
style: GoogleFonts.poppins(
fontSize: 17,
fontWeight: FontWeight.w500,
color: Colors.black,
),
children: [
TextSpan(text: '${pokemon.abilities}'),
],
),
),
),
const SizedBox(height: 20),
Container(
margin: const EdgeInsets.only(right: 25, bottom: 15),
child: Align(
alignment: Alignment.centerLeft,
child: RichText(
textAlign: TextAlign.justify,
text: TextSpan(
text: 'Tentang : ',
style: GoogleFonts.poppins(
fontSize: 17,
fontWeight: FontWeight.w500,
color: Colors.black,
),
children: [
TextSpan(
text: '${pokemon.deskripsi}',
style: GoogleFonts.poppins(
fontSize: 14,
fontWeight: FontWeight.normal,
),
),
],
),
),
),
),
],
),
),
),
),
);
}
Widget avatar() {
return Positioned(
left: (MediaQuery.of(context).size.width / 4),
top: 130,
child: Image.asset(
pokemon.image,
scale: 1.4,
alignment: Alignment.center,
),
);
}
return Scaffold(
backgroundColor: Color(hexa),
body: SafeArea(
child: Stack(
children: [
Column(
children: [
head(),
body(),
],
),
nav(),
avatar(),
],
),
),
);
}
}
| 0
|
mirrored_repositories/pokedumb/lib/modules
|
mirrored_repositories/pokedumb/lib/modules/controllers/PokemonController.dart
|
// ignore_for_file: file_names
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:pokemonapp/modules/models/FiturModel.dart';
import 'package:pokemonapp/modules/models/PokeModel.dart';
class PokemonController extends GetxController {
List<dynamic> pokeList = [].obs;
List<dynamic> fiturList = [].obs;
var isLoading = true.obs;
final current = 0.obs;
@override
void onInit() {
getDataPokemon();
getFitur();
super.onInit();
}
Future<void> getDataPokemon() async {
try {
final jsonData =
await rootBundle.loadString('assets/json/pokemondumb.json');
final data = jsonDecode(jsonData);
pokeList = data['pokemons']
.map((snapshot) => PokeModel.fromJson(snapshot))
.toList();
isLoading.value = false;
} catch (e) {
isLoading.value = false;
}
}
Future<void> getFitur() async {
try {
final json = await rootBundle.loadString('assets/json/fitur.json');
final decodedata = jsonDecode(json);
fiturList =
decodedata['fitur'].map((val) => FiturModel.fromJson(val)).toList();
isLoading.value = false;
} catch (e) {
isLoading.value = false;
}
}
}
| 0
|
mirrored_repositories/pokedumb/lib/modules
|
mirrored_repositories/pokedumb/lib/modules/controllers/GlobalController.dart
|
// ignore_for_file: file_names
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class GlobalController extends GetxController {
TextEditingController textController = TextEditingController();
var name = ''.obs;
@override
void onInit() {
super.onInit();
// Tambahkan listener pada textController
textController.addListener(() {
name.value = textController.text.toLowerCase();
});
}
}
| 0
|
mirrored_repositories/pokedumb/lib/modules
|
mirrored_repositories/pokedumb/lib/modules/models/FiturModel.dart
|
// ignore_for_file: file_names
class FiturModel {
final String title, content, img, color;
FiturModel(
this.title,
this.content,
this.img,
this.color,
);
factory FiturModel.fromJson(Map<String, dynamic> json) {
return FiturModel(
json['title'],
json['content'],
json['img'],
json['color'],
);
}
}
| 0
|
mirrored_repositories/pokedumb/lib/modules
|
mirrored_repositories/pokedumb/lib/modules/models/PokeModel.dart
|
// ignore_for_file: file_names
class PokeModel {
final String name,
image,
category,
weight,
height,
abilities,
color,
deskripsi;
PokeModel(
this.name,
this.image,
this.category,
this.weight,
this.height,
this.abilities,
this.color,
this.deskripsi,
);
factory PokeModel.fromJson(Map<String, dynamic> json) {
return PokeModel(
json['name'],
json['image'],
json['category'],
json['weight'],
json['height'],
json['abilities'],
json['color'],
json['deskripsi']);
}
}
| 0
|
mirrored_repositories/pokedumb/lib
|
mirrored_repositories/pokedumb/lib/utils/Login.dart
|
// ignore_for_file: file_names
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:pokemonapp/modules/controllers/GlobalController.dart';
class LoginView extends StatefulWidget {
const LoginView({super.key});
@override
State<LoginView> createState() => _LoginViewState();
}
class _LoginViewState extends State<LoginView> {
final _globalKey = GlobalKey<FormState>();
final gController = Get.put(GlobalController());
@override
Widget build(BuildContext context) {
Widget logo() {
return SizedBox(
width: 350,
height: 200,
child: Image.asset('assets/images/pokemon.png'),
);
}
Widget formList() {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 40),
width: double.infinity,
child: Form(
key: _globalKey,
child: TextFormField(
controller: gController.textController,
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: Colors.green),
),
floatingLabelStyle: GoogleFonts.poppins(
fontSize: 14,
fontWeight: FontWeight.w500,
color: Colors.green,
),
labelText: 'Masukkan Nama',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
),
validator: (val) {
if (val!.isEmpty) {
Fluttertoast.showToast(
msg: 'Gagal',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 16,
);
return 'Nama harus diisi ngab';
} else {
return null;
}
},
),
),
);
}
Widget loginbutton() {
return Container(
width: 200,
height: 45,
margin: const EdgeInsets.symmetric(vertical: 40),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(12),
),
child: TextButton(
onPressed: () {
if (_globalKey.currentState!.validate()) {
Navigator.pushReplacementNamed(context, '/main');
Fluttertoast.showToast(
msg: 'Berhasil Masuk',
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 16,
);
}
},
child: Text(
'Login',
style: GoogleFonts.poppins(
fontWeight: FontWeight.w600,
fontSize: 18,
color: Colors.white,
),
),
),
);
}
Widget prolog() {
return Container(
margin: const EdgeInsets.symmetric(
horizontal: 45,
vertical: 10,
),
alignment: Alignment.centerLeft,
child: Text(
'Login',
style: GoogleFonts.poppins(
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
);
}
return Scaffold(
body: SafeArea(
child: Container(
alignment: Alignment.center,
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
logo(),
prolog(),
formList(),
loginbutton(),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/pokedumb/lib
|
mirrored_repositories/pokedumb/lib/utils/Introduction.dart
|
// ignore_for_file: file_names
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:introduction_screen/introduction_screen.dart';
import 'package:lottie/lottie.dart';
class IntroductionView extends StatefulWidget {
const IntroductionView({super.key});
@override
State<IntroductionView> createState() => _IntroductionViewState();
}
class _IntroductionViewState extends State<IntroductionView> {
List<PageViewModel> listPageViewModel = [
PageViewModel(
titleWidget: Text(
'Pokemon',
style: GoogleFonts.poppins(
fontSize: 22,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
bodyWidget: Text(
'Monster yang memiliki kekuatan unik dan akan bertambah seiring dengan evolusinya',
style: GoogleFonts.poppins(
fontSize: 18,
fontWeight: FontWeight.w500,
color: Colors.red,
),
textAlign: TextAlign.center,
),
image: Lottie.asset(
'assets/json/pokemon.json',
height: 150,
width: 150,
),
),
PageViewModel(
titleWidget: Text(
'Pokedex',
style: GoogleFonts.poppins(
fontSize: 22,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
bodyWidget: Text(
'Temukan pokemon yang anda sukai dengan pokedex',
style: GoogleFonts.poppins(
fontSize: 18,
fontWeight: FontWeight.w500,
color: Colors.red,
),
textAlign: TextAlign.center,
),
image: Lottie.asset(
'assets/json/selection-list.json',
height: 200,
width: 200,
),
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Container(
alignment: Alignment.center,
child: IntroductionScreen(
pages: listPageViewModel,
dotsDecorator: const DotsDecorator(
color: Colors.black,
activeColor: Colors.red,
),
showSkipButton: true,
showNextButton: false,
skip: Text(
"Lewati",
style: GoogleFonts.poppins(
fontSize: 16,
fontWeight: FontWeight.w500,
color: Colors.red,
),
),
done: Text(
"Mulai",
style: GoogleFonts.poppins(
fontSize: 16,
fontWeight: FontWeight.w500,
color: Colors.red,
),
),
onDone: () {
Navigator.pushNamedAndRemoveUntil(
context, '/start', (route) => false);
},
),
),
),
);
}
}
| 0
|
mirrored_repositories/pokedumb/lib
|
mirrored_repositories/pokedumb/lib/utils/Greeting.dart
|
// ignore_for_file: file_names
String greeting() {
var hour = DateTime.now().hour;
if (hour < 11) {
return 'Selamat Pagi';
} else if (hour < 15) {
return 'Selamat Siang';
} else if (hour < 18) {
return 'Selamat Sore';
} else if (hour < 24) {
return 'Selamat Malam';
}
return 'Selamat Pagi';
}
| 0
|
mirrored_repositories/pokedumb/lib
|
mirrored_repositories/pokedumb/lib/utils/SplashScreen.dart
|
// ignore_for_file: file_names
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:lottie/lottie.dart';
class SplashScreen extends StatefulWidget {
const SplashScreen({super.key});
@override
State<SplashScreen> createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
super.initState();
Future.delayed(
const Duration(seconds: 3),
() {
Navigator.pushReplacementNamed(context, '/intro');
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
child: Lottie.asset(
'assets/json/pokeball.json',
alignment: Alignment.center,
height: 100,
width: 100,
),
),
Container(
margin: const EdgeInsets.symmetric(vertical: 30),
child: RichText(
text: TextSpan(
text: 'Poke',
style: GoogleFonts.poppins(
fontSize: 22,
fontWeight: FontWeight.bold,
color: Colors.red,
),
children: [
TextSpan(
text: 'dumb',
style: GoogleFonts.poppins(
color: Colors.black,
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/pokedumb
|
mirrored_repositories/pokedumb/test/widget_test.dart
|
// // This is a basic Flutter widget test.
// //
// // To perform an interaction with a widget in your test, use the WidgetTester
// // utility in the flutter_test package. For example, you can send tap and scroll
// // gestures. You can also use WidgetTester to find child widgets in the widget
// // tree, read text, and verify that the values of widget properties are correct.
// import 'package:flutter/material.dart';
// import 'package:flutter_test/flutter_test.dart';
// import 'package:pokemonapp/main.dart';
// void main() {
// testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// // Build our app and trigger a frame.
// await tester.pumpWidget(const MyApp());
// // Verify that our counter starts at 0.
// expect(find.text('0'), findsOneWidget);
// expect(find.text('1'), findsNothing);
// // Tap the '+' icon and trigger a frame.
// await tester.tap(find.byIcon(Icons.add));
// await tester.pump();
// // Verify that our counter has incremented.
// expect(find.text('0'), findsNothing);
// expect(find.text('1'), findsOneWidget);
// });
// }
| 0
|
mirrored_repositories/flutter_scroll_animation/flutter_scroll_animation
|
mirrored_repositories/flutter_scroll_animation/flutter_scroll_animation/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_scroll_animation/pages/home.dart';
import 'package:google_fonts/google_fonts.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
useMaterial3: true,
textTheme: GoogleFonts.titilliumWebTextTheme(),
),
home: const FinalView(),
);
}
}
| 0
|
mirrored_repositories/flutter_scroll_animation/flutter_scroll_animation/lib
|
mirrored_repositories/flutter_scroll_animation/flutter_scroll_animation/lib/repository/jewellery_repository.dart
|
import 'package:flutter_scroll_animation/models/jewellery.dart';
class JewelleryRepository {
/// Earnings
static List<JewelleryModel> earnings = [
JewelleryModel(
name: 'Hoop earrings with bow charm',
description:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.',
price: 19.99,
image:
'https://www.my-jewellery.com/media/catalog/product/cache/11c3b41386dea29ed7e600d018f63705/p/r/product_images-_mj_3906_1.jpg'),
JewelleryModel(
name: 'Three hearts statement earrings',
description:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.',
price: 19.99,
image:
'https://www.my-jewellery.com/media/catalog/product/cache/88cfb905fc78966ffa0563039e5fb511/p/r/product_images-_mj_7044.jpg'),
JewelleryModel(
name: 'Oval chain earrings',
description:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.',
price: 22.99,
image:
'https://www.my-jewellery.com/media/catalog/product/cache/88cfb905fc78966ffa0563039e5fb511/o/o/oorringen_ovale_schakel-mj01568-1200.jpg'),
];
/// Ring
static List<JewelleryModel> ring = [
JewelleryModel(
name: 'Ring with small heart',
description:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.',
price: 15.99,
image:
'https://www.my-jewellery.com/media/catalog/product/cache/88cfb905fc78966ffa0563039e5fb511/p/r/product_images-_mj_1736.jpg'),
JewelleryModel(
name: 'Wide structure mix ring',
description:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.',
price: 15.99,
image:
'https://www.my-jewellery.com/media/catalog/product/cache/11c3b41386dea29ed7e600d018f63705/s/t/stretch_ringen_set-mj04332-1500.jpg',
),
JewelleryModel(
name: 'Ring with hearts',
description:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.',
price: 19.99,
image:
'https://www.my-jewellery.com/media/catalog/product/cache/11c3b41386dea29ed7e600d018f63705/m/i/mix_ring_breed_structuur-mj04892-1200.jpg'),
JewelleryModel(
name: 'Universe statement ring ',
description:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.',
price: 19.99,
image:
'https://www.my-jewellery.com/media/catalog/product/cache/88cfb905fc78966ffa0563039e5fb511/p/r/product_images-_my_0797.jpg'),
];
/// Diamond
static List<JewelleryModel> diamond = [
JewelleryModel(
name: 'Chain necklace with cubic zirconia initial',
description:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.',
price: 29.99,
image:
'https://www.my-jewellery.com/media/catalog/product/cache/88cfb905fc78966ffa0563039e5fb511/p/r/product_images-_mj_2442.jpg'),
JewelleryModel(
name: 'Ring with clear zirconia',
description:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.',
price: 20.00,
image:
'https://www.my-jewellery.com/media/catalog/product/cache/11c3b41386dea29ed7e600d018f63705/p/r/product_images-_mj_0107.jpg'),
JewelleryModel(
name: 'Initial ring with rhinestone',
description:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.',
price: 17.99,
image:
'https://www.my-jewellery.com/media/catalog/product/cache/11c3b41386dea29ed7e600d018f63705/p/r/product_images-_mj_0719.jpg'),
];
}
| 0
|
mirrored_repositories/flutter_scroll_animation/flutter_scroll_animation/lib
|
mirrored_repositories/flutter_scroll_animation/flutter_scroll_animation/lib/pages/home.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_scroll_animation/models/jewellery.dart';
import 'package:flutter_scroll_animation/repository/jewellery_repository.dart';
import 'package:remixicon/remixicon.dart';
class FinalView extends StatefulWidget {
const FinalView({Key? key}) : super(key: key);
@override
_FinalViewState createState() => _FinalViewState();
}
class _FinalViewState extends State<FinalView> {
/// Categories keys
final List<GlobalKey> jewelleryCategories = [
GlobalKey(),
GlobalKey(),
GlobalKey(),
];
/// Scroll Controller
late ScrollController scrollController;
/// Tab Context
BuildContext? tabContext;
@override
void initState() {
scrollController = ScrollController();
scrollController.addListener(animateToTab);
super.initState();
}
/// Animate To Tab
void animateToTab() {
late RenderBox box;
for (var i = 0; i < jewelleryCategories.length; i++) {
box = jewelleryCategories[i].currentContext!.findRenderObject()
as RenderBox;
Offset position = box.localToGlobal(Offset.zero);
if (scrollController.offset >= position.dy) {
DefaultTabController.of(tabContext!).animateTo(
i,
duration: const Duration(milliseconds: 100),
);
}
}
}
/// Scroll to Index
void scrollToIndex(int index) async {
scrollController.removeListener(animateToTab);
final categories = jewelleryCategories[index].currentContext!;
await Scrollable.ensureVisible(
categories,
duration: const Duration(milliseconds: 600),
);
scrollController.addListener(animateToTab);
}
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Builder(
builder: (BuildContext context) {
tabContext = context;
return Scaffold(
appBar: _buildAppBar(),
body: SingleChildScrollView(
controller: scrollController,
child: Column(
children: [
/// Earnings Title - Content
_buildCategoryTitle('Earnings', 0),
_buildItemList(JewelleryRepository.earnings),
/// Ring Title - Content
_buildCategoryTitle('Ring', 1),
_buildItemList(JewelleryRepository.ring),
/// Diamonds Title - Content
_buildCategoryTitle('Diamond', 2),
_buildItemList(JewelleryRepository.diamond),
/// Empty Bottom space
const SizedBox(
height: 30,
)
],
),
),
);
},
),
);
}
/// AppBar
AppBar _buildAppBar() {
return AppBar(
leading:
IconButton(onPressed: () {}, icon: const Icon(Remix.menu_2_line)),
actions: [
IconButton(
onPressed: () {},
icon: const Icon(
Remix.search_line,
),
)
],
title: const Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
'Purchase your Jewellery in a minute with',
style: TextStyle(fontSize: 14, color: Colors.black54),
),
Text(
'JewellGo',
style: TextStyle(
fontWeight: FontWeight.w900,
fontStyle: FontStyle.italic,
),
)
],
),
bottom: TabBar(
tabs: const [
Tab(child: Text('Earnings')),
Tab(child: Text('Ring')),
Tab(child: Text('Diamond')),
],
onTap: (int index) => scrollToIndex(index),
),
);
}
/// Item Lists
Widget _buildItemList(List<JewelleryModel> categories) {
return Column(
children: categories.map((m3) => _buildSingleItem(m3)).toList(),
);
}
/// Single Product item widget
Widget _buildSingleItem(JewelleryModel item) {
return Column(
children: [
SizedBox(
width: double.infinity,
height: 160,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Row(
children: [
Expanded(
flex: 2,
child: Image.network(
item.image,
fit: BoxFit.cover,
),
),
Expanded(
flex: 3,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.name,
style: const TextStyle(
fontSize: 21,
fontWeight: FontWeight.bold,
),
),
Text(
item.description,
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12, color: Colors.grey.shade600),
),
Padding(
padding: const EdgeInsets.only(top: 24),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
"€${item.price}",
style: const TextStyle(
fontSize: 16, color: Colors.black),
),
const SizedBox(
width: 10,
),
Text(
"€${item.price + 26.07}",
style: const TextStyle(
decoration: TextDecoration.lineThrough,
fontSize: 13,
color: Colors.grey),
),
],
),
const Icon(Remix.arrow_right_s_line)
],
),
),
],
),
),
),
],
),
),
),
const SizedBox(
height: 20,
),
],
);
}
/// Category Title
Widget _buildCategoryTitle(String title, int index) {
return Padding(
key: jewelleryCategories[index],
padding: const EdgeInsets.only(top: 14, right: 12, left: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
title,
style: const TextStyle(
fontSize: 19,
fontWeight: FontWeight.w900,
),
),
TextButton(
onPressed: () {},
child: const Text(
'View more',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w300,
color: Colors.indigo),
),
),
],
),
const Divider(),
],
),
);
}
}
| 0
|
mirrored_repositories/flutter_scroll_animation/flutter_scroll_animation/lib
|
mirrored_repositories/flutter_scroll_animation/flutter_scroll_animation/lib/models/jewellery.dart
|
class JewelleryModel {
String name;
String description;
double price;
String image;
JewelleryModel({
required this.name,
required this.description,
required this.price,
required this.image,
});
}
| 0
|
mirrored_repositories/QUIZ-APP-FLUTTER
|
mirrored_repositories/QUIZ-APP-FLUTTER/lib/main.dart
|
import 'package:flutter/material.dart';
import 'home.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
title: "QUIZ",
);
}
}
| 0
|
mirrored_repositories/QUIZ-APP-FLUTTER
|
mirrored_repositories/QUIZ-APP-FLUTTER/lib/ques.dart
|
final QUES = [
{
"question": "What is the scientific name of a butterfly?",
"answers": ["Apis", "Coleoptera", "Formicidae", "Rhopalocera"],
"correctIndex": 3
},
{
"question": "How hot is the surface of the sun?",
"answers": ["1,233 K", "5,778 K", "12,130 K", "101,300 K"],
"correctIndex": 1
},
{
"question": "Who are the actors in The Internship?",
"answers": [
"Ben Stiller, Jonah Hill",
"Courteney Cox, Matt LeBlanc",
"Kaley Cuoco, Jim Parsons",
"Vince Vaughn, Owen Wilson"
],
"correctIndex": 3
},
{
"question": "What is the capital of Spain?",
"answers": ["Berlin", "Buenos Aires", "Madrid", "San Juan"],
"correctIndex": 2
},
{
"question":
"What are the school colors of the University of Texas at Austin?",
"answers": [
"Black, Red",
"Blue, Orange",
"White, Burnt Orange",
"White, Old gold, Gold"
],
"correctIndex": 2
},
{
"question": "What is 70 degrees Fahrenheit in Celsius?",
"answers": ["18.8889", "20", "21.1111", "158"],
"correctIndex": 2
},
{
"question": "When was Mahatma Gandhi born?",
"answers": [
"October 2, 1869",
"December 15, 1872",
"July 18, 1918",
"January 15, 1929"
],
"correctIndex": 0
},
{
"question": "How far is the moon from Earth?",
"answers": [
"7,918 miles (12,742 km)",
"86,881 miles (139,822 km)",
"238,400 miles (384,400 km)",
"35,980,000 miles (57,910,000 km)"
],
"correctIndex": 2
},
{
"question": "What is 65 times 52?",
"answers": ["117", "3120", "3380", "3520"],
"correctIndex": 2
},
{
"question": "How tall is Mount Everest?",
"answers": [
"6,683 ft (2,037 m)",
"7,918 ft (2,413 m)",
"19,341 ft (5,895 m)",
"29,029 ft (8,847 m)"
],
"correctIndex": 3
},
{
"question": "When did The Avengers come out?",
"answers": ["May 2, 2008", "May 4, 2012", "May 3, 2013", "April 4, 2014"],
"correctIndex": 1
},
{
"question": "What is 48,879 in hexidecimal?",
"answers": ["0x18C1", "0xBEEF", "0xDEAD", "0x12D591"],
"correctIndex": 1
}
];
| 0
|
mirrored_repositories/QUIZ-APP-FLUTTER
|
mirrored_repositories/QUIZ-APP-FLUTTER/lib/home.dart
|
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:quiz_app/components/AnswerButton.dart';
import 'package:quiz_app/components/HeadingText.dart';
import 'package:quiz_app/components/QuestionText.dart';
import 'ques.dart';
//APP CONSTANTS
var _THEME_COLOUR_ = const Color(0xff0A3D62);
class Home extends StatefulWidget {
Home({Key key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int totalQues = 3;
int solvedQues = 0;
String nextQue = "";
String quiz_status = "START";
String score = "";
String op1, op2, op3, op4, answer;
bool isQuizStarted = false;
int finalScore = 0;
List<int> solvedQuesIndexes = [];
void check_ans(String value) {
print(value);
setState(() {
solvedQues += 1;
if (value == answer) {
finalScore += 1;
}
if (solvedQues == 3) {
isQuizStarted = false;
score = "SCORE: $finalScore/$totalQues";
nextQue = "";
op1 = "";
op2 = "";
op3 = "";
op4 = "";
} else {
var index = Random().nextInt(QUES.length);
while (solvedQuesIndexes.contains(index)) {
index = Random().nextInt(QUES.length);
}
solvedQuesIndexes.add(index);
List<String> ans = QUES[index]['answers'];
nextQue = QUES[index]['question'];
op1 = ans[0];
op2 = ans[1];
op3 = ans[2];
op4 = ans[3];
answer = ans[QUES[index]['correctIndex']];
}
});
}
void start_quiz() {
print("In");
setState(() {
finalScore = 0;
solvedQues = 0;
isQuizStarted = true;
score = "";
quiz_status = "RESTART";
solvedQuesIndexes = [];
var index = Random().nextInt(QUES.length);
while (solvedQuesIndexes.contains(index)) {
index = Random().nextInt(QUES.length);
}
solvedQuesIndexes.add(index);
List<String> ans = QUES[index]['answers'];
nextQue = QUES[index]['question'];
op1 = ans[0];
op2 = ans[1];
op3 = ans[2];
op4 = ans[3];
answer = ans[QUES[index]['correctIndex']];
});
}
// String nextque = "Whats is the scientific name of a butterfly?";
@override
Widget build(BuildContext context) {
double screen_width = MediaQuery.of(context).size.width * 0.8;
return Scaffold(
appBar: AppBar(
backgroundColor: _THEME_COLOUR_,
title: Text(
"QUIZ",
style: TextStyle(
fontSize: 24.0,
),
),
centerTitle: true,
),
// backgroundColor: _THEME_BG_COLOUR_,
body: ListView(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Column(
children: <Widget>[
HeadingText(
"Questions: $solvedQues/$totalQues".toUpperCase(),
),
QuestionText("$nextQue", screen_width),
//Answer Button
Column(
children: <Widget>[
AnswerButton(op1, isQuizStarted, check_ans, screen_width),
AnswerButton(op2, isQuizStarted, check_ans, screen_width),
AnswerButton(op3, isQuizStarted, check_ans, screen_width),
AnswerButton(op4, isQuizStarted, check_ans, screen_width),
],
),
HeadingText("$score".toUpperCase()),
Padding(
padding: const EdgeInsets.all(8.0),
child: MaterialButton(
onPressed: start_quiz,
color: Colors.green[800],
minWidth: screen_width,
height: 50.0,
child: Text(
"$quiz_status",
style: TextStyle(
fontSize: 24.0,
color: Colors.white,
),
),
),
),
],
),
],
),
],
),
);
}
}
| 0
|
mirrored_repositories/QUIZ-APP-FLUTTER/lib
|
mirrored_repositories/QUIZ-APP-FLUTTER/lib/components/HeadingText.dart
|
import 'package:flutter/material.dart';
class HeadingText extends StatelessWidget {
final String textToDisplay;
const HeadingText(this.textToDisplay);
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 20,bottom: 10,left: 10,right: 10),
child: Text(
"$textToDisplay",
style: TextStyle(
fontSize: 35.0,
fontWeight: FontWeight.bold,
color: Colors.red[700],
),
),
);
}
}
| 0
|
mirrored_repositories/QUIZ-APP-FLUTTER/lib
|
mirrored_repositories/QUIZ-APP-FLUTTER/lib/components/AnswerButton.dart
|
import 'package:flutter/material.dart';
import 'AnswerText.dart';
class AnswerButton extends StatelessWidget {
final bool isQuizStarted;
final Function checkAnswer;
final String optionText;
final double screenWidth;
AnswerButton(
this.optionText, this.isQuizStarted, this.checkAnswer, this.screenWidth);
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
child: MaterialButton(
minWidth: screenWidth,
onPressed: isQuizStarted ? () => checkAnswer("$optionText") : null,
color: Colors.lightBlue[800],
height: 50.0,
child: AnswerText("$optionText", screenWidth),
// child: Text(
// "$optionText",
// softWrap: true,
// style: TextStyle(
// fontSize: 24.0,
// // fontWeight: FontWeight.w700,
// color: Colors.white,
// ),
// ),
),
);
}
}
| 0
|
mirrored_repositories/QUIZ-APP-FLUTTER/lib
|
mirrored_repositories/QUIZ-APP-FLUTTER/lib/components/QuestionText.dart
|
import 'package:flutter/material.dart';
class QuestionText extends StatelessWidget {
final String textToDisplay;
final double screenWidth;
const QuestionText(this.textToDisplay,this.screenWidth);
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10),
width: screenWidth,
child: Text(
"$textToDisplay",
softWrap: true,
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
);
}
}
| 0
|
mirrored_repositories/QUIZ-APP-FLUTTER/lib
|
mirrored_repositories/QUIZ-APP-FLUTTER/lib/components/AnswerText.dart
|
import 'package:flutter/material.dart';
class AnswerText extends StatelessWidget {
final String textToDisplay;
final double screenWidth;
const AnswerText(this.textToDisplay,this.screenWidth);
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10),
width: screenWidth,
child: Text(
"$textToDisplay",
softWrap: true,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 23.0,
color: Colors.white,
),
),
);
}
}
| 0
|
mirrored_repositories/QUIZ-APP-FLUTTER
|
mirrored_repositories/QUIZ-APP-FLUTTER/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:quiz_app/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/OnBoarding_UI
|
mirrored_repositories/OnBoarding_UI/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:onboarding_ui/router/router_config.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
debugShowCheckedModeBanner: false,
theme: ThemeData.light(useMaterial3: true),
darkTheme: ThemeData.dark(useMaterial3: true),
themeMode: ThemeMode.system,
routeInformationParser: router.routeInformationParser,
routerDelegate: router.routerDelegate,
routeInformationProvider: router.routeInformationProvider,
);
}
}
| 0
|
mirrored_repositories/OnBoarding_UI/lib
|
mirrored_repositories/OnBoarding_UI/lib/router/router_config.dart
|
import 'package:flutter/cupertino.dart';
import 'package:go_router/go_router.dart';
import 'package:onboarding_ui/router/router.dart';
import 'package:onboarding_ui/screens/home_screen.dart';
import 'package:onboarding_ui/screens/onboarding_screen.dart';
final router = GoRouter(routes: [
GoRoute(path: Routers.homepage.path, name: Routers.homepage.name,pageBuilder: (context, state) {
return const CupertinoPage(child: HomePage());
},),
GoRoute(path: Routers.onboardingscreen.path, name: Routers.onboardingscreen.name, pageBuilder: (context, state) {
return const CupertinoPage(child: OnBoardingScreen());
},),
]);
| 0
|
mirrored_repositories/OnBoarding_UI/lib
|
mirrored_repositories/OnBoarding_UI/lib/router/router.dart
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
class AppRouter {
String name;
String path;
AppRouter({
required this.name,
required this.path,
});
}
class Routers {
static AppRouter onboardingscreen = AppRouter(name: "/OnBoard", path: "/");
static AppRouter homepage = AppRouter(name: "/home", path: "/home");
}
| 0
|
mirrored_repositories/OnBoarding_UI/lib
|
mirrored_repositories/OnBoarding_UI/lib/models/onboardingModel.dart
|
import 'dart:convert';
// ignore_for_file: public_member_api_docs, sort_constructors_first
class OnBoardModel {
String titel;
String desc;
String image;
OnBoardModel({
required this.titel,
required this.desc,
required this.image,
});
}
class Data {
List<OnBoardModel> list = [
OnBoardModel(titel: "30 days Meditation Challenge", desc: "100+ guided meditations covering anxiety, focus, stress, gratitude and more.", image: "assets/Meditation.png"),
OnBoardModel(titel: "Choose your top goal", desc: "Practice your breathing, relax your body, listen the calming sound music make you feel better.", image: "assets/Mask Group (1).png"),
OnBoardModel(titel: "Listen the calming music help you sleep", desc: "50+ music with the calming sound help you to fall asleep faster. Calm can change your life.", image: "assets/Mask Group (2).png"),
];
}
| 0
|
mirrored_repositories/OnBoarding_UI/lib
|
mirrored_repositories/OnBoarding_UI/lib/screens/onboarding_screen.dart
|
import 'dart:async';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:go_router/go_router.dart';
import 'package:onboarding_ui/models/onboardingModel.dart';
import 'package:onboarding_ui/router/router.dart';
import 'package:onboarding_ui/screens/home_screen.dart';
import 'package:page_transition/page_transition.dart';
import 'package:swipeable_button_view/swipeable_button_view.dart';
class OnBoardingScreen extends StatefulWidget {
const OnBoardingScreen({super.key});
@override
State<OnBoardingScreen> createState() => _OnBoardingScreenState();
}
class _OnBoardingScreenState extends State<OnBoardingScreen> {
@override
late PageController _pageController;
@override
void initState() {
super.initState();
_pageController = PageController(initialPage: 0);
autoswipe();
}
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
bool onLastPage = false;
bool onFirstPage = false;
bool isFinished = false;
int pageIndex = 0;
void autoswipe() {
Timer(Duration(seconds: 5), () {
if (pageIndex != 2) {
_pageController.nextPage(
duration: Duration(milliseconds: 500), curve: Curves.easeIn);
autoswipe();
}
});
}
Widget build(BuildContext context) {
Data info = Data();
return Scaffold(
// backgroundColor: Colors.white.withAlpha(2),
extendBodyBehindAppBar: true,
appBar: AppBar(
backgroundColor: Colors.transparent,
actions: [
const SizedBox(
width: 10,
),
onFirstPage
? IconButton(
onPressed: () {
GoRouter.of(context).pushNamed(Routers.homepage.name);
},
icon: const Icon(
Icons.close_rounded,
color: Colors.white,
size: 30,
))
: IconButton(
onPressed: () {
_pageController.previousPage(
duration: const Duration(milliseconds: 500),
curve: Curves.easeIn);
},
icon: const Icon(
Icons.arrow_back_ios_new,
color: Colors.white,
size: 30,
)),
const Spacer(),
IconButton(
onPressed: () {},
icon: const Icon(
CupertinoIcons.heart_fill,
color: Colors.white,
size: 30,
)),
const SizedBox(
width: 10,
)
],
),
body: Expanded(
flex: 3,
child: PageView.builder(
allowImplicitScrolling: false,
onPageChanged: (value) {
setState(() {
onLastPage = (value == 2);
onFirstPage = (value == 0);
pageIndex = value;
});
},
controller: _pageController,
dragStartBehavior: DragStartBehavior.down,
itemCount: info.list.length,
physics: ClampingScrollPhysics(),
pageSnapping: true,
scrollBehavior: const CupertinoScrollBehavior(),
itemBuilder: (context, index) {
var data = info.list[index];
return Stack(children: [
SvgPicture.asset(
"assets/blurry-gradient-haikei.svg",
fit: BoxFit.fill,
alignment: Alignment.center,
height: MediaQuery.of(context).size.height,
),
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
stops: [
0.3,
0.8
],
colors: [
Colors.lightBlueAccent.withOpacity(0.7),
// Colors.purpleAccent,
Colors.purple
]),
),
child: SafeArea(
child: Center(
child: Stack(children: [
Positioned(
top: 0,
right: -20,
child: Hero(
transitionOnUserGestures: true,
tag: "${data.titel}_cube",
child: Image.asset("assets/cube.png"))),
Positioned(
bottom: -30 +
(pageIndex ?? 1) * -180 +
(pageIndex ?? 2) * 300,
left: 10 +
(pageIndex ?? 1) * -30 +
(pageIndex ?? 2) * -50,
child: Hero(
tag: "${data.titel}_rightImage",
child: RotatedBox(
quarterTurns: pageIndex == 0
? 0
: pageIndex == 1
? 1
: 4,
child: Image.asset(
"assets/ring.png",
height: pageIndex == 0 ? 350 : 250,
opacity: const AlwaysStoppedAnimation(0.5),
),
),
)),
Positioned(
top: 80 +
(pageIndex ?? 1) * 0 +
(pageIndex ?? 2) * 160,
left: -160 +
(pageIndex ?? 1) * 300 +
(pageIndex ?? 2) * -120,
// left: -160,
child: Hero(
tag: "${data.titel}_leftImage",
child: Image.asset(
"assets/Clay_Purple0004.png",
filterQuality: FilterQuality.high,
opacity: const AlwaysStoppedAnimation(0.6),
scale: 1,
),
),
),
Align(
alignment: const Alignment(0, 0),
child: Column(
children: [
const SizedBox(
height: 15,
),
Container(
height: 300,
width: 300,
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
boxShadow: const [
BoxShadow(
blurStyle: BlurStyle.inner,
offset: Offset.zero,
color: Colors.grey,
blurRadius: 30,
spreadRadius: 0)
],
shape: BoxShape.circle,
image: DecorationImage(
image: AssetImage(data.image))),
),
const Spacer(),
Container(
height: 380,
width: 320,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
tileMode: TileMode.decal,
colors: [
Colors.white.withOpacity(0.3),
Colors.white.withOpacity(0.1),
Colors.white.withOpacity(0.01),
Colors.transparent.withOpacity(0.1),
Colors.transparent.withOpacity(0.04)
]),
),
child: Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
Text(
data.titel,
textAlign: TextAlign.left,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 35),
),
const Spacer(),
Text(
data.desc,
style: const TextStyle(
color: Colors.white70,
fontSize: 15,
fontWeight: FontWeight.w600),
),
const Spacer(),
onLastPage
?
// SwipeableButtonView(
// buttonText: 'Slide to Pay',
// buttontextstyle:
// const TextStyle(
// fontSize: 25,
// color: Colors.white),
// buttonWidget: const Icon(
// Icons
// .arrow_forward_ios_rounded,
// color: Colors.grey),
// activeColor:
// const Color(0xFF009C41),
// onWaitingProcess: () {
// // - - -
// // Amount of time the circular progress
// // indicator spins before navigating to next page
// //- - -
// Future.delayed(
// const Duration(
// seconds: 2),
// () => setState(() =>
// isFinished = true));
// },
// isFinished: isFinished,
// onFinish: () async {
// // - - - Navigate to confirmation page - - -
// await Navigator.push(
// context,
// PageTransition(
// type:
// PageTransitionType
// .fade,
// child:
// const HomePage()));
// // - - - Reset isFinished variable - - -
// setState(
// () => isFinished = false);
// },
// )
Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(
20),
color: const Color(
0xFF844FFC)),
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
PageTransition(
child:
const HomePage(),
type:
PageTransitionType
.fade));
// GoRouter.of(context)
// .pushNamed(Routers
// .homepage.name);
},
style: ButtonStyle(
backgroundColor:
const MaterialStatePropertyAll(
Colors
.transparent),
alignment:
Alignment.center,
padding:
const MaterialStatePropertyAll(
EdgeInsets.symmetric(
horizontal:
85,
vertical:
20)),
shape: MaterialStatePropertyAll(
RoundedRectangleBorder(
borderRadius:
BorderRadius
.circular(
20)))),
child: const Text(
"Get Started",
style: TextStyle(
color: Colors.white,
fontSize: 18),
)),
)
: Row(
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: [
TextButton(
onPressed: () {
setState(() {
_pageController
.jumpToPage(
2,
);
});
},
child: const Text(
"Skip",
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight:
FontWeight
.w700),
)),
ElevatedButton(
onPressed: () {
setState(() {
_pageController.nextPage(
duration:
const Duration(
milliseconds:
300),
curve: Curves
.easeIn);
});
},
child: const Text(
"Next",
style: TextStyle(
color: Colors.black,
fontSize: 18),
),
style: ButtonStyle(
shape:
MaterialStatePropertyAll(
RoundedRectangleBorder(
borderRadius:
BorderRadius
.circular(
20)),
),
padding:
const MaterialStatePropertyAll(
EdgeInsets.only(
top: 20,
bottom:
20,
right: 30,
left:
30)))),
],
),
const Spacer(),
Row(
children: [
const Spacer(),
...List.generate(
info.list.length,
(index) => Padding(
padding:
const EdgeInsets.only(
right: 12),
child: DotIndicator(
isActive:
index == pageIndex,
),
)),
const Spacer(),
],
)
],
),
),
),
),
const Spacer()
],
),
),
]),
),
),
),
]);
}),
),
);
}
}
class DotIndicator extends StatelessWidget {
final bool isActive;
DotIndicator({
this.isActive = false,
super.key,
});
@override
Widget build(BuildContext context) {
return AnimatedContainer(
height: 12,
width: 12,
duration: const Duration(milliseconds: 300),
decoration: BoxDecoration(
color: isActive ? Colors.white : Colors.grey, shape: BoxShape.circle),
);
}
}
| 0
|
mirrored_repositories/OnBoarding_UI/lib
|
mirrored_repositories/OnBoarding_UI/lib/screens/home_screen.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
appBar: AppBar(
iconTheme: const CupertinoIconThemeData(color: Colors.white, size: 30),
backgroundColor: Colors.transparent,
actions: [
IconButton(
onPressed: () {},
icon: const Icon(
CupertinoIcons.heart_fill,
color: Colors.white,
))
],
),
backgroundColor: const Color(0xFF844FFC),
body: const SafeArea(
child: SafeArea(
child: Center(
child: Text(
"Home Page ",
style: TextStyle(
fontSize: 40, color: Colors.white, fontWeight: FontWeight.bold),
),
))),
);
}
}
| 0
|
mirrored_repositories/OnBoarding_UI/lib
|
mirrored_repositories/OnBoarding_UI/lib/screens/save_onboard.dart
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:io';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:onboarding_ui/models/onboardingModel.dart';
class OnBoardingScreen extends StatefulWidget {
const OnBoardingScreen({super.key});
@override
State<OnBoardingScreen> createState() => _OnBoardingScreenState();
}
class _OnBoardingScreenState extends State<OnBoardingScreen> {
late PageController _pageController;
@override
void initState() {
_pageController = PageController(initialPage: 0);
super.initState();
}
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
Data info = Data();
return Scaffold(
extendBodyBehindAppBar: true,
appBar: AppBar(
backgroundColor: Colors.transparent,
actions: [
const SizedBox(
width: 10,
),
IconButton(
onPressed: () {},
icon: const Icon(
Icons.close_rounded,
color: Colors.white,
size: 30,
)),
const Spacer(),
IconButton(
onPressed: () {},
icon: const Icon(
CupertinoIcons.heart_fill,
color: Colors.white,
size: 30,
)),
const SizedBox(
width: 10,
)
],
elevation: 0,
),
body: PageView.builder(
allowImplicitScrolling: false,
controller: _pageController,
itemCount: info.list.length,
itemBuilder: (context, index) {
var data = info.list[index];
return OnBoardingComponent(
title: data.titel,
desc: data.desc,
image: data.image,
);
}));
}
}
class OnBoardingComponent extends StatefulWidget {
String title, desc, image;
OnBoardingComponent({
required this.title,
required this.desc,
required this.image,
super.key,
});
@override
State<OnBoardingComponent> createState() => _OnBoardingComponentState();
}
class _OnBoardingComponentState extends State<OnBoardingComponent> {
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
stops: [0.3, 0.8],
colors: [Colors.blue.withOpacity(0.6), Colors.purple])),
child: SafeArea(
child: Center(
child: Stack(children: [
Positioned(
top: -20, right: -10, child: Image.asset("assets/cube.png")),
Positioned(
bottom: -30,
right: -70,
child: Image.asset(
"assets/ring.png",
opacity: const AlwaysStoppedAnimation(0.5),
)),
Positioned(
top: 80,
left: -160,
child: Image.asset(
"assets/Clay_Purple0004.png",
filterQuality: FilterQuality.high,
opacity: const AlwaysStoppedAnimation(0.6),
scale: 1,
)),
Align(
alignment: const Alignment(0, 0),
child: Column(
children: [
Container(
height: 300,
width: 300,
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
offset: Offset.zero,
color: Colors.grey,
blurRadius: 30,
spreadRadius: 0)
],
shape: BoxShape.circle,
image:
DecorationImage(image: AssetImage(widget.image))),
),
const Spacer(),
Container(
height: 380,
width: 320,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Colors.transparent.withOpacity(0.2)),
child: Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
Text(
widget.title,
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 35),
),
const Spacer(),
Text(
widget.desc,
style: TextStyle(
color: Colors.white70,
fontSize: 15,
fontWeight: FontWeight.w600),
),
const Spacer(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton(
onPressed: () {},
child: const Text(
"Skip",
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w700),
)),
ElevatedButton(
onPressed: () {
setState(() {});
},
child: const Text(
"Next",
style: TextStyle(
color: Colors.black, fontSize: 18),
),
style: ButtonStyle(
shape: MaterialStatePropertyAll(
RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(20)),
),
padding: const MaterialStatePropertyAll(
EdgeInsets.only(
top: 20,
bottom: 20,
right: 30,
left: 30)))),
],
),
const Spacer(),
AnimatedContainer(
height: 10,
width: 10,
duration: const Duration(milliseconds: 300),
)
],
),
),
),
),
const Spacer()
],
),
),
]),
),
),
);
}
}
| 0
|
mirrored_repositories/OnBoarding_UI
|
mirrored_repositories/OnBoarding_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 in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:onboarding_ui/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0
|
mirrored_repositories/trashpick
|
mirrored_repositories/trashpick/lib/main.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:trashpick/Pages/BottomNavBar/PickMyTrash/pick_trash_location.dart';
import 'Pages/OnAppStart/welcome_page.dart';
import './Theme/theme_provider.dart';
import './Pages/BottomNavBar/bottom_nav_bar.dart';
import 'Pages/OnAppStart/check_permissions.dart';
import 'Pages/OnAppStart/sign_in_page.dart';
bool allPermissions = false;
final user = FirebaseAuth.instance.currentUser;
String accountType;
Future<void> geAccountType() async {
print("----------------------- CHECK ACCOUNT TYPE -----------------------");
await FirebaseFirestore.instance
.collection('Users')
.doc(user.uid)
.get()
.then((value) {
accountType = value.data()["accountType"];
print("----------------------- $accountType -----------------------");
});
}
_checkPermissionStatus() async {
print("----------------------- CHECK PERMISSION STATUS CALLED!");
var locationPermissionStatus = await Permission.location.status;
var cameraPermissionStatus = await Permission.camera.status;
var storagePermissionStatus = await Permission.storage.status;
if (locationPermissionStatus.isUndetermined &&
cameraPermissionStatus.isUndetermined &&
storagePermissionStatus.isUndetermined) {
print("ALL (LOCATION, CAMERA, STORAGE) PERMISSION DIDN'T ASK YET");
} else if (locationPermissionStatus.isGranted &&
cameraPermissionStatus.isGranted &&
storagePermissionStatus.isGranted) {
print("ALL (LOCATION, CAMERA, STORAGE) PERMISSION IS GRANTED!");
allPermissions = true;
} else if (locationPermissionStatus.isDenied) {
print("LOCATION PERMISSION DENIED!");
} else if (cameraPermissionStatus.isDenied) {
print("CAMERA PERMISSION DENIED!");
} else if (storagePermissionStatus.isDenied) {
print("STORAGE PERMISSION DENIED!");
} else if (locationPermissionStatus.isRestricted) {
print("LOCATION PERMISSION RESTRICTED!");
} else if (cameraPermissionStatus.isRestricted) {
print("CAMERA PERMISSION RESTRICTED!");
} else if (storagePermissionStatus.isRestricted) {
print("STORAGE PERMISSION RESTRICTED!");
} else if (!locationPermissionStatus.isGranted) {
print("LOCATION PERMISSION IS NOT GRANTED!");
} else if (!cameraPermissionStatus.isGranted) {
print("CAMERA PERMISSION IS NOT GRANTED!");
} else if (!storagePermissionStatus.isGranted) {
print("STORAGE PERMISSION IS NOT GRANTED!");
} else {
allPermissions = false;
}
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
print("----------------------- MAIN METHOD RUN -----------------------");
await _checkPermissionStatus();
await Firebase.initializeApp();
if (user != null) {
await geAccountType();
}
await SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(
//systemNavigationBarColor: Colors.blue,
statusBarColor: Colors.green.shade900,
//statusBarIconBrightness: Brightness.light
),
);
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
static const String title = 'TrashPick';
_mainPage() {
print(
"------------------ All Permissions: $allPermissions ------------------");
print("----------------------- USER: $user ------------------");
if (allPermissions == true) {
if (user == null) {
print("----------------------- SWITCH: WelcomePage ------------------");
//return TestTheme(title: title);
//return BottomNavBar(title: title);
return WelcomePage();
} else {
print("----------------------- SWITCH: BottomBar ------------------");
return BottomNavBar(accountType);
//return PickTrashLocation();
}
} else {
print(
"----------------------- SWITCH: CheckAppPermissions ------------------");
return CheckAppPermissions();
}
}
@override
Widget build(BuildContext context) => ChangeNotifierProvider(
create: (context) => ThemeProvider(),
builder: (context, _) {
final themeProvider = Provider.of<ThemeProvider>(context);
return MaterialApp(
title: title,
debugShowCheckedModeBanner: false,
themeMode: themeProvider.themeMode,
theme: AppThemeData.lightTheme,
darkTheme: AppThemeData.darkTheme,
home:
/*AnimatedSplashScreen(
splash: Image.asset(
'assets/images/trashpick_logo_2.png',
),
animationDuration: Duration(seconds: 2),
nextScreen: HomePage(title: title),
splashTransition: SplashTransition.fadeTransition,
),*/
_mainPage(),
);
},
);
}
| 0
|
mirrored_repositories/trashpick/lib
|
mirrored_repositories/trashpick/lib/Generators/uui_generator.dart
|
import 'package:uuid/uuid.dart';
import 'package:uuid/uuid_util.dart';
class UUIDGenerator {
// Generate a v1 (time-based) id -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'
String uuidV1() {
var uuid = Uuid();
var v1 = uuid.v1();
return v1.toString();
}
// Generate a v1Exact -> '710b962e-041c-11e1-9234-0123456789ab'
String uuidV1Exact() {
var uuid = Uuid();
var v1Exact = uuid.v1(options: {
'node': [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
'clockSeq': 0x1234,
'mSecs': DateTime.utc(2011, 11, 01).millisecondsSinceEpoch,
'nSecs': 5678
});
return v1Exact.toString();
}
// Generate a v4 (random) id -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'
String uuidV4() {
var uuid = Uuid();
var v4 = uuid.v4();
return v4.toString();
}
// Generate a v4 (crypto-random) id -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'
String uuidV4Crypto() {
var uuid = Uuid();
var v4Crypto = uuid.v4(options: {'rng': UuidUtil.cryptoRNG});
return v4Crypto.toString();
}
// Generate a v5 (namespace-name-sha1-based) id -> 'c74a196f-f19d-5ea9-bffd-a2742432fc9c'
String uuidV5() {
var uuid = Uuid();
var v5 = uuid.v5(Uuid.NAMESPACE_URL, 'www.google.com');
return v5.toString();
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/bottom_nav_bar.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:trashpick/Models/user_model.dart';
import 'package:trashpick/Pages/BottomNavBar/PickMyTrash/pick_my_trash_page.dart';
import 'package:trashpick/Pages/BottomNavBar/TrashToBeCollected/trash_to_be_collected_page.dart';
import '../../Theme/theme_provider.dart';
import 'Home/home_page.dart';
import 'BeAware/be_aware.dart';
import 'RecyclingCenters/recycling_centers_page.dart';
import 'Settings/settings_page.dart';
class BottomNavBar extends StatefulWidget {
final String accountType;
BottomNavBar(this.accountType);
@override
_BottomNavBarState createState() => _BottomNavBarState();
}
class _BottomNavBarState extends State<BottomNavBar> {
int _selectedPage = 0;
List<Widget> pageList = [];
String uuid = FirebaseAuth.instance.currentUser.uid.toString();
@override
void initState() {
checkAccountType();
super.initState();
}
List<BottomNavigationBarItem> appBottomNavBarItems =
const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(
Icons.home_rounded,
size: 30.0,
),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(
Icons.transfer_within_a_station_rounded,
size: 30.0,
),
label: 'Trash to be collected',
),
BottomNavigationBarItem(
icon: Icon(
Icons.restore_from_trash,
size: 30.0,
),
label: 'Recycling Centers',
),
BottomNavigationBarItem(
icon: Icon(
Icons.notifications_rounded,
size: 30.0,
),
label: 'Be Aware',
),
BottomNavigationBarItem(
icon: Icon(
Icons.settings_rounded,
size: 30.0,
),
label: 'My Profile',
),
];
appBottomNavBar() {
return BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: _selectedPage,
showSelectedLabels: false,
showUnselectedLabels: false,
selectedItemColor: AppThemeData().primaryColor,
unselectedItemColor: AppThemeData().greyColor,
onTap: _onItemTapped,
items: appBottomNavBarItems,
);
}
checkAccountType() async {
pageList.add(HomePage(widget.accountType));
print(
"----------------------- SWITCH TAB FOR ACCOUNT TYPE: ${widget.accountType} -----------------------");
if (widget.accountType == "Trash Picker") {
print("Current User Account Type: Trash Picker");
pageList.add(PickMyTrash(widget.accountType));
} else {
print("Current User Account Type: Trash Collector");
pageList.add(TrashToBeCollected());
}
pageList.add(RecyclingCenters());
pageList.add(BeAware());
pageList.add(SettingsPage());
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => showDialog<bool>(
context: context,
builder: (c) => AlertDialog(
title: Text('Exit from TrashPick'),
content: Text('Do you really want to exit'),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10.0))),
actions: [
TextButton(
child: Text('Yes'),
onPressed: () => Navigator.pop(c, true),
),
TextButton(
child: Text('No'),
onPressed: () => Navigator.pop(c, false),
),
],
)),
child: Scaffold(
backgroundColor: AppThemeData().whiteColor,
body: IndexedStack(
index: _selectedPage,
children: pageList,
),
bottomNavigationBar: appBottomNavBar()),
);
}
void _onItemTapped(int index) {
setState(() {
_selectedPage = index;
});
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/TrashToBeCollected/trash_to_be_collected_list.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:trashpick/Models/trash_pick_ups_model.dart';
import 'package:trashpick/Models/user_model.dart';
import 'package:trashpick/Pages/BottomNavBar/PickMyTrash/pick_my_trash_page.dart';
import 'package:trashpick/Pages/BottomNavBar/PickMyTrash/view_trash_details.dart';
import 'package:trashpick/Theme/theme_provider.dart';
import 'package:trashpick/Widgets/button_widgets.dart';
class TrashToBeCollectedList extends StatefulWidget {
@override
_TrashToBeCollectedListState createState() => _TrashToBeCollectedListState();
}
class _TrashToBeCollectedListState extends State<TrashToBeCollectedList> {
final firestoreInstance = FirebaseFirestore.instance;
TrashPickUpsModel trashPickUpsModel;
UserModelClass selectedTrashPickerModel;
String accountType = "Trash Collector";
bool viewTrashPicker = false;
@override
void initState() {
super.initState();
}
loadingProgress() {
return Container(
child: Center(
child: SizedBox(
child: CircularProgressIndicator(),
height: 40.0,
width: 40.0,
),
),
);
}
Widget trashPickersDetailsCard(
AsyncSnapshot<QuerySnapshot> snapshot, UserModelClass userModelClass) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: Container(
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Colors.grey.shade100,
child: InkWell(
splashColor: Colors.blue.withAlpha(30),
onTap: () {
print('Selected Trash: ${userModelClass.uuid}');
setState(() {
viewTrashPicker = true;
selectedTrashPickerModel = userModelClass;
});
},
child: snapshot.data.docs.length == null
? Container()
: Row(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: ClipOval(
child: Image.network(
userModelClass.profileImage,
fit: BoxFit.cover,
height: 80,
width: 80,
),
),
),
SizedBox(
width: 10.0,
),
Expanded(
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
userModelClass.name,
style: TextStyle(
fontSize: Theme.of(context)
.textTheme
.headline6
.fontSize,
fontWeight: FontWeight.w500,
color: Theme.of(context).primaryColor),
),
SizedBox(
height: 5.0,
),
Text(
userModelClass.homeAddress,
textAlign: TextAlign.start,
style: TextStyle(
color: AppThemeData
.lightTheme.iconTheme.color),
),
],
),
),
),
],
),
),
),
),
);
}
_trashPickersList() {
return Container(
height: MediaQuery.of(context).size.height * 0.75,
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("Users")
.where('accountType', isEqualTo: "Trash Picker")
//.orderBy('name',descending: false)
.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return loadingProgress();
}
return !snapshot.hasData
? Container()
: snapshot.data.docs.length.toString() == "0"
? Container(
height: 250.0,
width: 200.0,
child: Column(
children: [
SizedBox(
height: 30.0,
),
Text(
"No Trash Pickers registered yet",
style: TextStyle(
fontSize: Theme.of(context)
.textTheme
.headline6
.fontSize),
),
ClipOval(
child: Image.asset(
'assets/images/trashpick_user_avatar.png',
height: 60.0,
width: 60.0,
),
),
],
),
)
: ListView.builder(
scrollDirection: Axis.vertical,
physics: BouncingScrollPhysics(),
itemCount: snapshot.data.docs.length,
itemBuilder: (BuildContext context, int index) {
UserModelClass userModelClass =
UserModelClass.fromDocument(
snapshot.data.docs[index]);
return trashPickersDetailsCard(
snapshot, userModelClass);
},
);
},
),
);
}
getAllTrashPickUps() {
FirebaseFirestore.instance.collection("Users").get().then((querySnapshot) {
querySnapshot.docs.forEach((result) {
FirebaseFirestore.instance
.collection("Users")
.doc(result.id)
.collection("Trash Pick Ups")
.get()
.then((querySnapshot) {
querySnapshot.docs.forEach((result) {
TrashPickUpsModel trashPickUpsModel =
TrashPickUpsModel.fromDocument(result);
print("--------------------- Trash Pick Ups ---------------------\n"
"id: ${trashPickUpsModel.trashID}\n"
"name: ${trashPickUpsModel.trashName}\n"
"image: ${trashPickUpsModel.trashImage}");
});
});
});
});
}
_selectedTrashPicker() {
return Column(
children: [
SizedBox(
height: 10.0,
),
Row(
children: [
IconButton(
icon: Icon(Icons.arrow_back_ios_rounded),
onPressed: () {
setState(() {
viewTrashPicker = false;
});
},
),
Text(
"${selectedTrashPickerModel.name}'s Trash Pick Ups",
style: Theme.of(context).textTheme.bodyText2,
),
],
),
_scheduledTrashPicksList(
selectedTrashPickerModel.name, selectedTrashPickerModel.uuid),
],
);
}
Widget trashDetailsCard(AsyncSnapshot<QuerySnapshot> snapshot,
TrashPickUpsModel trashPickUpsModel, String userID) {
return Container(
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Colors.grey.shade100,
child: InkWell(
splashColor: Colors.blue.withAlpha(30),
onTap: () {
print('Selected Trash: ${trashPickUpsModel.trashID}');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ViewTrashDetails(
userID, trashPickUpsModel.trashID, "Trash Collector")),
);
},
child: snapshot.data.docs.length == null
? Container()
: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Image.network(
trashPickUpsModel.trashImage,
fit: BoxFit.cover,
height: 150,
width: 150,
),
),
SizedBox(
width: 10.0,
),
Expanded(
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
trashPickUpsModel.trashName,
style: TextStyle(
fontSize: Theme.of(context)
.textTheme
.headline6
.fontSize,
fontWeight: FontWeight.w500,
color: Theme.of(context).primaryColor),
),
Divider(
color: Theme.of(context).iconTheme.color,
),
Text(
trashPickUpsModel.trashDescription,
textAlign: TextAlign.start,
style: TextStyle(
color:
AppThemeData.lightTheme.iconTheme.color),
),
//Text(trashPickUpsModel.trashLocationAddress),
],
),
),
),
],
),
),
),
);
}
_scheduledTrashPicksList(String userName, String userID) {
return Container(
height: MediaQuery.of(context).size.height,
//color: Colors.red,
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("Users")
.doc(userID)
.collection('Trash Pick Ups')
.orderBy('postedDate', descending: true)
.snapshots(),
builder: (context, snapshot) {
return !snapshot.hasData
? Container()
: snapshot.data.docs.length.toString() == "0"
? Container(
height: 250.0,
width: 200.0,
child: Column(
children: [
SizedBox(
height: 30.0,
),
Text(
"$userName has no scheduled trash pick ups yet",
style: TextStyle(
fontSize: Theme.of(context)
.textTheme
.headline6
.fontSize),
),
Image.asset(
'assets/icons/icon_broom.png',
height: 100.0,
width: 100.0,
),
],
),
)
: ListView.builder(
scrollDirection: Axis.vertical,
physics: BouncingScrollPhysics(),
itemCount: snapshot.data.docs.length,
itemBuilder: (BuildContext context, int index) {
TrashPickUpsModel trashPickUpsModel =
TrashPickUpsModel.fromDocument(
snapshot.data.docs[index]);
return trashDetailsCard(
snapshot, trashPickUpsModel, userID);
},
);
},
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: Center(
child: viewTrashPicker
? Container(
child: _selectedTrashPicker(),
)
: Column(
children: [
SizedBox(
height: 10.0,
),
Text(
"Trash Pickers",
style: Theme.of(context).textTheme.bodyText2,
),
_trashPickersList(),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/TrashToBeCollected/trash_to_be_collected_page.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:trashpick/Models/trash_pick_ups_model.dart';
import 'package:trashpick/Pages/BottomNavBar/TrashToBeCollected/trash_to_be_collected_list.dart';
import 'package:trashpick/Theme/theme_provider.dart';
import 'package:trashpick/Widgets/toast_messages.dart';
import '../../../Widgets/primary_app_bar_widget.dart';
class TrashToBeCollected extends StatefulWidget {
@override
_TrashToBeCollectedState createState() => _TrashToBeCollectedState();
}
class _TrashToBeCollectedState extends State<TrashToBeCollected> {
Widget _childMap;
GoogleMapController _googleMapController;
Position _currentPosition;
String _currentAddress;
BitmapDescriptor currentUserMarkerIcon, mapRecyclingCenterMarkerIcon;
List eventLocations;
Map<MarkerId, Marker> currentUserMarker = <MarkerId, Marker>{};
Map<MarkerId, Marker> recyclingCentersMarkers = <MarkerId, Marker>{};
Set<Marker> _displayMapMarkers = Set();
final FirebaseAuth auth = FirebaseAuth.instance;
@override
void initState() {
_childMap = loadingMap("Loading Map...");
//checkLocationPermission();
_getCurrentUserLocation();
setCurrentUserMarkerIcon();
setMapRecyclingCentersMarkerIcon();
getRecyclingCentersLocation();
super.initState();
}
// ---------------------------------- CURRENT USER ---------------------------------- \\
_getCurrentUserLocation() {
try {
Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
forceAndroidLocationManager: true)
.then((Position position) {
setState(() {
_currentPosition = position;
_displayMapMarkers = Set<Marker>.of(currentUserMarker.values);
_childMap = mapWidget();
});
_getCurrentUserAddressFromLatLng();
}).catchError((e) {
print(e);
});
} catch (error) {
ToastMessages().toastError(error, context);
}
}
_getCurrentUserAddressFromLatLng() async {
try {
List<Placemark> p = await placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = p[0];
setState(() {
if (place != null) {
_currentAddress = "${place.name}, "
"${place.street}, "
"${place.locality}, "
"${place.country}";
} else {
_currentAddress = "No Address";
}
_childMap = mapWidget();
});
} catch (error) {
ToastMessages().toastError(error, context);
}
}
setCurrentUserMarkerIcon() async {
currentUserMarkerIcon = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(devicePixelRatio: 5.0),
'assets/icons/icon_home.png');
}
_setCurrentUserMarker() {
return <Marker>[
Marker(
markerId: MarkerId('MyCurrentLocation'),
position:
LatLng(_currentPosition.latitude, _currentPosition.longitude),
icon: currentUserMarkerIcon,
onTap: () {
print('My Location');
},
infoWindow:
InfoWindow(title: 'My Location', snippet: _currentAddress))
].toSet();
}
// ---------------------------------- Recycling Centers ---------------------------------- \\
setMapRecyclingCentersMarkerIcon() async {
mapRecyclingCenterMarkerIcon = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(devicePixelRatio: 50.0),
'assets/icons/icon_bin.png');
}
getRecyclingCentersLocation() {
FirebaseFirestore.instance.collection("Users").get().then((querySnapshot) {
querySnapshot.docs.forEach((result) {
FirebaseFirestore.instance
.collection("Users")
.doc(result.id)
.collection("Trash Pick Ups")
.get()
.then((querySnapshot) {
if (querySnapshot.docs.isNotEmpty) {
querySnapshot.docs.forEach((result) {
TrashPickUpsModel trashPickUpsModel =
TrashPickUpsModel.fromDocument(result);
print(
"--------------------- Recycling Center ---------------------\n"
"id: ${trashPickUpsModel.trashID}\n"
"name: ${trashPickUpsModel.trashName}\n"
"latitude: ${trashPickUpsModel.trashLocationLocation.latitude}\n"
"longitude: ${trashPickUpsModel.trashLocationLocation.longitude}");
setRecyclingCentersMarkers(
trashPickUpsModel.trashID,
trashPickUpsModel.trashName,
trashPickUpsModel.trashLocationLocation.latitude,
trashPickUpsModel.trashLocationLocation.longitude,
);
});
}
});
});
});
}
setRecyclingCentersMarkers(
id,
name,
latitude,
longitude,
) async {
final MarkerId markerID = MarkerId(id);
final Marker marker = Marker(
markerId: markerID,
icon: mapRecyclingCenterMarkerIcon,
position: LatLng(latitude, longitude),
infoWindow: InfoWindow(
title: name,
onTap: () {
/*showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return MarkerDetailsCard().showEventDetails(
id,
name,
location
context);
},
);*/
print("id: $id\n"
"name:$name\n"
"latitude: $latitude\n"
"longitude: $longitude");
}),
);
setState(() {
recyclingCentersMarkers[markerID] = marker;
_displayMapMarkers = Set<Marker>.of(recyclingCentersMarkers.values);
_childMap = mapWidget();
//print("Recycling Center MarkerID: $markerID");
});
}
// ---------------------------------- COMMON MAP ---------------------------------- \\
loadingMap(String m) {
return Center(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 100.0, horizontal: 100.0),
child: Text(
m,
style: TextStyle(fontSize: 16.0),
textAlign: TextAlign.center,
),
),
);
}
checkLocationPermission() async {
LocationPermission permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied ||
permission == LocationPermission.deniedForever) {
await Geolocator.openAppSettings();
await Geolocator.openLocationSettings();
} else {
_getCurrentUserLocation();
//ToastMessages().toastInfo("Location Permission Granted!");
}
}
Widget mapWidget() {
return GoogleMap(
mapType: MapType.normal,
markers: _displayMapMarkers,
myLocationEnabled: true,
myLocationButtonEnabled: true,
zoomControlsEnabled: true,
initialCameraPosition: CameraPosition(
target: LatLng(_currentPosition.latitude, _currentPosition.longitude),
zoom: 8.5,
),
onMapCreated: (GoogleMapController controller) {
_googleMapController = controller;
},
);
}
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).appBarTheme.backgroundColor,
automaticallyImplyLeading: false,
title: Text(
"Trash To Be Collected",
style: Theme.of(context).textTheme.headline6,
),
elevation: Theme.of(context).appBarTheme.elevation,
actions: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: Icon(
Icons.transfer_within_a_station_rounded,
color: AppThemeData().secondaryColor,
size: 35.0,
),
)
],
bottom: TabBar(
tabs: [
Tab(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
"Trash List",
style: Theme.of(context).textTheme.subtitle1,
),
Icon(
Icons.list_alt_rounded,
color: Theme.of(context).iconTheme.color,
),
],
),
),
Tab(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
"Map View",
style: Theme.of(context).textTheme.subtitle1,
),
Icon(Icons.map_rounded,
color: Theme.of(context).iconTheme.color),
],
),
),
],
),
),
body: TabBarView(
physics: NeverScrollableScrollPhysics(),
children: [
TrashToBeCollectedList(),
Container(
child: _childMap,
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/BeAware/read_article.dart
|
import 'package:flutter/material.dart';
import 'package:trashpick/Theme/theme_provider.dart';
import 'package:trashpick/Widgets/primary_app_bar_widget.dart';
import 'package:trashpick/Widgets/secondary_app_bar_widget.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:io';
class ReadArticle extends StatefulWidget {
final String articleLink;
ReadArticle(this.articleLink);
@override
_ReadArticleState createState() => _ReadArticleState();
}
class _ReadArticleState extends State<ReadArticle> {
final _key = UniqueKey();
bool isLoading = true;
@override
void initState() {
super.initState();
if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: SecondaryAppBar(
title: "Article from Website",
appBar: AppBar(),
widgets: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: Icon(
Icons.notifications_rounded,
color: AppThemeData().secondaryColor,
size: 35.0,
),
)
],
),
body: SafeArea(
child: Stack(
children: [
WebView(
key: _key,
initialUrl: widget.articleLink,
javascriptMode: JavascriptMode.unrestricted,
onPageFinished: (finish) {
setState(() {
isLoading = false;
});
},
),
isLoading
? Center(
child: CircularProgressIndicator(),
)
: Stack(),
],
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/BeAware/be_aware.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:trashpick/Models/articles_model.dart';
import 'package:trashpick/Pages/BottomNavBar/BeAware/read_article.dart';
import 'package:trashpick/Theme/theme_provider.dart';
import 'package:trashpick/Widgets/button_widgets.dart';
import '../../../Widgets/primary_app_bar_widget.dart';
class BeAware extends StatefulWidget {
@override
_BeAwareState createState() => _BeAwareState();
}
class _BeAwareState extends State<BeAware> {
int documents;
@override
void initState() {
getTotalArticles();
super.initState();
}
getTotalArticles() async {
final QuerySnapshot qSnap =
await FirebaseFirestore.instance.collection('Articles').get();
documents = qSnap.docs.length;
print(
"----------------------- TOTAL ARTICLES: $documents -----------------------");
}
@override
Widget build(BuildContext context) {
Widget articleDetailsCard(
AsyncSnapshot<QuerySnapshot> snapshot, ArticlesModel articlesModel) {
return Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Colors.grey.shade100,
child: InkWell(
splashColor: Colors.blue.withAlpha(30),
onTap: () {
print('Selected Article: ${articlesModel.articleID}');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ReadArticle(articlesModel.articleLink)),
);
},
child: snapshot.data.docs.length == null
? Container()
: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Image.network(
articlesModel.articleImage,
fit: BoxFit.cover,
height: 150,
width: 150,
),
),
SizedBox(
width: 10.0,
),
Expanded(
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
articlesModel.articleTitle,
style: TextStyle(
fontSize: Theme.of(context)
.textTheme
.headline6
.fontSize,
fontWeight: FontWeight.w500,
color: Theme.of(context).primaryColor),
),
Divider(
color: Theme.of(context).iconTheme.color,
),
Text(
articlesModel.articleDescription,
textAlign: TextAlign.start,
style: TextStyle(
color: AppThemeData
.lightTheme.iconTheme.color),
),
//Text(trashPickUpsModel.trashLocationAddress),
],
),
),
),
],
),
),
),
),
);
}
_articlesList() {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("Articles")
.orderBy('articlePostedDate', descending: true)
.snapshots(),
builder: (context, snapshot) {
return !snapshot.hasData
? Container()
: snapshot.data.docs.length.toString() == "0"
? Container(
height: 250.0,
width: 200.0,
child: Column(
children: [
SizedBox(
height: 30.0,
),
Text(
"You have no articles yet",
style: TextStyle(
fontSize: Theme.of(context)
.textTheme
.headline6
.fontSize),
),
Image.asset(
'assets/icons/icon_broom.png',
height: 100.0,
width: 100.0,
),
],
),
)
: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: BouncingScrollPhysics(),
itemCount: snapshot.data.docs.length,
itemBuilder: (BuildContext context, int index) {
ArticlesModel articlesModel =
ArticlesModel.fromDocument(
snapshot.data.docs[index]);
return articleDetailsCard(snapshot, articlesModel);
},
);
},
);
}
return Scaffold(
appBar: PrimaryAppBar(
title: "Be Aware",
appBar: AppBar(),
widgets: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: Icon(
Icons.notifications_rounded,
color: AppThemeData().secondaryColor,
size: 35.0,
),
)
],
),
body: SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"TrashPick Articles",
style: TextStyle(
fontSize: Theme.of(context).textTheme.headline6.fontSize,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 20.0,
),
_articlesList(),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/RecyclingCenters/recyling_centers_bottom_sheet.dart
|
import 'package:flutter/material.dart';
import 'package:trashpick/Models/recycling_center_model.dart';
class RecyclingCentersBottomSheet {
detailsTitle(BuildContext context, String detailsTitle) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 2.0),
child: Text(
detailsTitle,
style: TextStyle(
color: Theme.of(context).textTheme.subtitle2.color,
fontSize: Theme.of(context).textTheme.subtitle2.fontSize,
fontWeight: FontWeight.bold),
),
);
}
detailsName(BuildContext context, String detailsName) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 2.0),
child: Text(
detailsName,
style: TextStyle(
color: Theme.of(context).textTheme.subtitle2.color,
fontSize: Theme.of(context).textTheme.subtitle2.fontSize,
fontWeight: FontWeight.normal),
),
);
}
showCentersDetails(BuildContext context,
RecyclingCenterModel recyclingCenterModel, var latitude, var longitude) {
return SingleChildScrollView(
child: Container(
color: Theme.of(context).appBarTheme.color,
child: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 14.0,
),
Text(
"Recycling Center",
style: TextStyle(
color:
Theme.of(context).textTheme.headline6.color,
fontSize: Theme.of(context)
.textTheme
.headline6
.fontSize,
fontWeight: FontWeight.bold),
),
],
),
IconButton(
icon: Icon(Icons.cancel_rounded),
onPressed: () => Navigator.pop(context),
)
],
),
SizedBox(
height: 5.0,
),
detailsTitle(context, "Name"),
detailsName(context, recyclingCenterModel.name),
SizedBox(
height: 5.0,
),
detailsTitle(context, "Phone"),
detailsName(context, recyclingCenterModel.phone),
SizedBox(
height: 5.0,
),
detailsTitle(context, "Address"),
detailsName(context, recyclingCenterModel.address),
SizedBox(
height: 10.0,
),
detailsTitle(context, "Latitude"),
detailsName(context, latitude.toString()),
SizedBox(
height: 5.0,
),
detailsTitle(context, "Longitude"),
detailsName(context, longitude.toString()),
/* SizedBox(
height: 5.0,
),
detailsTitle(context, "Street"),
detailsName(context, street),
SizedBox(
height: 5.0,
),
detailsTitle(context, "Postal Code"),
detailsName(context, postalCode),
SizedBox(
height: 5.0,
),
detailsTitle(context, "Administrative Area"),
detailsName(context, administrativeArea),
SizedBox(
height: 5.0,
),
detailsTitle(context, "Sub Administrative Area"),
detailsName(context, subAdministrativeArea),
SizedBox(
height: 5.0,
),
detailsTitle(context, "Thoroughfare"),
detailsName(context, thoroughfare),
SizedBox(
height: 5.0,
),
detailsTitle(context, "Sub Thoroughfare"),
detailsName(context, subThoroughfare),
SizedBox(
height: 5.0,
),
detailsTitle(context, "Locality"),
detailsName(context, locality),
SizedBox(
height: 5.0,
),
detailsTitle(context, "Sub Locality"),
detailsName(context, subLocality),
SizedBox(
height: 5.0,
),
detailsTitle(context, "Country"),
detailsName(context, country),
SizedBox(
height: 5.0,
),
detailsTitle(context, "ISO Country Code"),
detailsName(context, isoCountryCode),*/
SizedBox(
height: 80.0,
),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/RecyclingCenters/recycling_centers_page.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:trashpick/Models/recycling_center_model.dart';
import 'package:trashpick/Theme/theme_provider.dart';
import 'package:trashpick/Widgets/toast_messages.dart';
import '../../../Widgets/primary_app_bar_widget.dart';
import 'recycling_centers_list.dart';
import 'recyling_centers_bottom_sheet.dart';
class RecyclingCenters extends StatefulWidget {
@override
_RecyclingCentersState createState() => _RecyclingCentersState();
}
class _RecyclingCentersState extends State<RecyclingCenters> {
Widget _childMap;
GoogleMapController _googleMapController;
Position _currentPosition;
String _currentAddress;
BitmapDescriptor currentUserMarkerIcon, mapRecyclingCenterMarkerIcon;
List eventLocations;
Map<MarkerId, Marker> currentUserMarker = <MarkerId, Marker>{};
Map<MarkerId, Marker> recyclingCentersMarkers = <MarkerId, Marker>{};
Set<Marker> _displayMapMarkers = Set();
@override
void initState() {
_childMap = loadingMap("Loading Map...");
//checkLocationPermission();
_getCurrentUserLocation();
setCurrentUserMarkerIcon();
setMapRecyclingCentersMarkerIcon();
getRecyclingCentersLocation();
super.initState();
}
// ---------------------------------- CURRENT USER ---------------------------------- \\
_getCurrentUserLocation() {
try {
Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
forceAndroidLocationManager: true)
.then((Position position) {
setState(() {
_currentPosition = position;
_displayMapMarkers = Set<Marker>.of(currentUserMarker.values);
_childMap = mapWidget();
});
_getCurrentUserAddressFromLatLng();
}).catchError((e) {
print(e);
});
} catch (error) {
ToastMessages().toastError(error, context);
}
}
_getCurrentUserAddressFromLatLng() async {
try {
List<Placemark> p = await placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = p[0];
setState(() {
if (place != null) {
_currentAddress = "${place.name}, "
"${place.street}, "
"${place.locality}, "
"${place.country}";
} else {
_currentAddress = "No Address";
}
_childMap = mapWidget();
});
} catch (error) {
ToastMessages().toastError(error, context);
}
}
setCurrentUserMarkerIcon() async {
currentUserMarkerIcon = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(devicePixelRatio: 5.0),
'assets/icons/icon_home.png');
}
_setCurrentUserMarker() {
return <Marker>[
Marker(
markerId: MarkerId('MyCurrentLocation'),
position:
LatLng(_currentPosition.latitude, _currentPosition.longitude),
icon: currentUserMarkerIcon,
onTap: () {
print('My Location');
},
infoWindow:
InfoWindow(title: 'My Location', snippet: _currentAddress))
].toSet();
}
// ---------------------------------- Recycling Centers ---------------------------------- \\
setMapRecyclingCentersMarkerIcon() async {
mapRecyclingCenterMarkerIcon = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(devicePixelRatio: 50.0),
'assets/icons/icon_recycling_center.png');
}
getRecyclingCentersLocation() {
FirebaseFirestore.instance
.collection("Recycling Centers")
.get()
.then((querySnapshot) {
if (querySnapshot.docs.isNotEmpty) {
querySnapshot.docs.forEach((result) {
RecyclingCenterModel recyclingCenterModel =
RecyclingCenterModel.fromDocument(result);
print("--------------------- Recycling Center ---------------------\n"
"id: ${recyclingCenterModel.id}\n"
"name: ${recyclingCenterModel.name}\n"
"latitude: ${recyclingCenterModel.location.latitude}\n"
"longitude: ${recyclingCenterModel.location.longitude}");
setRecyclingCentersMarkers(
recyclingCenterModel,
recyclingCenterModel.location.latitude,
recyclingCenterModel.location.longitude,
);
});
}
});
}
setRecyclingCentersMarkers(
RecyclingCenterModel recyclingCenterModel,
latitude,
longitude,
) async {
final MarkerId markerID = MarkerId(recyclingCenterModel.id);
final Marker marker = Marker(
markerId: markerID,
icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueBlue),
position: LatLng(latitude, longitude),
infoWindow: InfoWindow(
title: recyclingCenterModel.name,
onTap: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return RecyclingCentersBottomSheet().showCentersDetails(
context, recyclingCenterModel, latitude, longitude);
},
);
print("id: ${recyclingCenterModel.id}\n"
"name:${recyclingCenterModel.name}\n"
"latitude: $latitude\n"
"longitude: $longitude");
}),
);
setState(() {
recyclingCentersMarkers[markerID] = marker;
_displayMapMarkers = Set<Marker>.of(recyclingCentersMarkers.values);
_childMap = mapWidget();
//print("Recycling Center MarkerID: $markerID");
});
}
// ---------------------------------- COMMON MAP ---------------------------------- \\
loadingMap(String m) {
return Center(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 100.0, horizontal: 100.0),
child: Text(
m,
style: TextStyle(fontSize: 16.0),
textAlign: TextAlign.center,
),
),
);
}
checkLocationPermission() async {
LocationPermission permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied ||
permission == LocationPermission.deniedForever) {
await Geolocator.openAppSettings();
await Geolocator.openLocationSettings();
} else {
_getCurrentUserLocation();
//ToastMessages().toastInfo("Location Permission Granted!");
}
}
Widget mapWidget() {
return GoogleMap(
mapType: MapType.normal,
markers: _displayMapMarkers,
myLocationEnabled: true,
myLocationButtonEnabled: true,
zoomControlsEnabled: true,
initialCameraPosition: CameraPosition(
target: LatLng(_currentPosition.latitude, _currentPosition.longitude),
zoom: 8.5,
),
onMapCreated: (GoogleMapController controller) {
_googleMapController = controller;
},
);
}
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).appBarTheme.backgroundColor,
automaticallyImplyLeading: false,
title: Text(
"Recycling Centers",
style: Theme.of(context).textTheme.headline6,
),
elevation: Theme.of(context).appBarTheme.elevation,
actions: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: Icon(
Icons.transfer_within_a_station_rounded,
color: AppThemeData().secondaryColor,
size: 35.0,
),
)
],
bottom: TabBar(
tabs: [
Tab(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
"Centers List",
style: Theme.of(context).textTheme.subtitle1,
),
Icon(
Icons.location_on_rounded,
color: Theme.of(context).iconTheme.color,
),
],
),
),
Tab(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
"Map View",
style: Theme.of(context).textTheme.subtitle1,
),
Icon(Icons.map_rounded,
color: Theme.of(context).iconTheme.color),
],
),
),
],
),
),
body: TabBarView(
physics: NeverScrollableScrollPhysics(),
children: [
RecyclingCentersList(),
Container(
child: _childMap,
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/RecyclingCenters/recycling_centers_list.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:trashpick/Models/recycling_center_model.dart';
import 'package:trashpick/Theme/theme_provider.dart';
class RecyclingCentersList extends StatefulWidget {
@override
_RecyclingCentersListState createState() => _RecyclingCentersListState();
}
class _RecyclingCentersListState extends State<RecyclingCentersList> {
final firestoreInstance = FirebaseFirestore.instance;
RecyclingCenterModel recyclingCenterModel;
String accountType = "Trash Collector";
bool viewTrashPicker = false;
@override
void initState() {
super.initState();
}
loadingProgress() {
return Container(
child: Center(
child: SizedBox(
child: CircularProgressIndicator(),
height: 40.0,
width: 40.0,
),
),
);
}
Widget recyclingCentersDetailsCard(AsyncSnapshot<QuerySnapshot> snapshot,
RecyclingCenterModel recyclingCenterModel) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: Container(
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Colors.grey.shade100,
child: InkWell(
splashColor: Colors.blue.withAlpha(30),
onTap: () {
print('Selected Trash: ${recyclingCenterModel.id}');
/* setState(() {
viewTrashPicker = true;
selectedTrashPickerModel = userModelClass;
});*/
},
child: snapshot.data.docs.length == null
? Container()
: Row(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: ClipOval(
child: Image.asset(
"assets/icons/icon_recycle.png",
fit: BoxFit.cover,
height: 80,
width: 80,
),
),
),
SizedBox(
width: 10.0,
),
Expanded(
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
recyclingCenterModel.name,
style: TextStyle(
fontSize: Theme.of(context)
.textTheme
.headline6
.fontSize,
fontWeight: FontWeight.w500,
color: Theme.of(context).primaryColor),
),
SizedBox(
height: 5.0,
),
Text(
recyclingCenterModel.address,
textAlign: TextAlign.start,
style: TextStyle(
color: AppThemeData
.lightTheme.iconTheme.color),
),
SizedBox(
height: 5.0,
),
Text(
recyclingCenterModel.phone,
textAlign: TextAlign.start,
style: TextStyle(
color: AppThemeData
.lightTheme.iconTheme.color),
),
],
),
),
),
],
),
),
),
),
);
}
_recyclingCentersList() {
return Container(
height: MediaQuery.of(context).size.height * 0.75,
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("Recycling Centers")
.orderBy('name', descending: false)
.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return loadingProgress();
}
return !snapshot.hasData
? Container()
: snapshot.data.docs.length.toString() == "0"
? Container(
height: 250.0,
width: 200.0,
child: Column(
children: [
SizedBox(
height: 30.0,
),
Text(
"No Recycling Centers yet",
style: TextStyle(
fontSize: Theme.of(context)
.textTheme
.headline6
.fontSize),
),
ClipOval(
child: Image.asset(
'assets/images/trashpick_user_avatar.png',
height: 60.0,
width: 60.0,
),
),
],
),
)
: ListView.builder(
scrollDirection: Axis.vertical,
physics: BouncingScrollPhysics(),
itemCount: snapshot.data.docs.length,
itemBuilder: (BuildContext context, int index) {
recyclingCenterModel =
RecyclingCenterModel.fromDocument(
snapshot.data.docs[index]);
return recyclingCentersDetailsCard(
snapshot, recyclingCenterModel);
},
);
},
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: Center(
child: Column(
children: [
SizedBox(
height: 10.0,
),
_recyclingCentersList(),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/Settings/give_feedback_page.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:trashpick/Generators/uui_generator.dart';
import 'package:trashpick/Theme/theme_provider.dart';
import 'package:trashpick/Widgets/button_widgets.dart';
import 'package:trashpick/Widgets/secondary_app_bar_widget.dart';
import 'package:trashpick/Widgets/toast_messages.dart';
class GiveFeedbackPage extends StatefulWidget {
@override
_GiveFeedbackPageState createState() => _GiveFeedbackPageState();
}
class _GiveFeedbackPageState extends State<GiveFeedbackPage> {
TextEditingController _giveFeedbackController = new TextEditingController();
int charLength = 0;
String formattedDate = DateFormat('dd-MM-yyyy').format(DateTime.now());
String formattedTime = DateFormat('kk:mm:a').format(DateTime.now());
// Uploading Process
bool isStartToUpload = false;
bool isUploadComplete = false;
bool isAnError = false;
double circularProgressVal;
_onChanged(String value) {
setState(() {
charLength = value.length;
});
}
// -------------------------------- UPLOADING PROCESS -------------------------------- \\
void ifAnError() {
Navigator.pop(context);
setState(() {
isStartToUpload = false;
isUploadComplete = false;
isAnError = true;
//Navigator.pop(context);
showAlertDialog(context);
});
}
void sendErrorCode(String error) {
ToastMessages().toastError(error, context);
ifAnError();
}
void sendSuccessCode() {
print("Feedback Send Success!");
Navigator.pop(context);
setState(() {
isStartToUpload = false;
isUploadComplete = true;
});
showAlertDialog(context);
}
showAlertDialog(BuildContext context) {
// show the dialog
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: !isUploadComplete
? Center(child: Text("Sending Feedback"))
: Center(child: Text("Feedback Send Success")),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (!isUploadComplete)
!isAnError
? Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30.0,
),
CircularProgressIndicator(
value: circularProgressVal,
strokeWidth: 6,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.teal.shade700),
),
SizedBox(
height: 30.0,
),
Text("Please wait until your feedback send.",
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 16.0)
.copyWith(color: Colors.grey.shade900)),
],
)
: Container(
child: Column(
children: [
Text("Error!",
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
)),
SizedBox(
height: 50.0,
),
new ButtonWidget(
text: "Try Again",
textColor: AppThemeData().whiteColor,
color: AppThemeData().primaryColor,
onClicked: () {
Navigator.pop(context);
}),
],
))
else
Center(
child: Padding(
padding: const EdgeInsets.only(top: 5.0),
child: Column(
children: [
Image.asset(
'assets/icons/icon_feedback.png',
height: 50,
width: 50,
),
SizedBox(height: 30),
Text("Feedback Successfully Send!",
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 22.0)
.copyWith(
color: Colors.grey.shade900,
fontWeight: FontWeight.bold)),
SizedBox(height: 50),
new ButtonWidget(
textColor: AppThemeData().whiteColor,
color: AppThemeData().secondaryColor,
text: "OK",
onClicked: () {
Navigator.pop(context);
},
)
],
),
),
)
],
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0))),
);
},
);
},
);
}
sendFeedback() {
FirebaseFirestore.instance
.collection('Feedbacks')
.doc("User Feedbacks")
.collection(FirebaseAuth.instance.currentUser.uid)
.doc(UUIDGenerator().uuidV1())
.set({
'feedback': _giveFeedbackController.text,
'postedDate': formattedDate + ", " + formattedTime,
})
.then(
(value) => sendSuccessCode(),
)
.catchError((error) => sendErrorCode(error.toString()));
}
void validateEdits() {
if (_giveFeedbackController.text.isEmpty) {
ToastMessages().toastError("Please enter feedback to send", context);
} else {
print(_giveFeedbackController.text);
sendFeedback();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: SecondaryAppBar(
title: "Give Feedback",
appBar: AppBar(),
widgets: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: Icon(
Icons.feedback_rounded,
color: Theme.of(context).iconTheme.color,
size: 35.0,
),
)
],
),
body: ListView(
children: [
SizedBox(
height: 20.0,
),
Image.asset(
'assets/logos/trashpick_logo_curved.png',
height: 150.0,
width: 150.0,
),
Padding(
padding: const EdgeInsets.all(20.0),
child: TextFormField(
controller: _giveFeedbackController,
style: TextStyle(fontWeight: FontWeight.normal),
decoration: InputDecoration(
contentPadding: EdgeInsets.fromLTRB(20.0, 40.0, 20.0, 10.0),
helperText: "No of letters: $charLength",
hintText: "Say something about your idea",
labelText: 'Type Your Feedback',
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: Colors.black,
width: 1.0,
),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.black,
width: 1.0,
),
),
labelStyle: TextStyle(
color: Colors.grey.shade900, fontWeight: FontWeight.bold),
),
onChanged: _onChanged,
maxLines: null,
keyboardType: TextInputType.multiline,
),
),
Padding(
padding: const EdgeInsets.all(20.0),
child: MinButtonWidget(
text: "Send Feedback",
color: AppThemeData().secondaryColor,
onClicked: () {
validateEdits();
},
),
),
],
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/Settings/settings_user_guide.dart
|
import 'package:flutter/material.dart';
import 'package:trashpick/Pages/OnAppStart/welcome_page.dart';
import 'package:webview_flutter/webview_flutter.dart';
class SettingsUserGuide extends StatefulWidget {
@override
_SettingsUserGuideState createState() => _SettingsUserGuideState();
}
class _SettingsUserGuideState extends State<SettingsUserGuide> {
final _key = UniqueKey();
bool isLoading = true;
String siteLink =
"https://sites.google.com/view/trashpick--app-user-guide/home";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).appBarTheme.backgroundColor,
leading: IconButton(
icon: Icon(Icons.arrow_back_ios_rounded,
color: Theme.of(context).iconTheme.color),
onPressed: () {
print("Go to Welcome Page");
Navigator.pop(context);
},
),
title: Text(
"User Guide",
style: Theme.of(context).textTheme.headline6,
),
elevation: Theme.of(context).appBarTheme.elevation,
),
body: SafeArea(
child: Stack(
children: [
WebView(
key: _key,
initialUrl: siteLink,
javascriptMode: JavascriptMode.unrestricted,
onPageFinished: (finish) {
setState(() {
isLoading = false;
});
},
),
isLoading
? Center(
child: CircularProgressIndicator(),
)
: Stack(),
],
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/Settings/profile_info_page.dart
|
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:trashpick/Models/user_model.dart';
import 'package:trashpick/Theme/theme_provider.dart';
import 'package:trashpick/Widgets/button_widgets.dart';
import 'package:trashpick/Widgets/image_frames_widgets.dart';
import 'package:trashpick/Widgets/secondary_app_bar_widget.dart';
import 'package:trashpick/Widgets/toast_messages.dart';
class ProfileInfoPage extends StatefulWidget {
@override
_ProfileInfoPageState createState() => _ProfileInfoPageState();
}
class _ProfileInfoPageState extends State<ProfileInfoPage> {
var currentUserID = FirebaseAuth.instance.currentUser.uid;
CollectionReference imgRef;
firebase_storage.Reference ref;
File _userSelectedFileImage;
String firebaseStorageUploadedImageURL;
String _userLatestProfileImage;
// Uploading Process
bool isStartToUpload = false;
bool isUploadComplete = false;
bool isAnError = false;
double circularProgressVal;
// -------------------------------- UPLOADING PROCESS -------------------------------- \\
void ifAnError() {
Navigator.pop(context);
setState(() {
isStartToUpload = false;
isUploadComplete = false;
isAnError = true;
//Navigator.pop(context);
showAlertDialog(context);
});
}
void sendErrorCode(String error) {
ToastMessages().toastError(error, context);
ifAnError();
}
void sendSuccessCode() {
print("Profile Update Success!");
Navigator.pop(context);
setState(() {
isStartToUpload = false;
isUploadComplete = true;
});
showAlertDialog(context);
}
showAlertDialog(BuildContext context) {
// show the dialog
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: !isUploadComplete
? Center(child: Text("Updating Profile"))
: Center(child: Text("Profile Updated")),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (!isUploadComplete)
!isAnError
? Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30.0,
),
CircularProgressIndicator(
value: circularProgressVal,
strokeWidth: 6,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.teal.shade700),
),
SizedBox(
height: 30.0,
),
Text("Please wait until your profile is update.",
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 16.0)
.copyWith(color: Colors.grey.shade900)),
],
)
: Container(
child: Column(
children: [
Text("Error!",
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
)),
SizedBox(
height: 50.0,
),
new ButtonWidget(
text: "Try Again",
textColor: AppThemeData().whiteColor,
color: AppThemeData().primaryColor,
onClicked: () {
Navigator.pop(context);
}),
],
))
else
Center(
child: Padding(
padding: const EdgeInsets.only(top: 5.0),
child: Column(
children: [
Image.asset(
'assets/icons/icon_profile_upload.png',
height: 50,
width: 50,
),
SizedBox(height: 30),
Text("Profile has uploaded!",
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 22.0)
.copyWith(
color: Colors.grey.shade900,
fontWeight: FontWeight.bold)),
SizedBox(height: 50),
new ButtonWidget(
textColor: AppThemeData().whiteColor,
color: AppThemeData().secondaryColor,
text: "OK",
onClicked: () {
Navigator.pop(context);
},
)
],
),
),
)
],
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0))),
);
},
);
},
);
}
void validateEdits() {
if (_userSelectedFileImage == null) {
ToastMessages().toastError("Please select an image", context);
} else {
showAlertDialog(context);
uploadImagesToStorage();
}
}
// -------------------------------- CHANGE IMAGE -------------------------------- \\
_imgFromCamera() async {
File fileImage = await ImagePicker.pickImage(
source: ImageSource.camera, imageQuality: 50);
setState(() {
_userSelectedFileImage = fileImage;
});
}
_imgFromGallery() async {
File fileImage = await ImagePicker.pickImage(
source: ImageSource.gallery, imageQuality: 50);
setState(() {
_userSelectedFileImage = fileImage;
});
}
changeProfilePicture(context) {
showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return SafeArea(
child: Container(
child: new Wrap(
children: <Widget>[
new ListTile(
leading: new Icon(Icons.photo_library),
title: new Text('Photo Library'),
onTap: () {
_imgFromGallery();
Navigator.of(context).pop();
}),
new ListTile(
leading: new Icon(Icons.photo_camera),
title: new Text('Camera'),
onTap: () {
_imgFromCamera();
Navigator.of(context).pop();
},
),
],
),
),
);
});
}
Future<void> uploadImagesToStorage() async {
if (_userSelectedFileImage != null) {
FirebaseStorage.instance.refFromURL(_userLatestProfileImage).delete();
try {
ref = firebase_storage.FirebaseStorage.instance.ref().child(
'User Profile Images/${FirebaseAuth.instance.currentUser.uid}/${FirebaseAuth.instance.currentUser.uid}');
await ref.putFile(_userSelectedFileImage);
String downloadURL = await firebase_storage.FirebaseStorage.instance
.ref()
.child(
'User Profile Images/${FirebaseAuth.instance.currentUser.uid}/${FirebaseAuth.instance.currentUser.uid}')
.getDownloadURL();
firebaseStorageUploadedImageURL = downloadURL.toString();
print("Image Uploaded to Firebase Storage!");
print("Image URL: " + firebaseStorageUploadedImageURL);
saveEditProfileToFireStore(firebaseStorageUploadedImageURL);
} catch (e) {
print(e.toString());
ifAnError();
}
} else {
saveEditProfileToFireStore(_userLatestProfileImage);
}
}
saveEditProfileToFireStore(String firebaseStorageUploadedImageURL) {
print("IMAGE: " + firebaseStorageUploadedImageURL);
FirebaseFirestore.instance
.collection('Users')
.doc(currentUserID.toString())
.update({
'profileImage': firebaseStorageUploadedImageURL,
})
.then(
(value) => sendSuccessCode(),
)
.catchError((error) => sendErrorCode(error.toString()));
}
// -------------------------------- PROFILE DETAILS -------------------------------- \\
_columnTitle(String title) {
return Padding(
padding: const EdgeInsets.only(top: 20.0),
child: Text(
title,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.bold),
),
);
}
_columnDetail(String title) {
return Padding(
padding: const EdgeInsets.only(top: 10.0),
child: Text(
title,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.normal),
),
);
}
Widget _profileDetails() {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 30.0),
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("Users")
.where('uuid', isEqualTo: "${currentUserID.toString()}")
.snapshots(),
builder: (context, dataSnapshot) {
if (!dataSnapshot.hasData) {
return Text(
"Hi! ",
style: TextStyle(
fontSize: Theme.of(context).textTheme.headline6.fontSize,
fontWeight: FontWeight.bold),
);
} else {
UserModelClass userModelClass =
UserModelClass.fromDocument(dataSnapshot.data.docs[0]);
_userLatestProfileImage = userModelClass.profileImage;
return ListView(
physics: BouncingScrollPhysics(),
children: [
SizedBox(
height: 5.0,
),
Center(
child: _userSelectedFileImage != null
? new ImageFramesWidgets().userProfileFrame(
_userSelectedFileImage, 150.0, 65.0, false)
: new ImageFramesWidgets().userProfileFrame(
_userLatestProfileImage, 150.0, 65.0, true),
),
SizedBox(
height: 20.0,
),
Center(
child: TextWithIconButtonWidget(
text: "Click to Change Image",
icon: Icons.camera_alt_rounded,
iconToLeft: true,
onClicked: () {
print('Change Profile Image');
changeProfilePicture(context);
},
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_columnTitle("Name"),
_columnDetail(userModelClass.name),
_columnTitle("Account Type"),
_columnDetail(userModelClass.accountType),
_columnTitle("Contact Number"),
_columnDetail(userModelClass.contactNumber),
_columnTitle("Email"),
_columnDetail(userModelClass.email),
_columnTitle("Home Address"),
_columnDetail(userModelClass.homeAddress),
],
),
SizedBox(
height: 20.0,
),
MinButtonWidget(
text: "Update Profile",
color: AppThemeData().secondaryColor,
onClicked: () {
validateEdits();
},
),
SizedBox(
height: 20.0,
),
],
);
}
},
),
);
}
// -------------------------------- BUILD -------------------------------- \\
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: SecondaryAppBar(
title: "Profile Info",
appBar: AppBar(),
widgets: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: Icon(
Icons.person_rounded,
color: Theme.of(context).iconTheme.color,
size: 35.0,
),
)
],
),
body: _profileDetails(),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/Settings/settings_page.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:trashpick/Models/user_model.dart';
import 'package:trashpick/Pages/BottomNavBar/Settings/give_feedback_page.dart';
import 'package:trashpick/Widgets/button_widgets.dart';
import 'package:trashpick/Widgets/image_frames_widgets.dart';
import '../../../Widgets/primary_app_bar_widget.dart';
import '../../../Widgets/alert_dialogs.dart';
import '../../../Widgets/change_theme_button_widget.dart';
import '../../../Theme/theme_provider.dart';
import 'profile_info_page.dart';
import 'settings_user_guide.dart';
class SettingsPage extends StatefulWidget {
@override
_SettingsPageState createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
final userReference = FirebaseFirestore.instance.collection('Users');
final FirebaseAuth auth = FirebaseAuth.instance;
String hashTags = "#TideTunersPlasticChallage #BetterWorldFramework #Scouts";
profileHeader() {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("Users")
.where('uuid', isEqualTo: "${auth.currentUser.uid}")
.snapshots(),
builder: (context, dataSnapshot) {
if (!dataSnapshot.hasData) {
return Text(
"Hi! ",
style: TextStyle(
fontSize: Theme.of(context).textTheme.headline6.fontSize,
fontWeight: FontWeight.bold),
);
} else {
UserModelClass userModelClass =
UserModelClass.fromDocument(dataSnapshot.data.docs[0]);
return Row(
children: [
ImageFramesWidgets().userProfileFrame(
userModelClass.profileImage, 90.0, 36.0, true),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${userModelClass.name}",
style: TextStyle(
fontSize:
Theme.of(context).textTheme.headline6.fontSize,
fontWeight: FontWeight.bold),
),
Text(
"${userModelClass.accountType}",
style: TextStyle(
fontSize:
Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.bold),
),
],
),
],
);
}
},
);
}
aboutUsTitle() {
return Row(mainAxisSize: MainAxisSize.min, children: [
Icon(
Icons.info_outline_rounded,
color: Theme.of(context).iconTheme.color,
),
SizedBox(
width: 10.0,
),
Text("About Us",
style: TextStyle(
fontSize: Theme.of(context).textTheme.button.fontSize,
color: Theme.of(context).textTheme.button.color,
fontWeight: FontWeight.bold,
))
]);
}
aboutUsContainer() {
return Column(
children: [
Text(
hashTags,
style: TextStyle(
fontSize: Theme.of(context).textTheme.caption.fontSize,
fontWeight: FontWeight.bold,
color: AppThemeData().deepBlueColor),
),
SizedBox(
height: 10.0,
),
Image.asset(
'assets/images/about_banner_1.png',
width: MediaQuery.of(context).size.width,
),
SizedBox(
height: 5.0,
),
Image.asset(
'assets/images/about_banner_2.png',
width: MediaQuery.of(context).size.width,
),
],
);
}
@override
Widget build(BuildContext context) {
final themeText =
Provider.of<ThemeProvider>(context).themeMode == ThemeMode.light
? 'Light Theme'
: 'Dark Theme';
final IconData themeIcon =
Provider.of<ThemeProvider>(context).themeMode == ThemeMode.light
? Icons.wb_sunny_rounded
: Icons.nightlight_round;
return Scaffold(
appBar: PrimaryAppBar(
title: "Settings",
appBar: AppBar(),
widgets: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: Icon(
Icons.settings_rounded,
color: Theme.of(context).iconTheme.color,
size: 35.0,
),
)
],
),
body: SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
profileHeader(),
SizedBox(
height: 20.0,
),
TextWithIconButtonWidget(
text: "Sign Out",
icon: Icons.logout,
iconToLeft: true,
onClicked: () => SignOutAlertDialog().showAlert(context),
),
SizedBox(
height: 5.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Icon(themeIcon),
SizedBox(
width: 10.0,
),
Text(
"$themeText",
style: TextStyle(
fontSize:
Theme.of(context).textTheme.button.fontSize,
fontWeight: FontWeight.bold),
),
],
),
ChangeThemeButtonWidget(),
],
),
SizedBox(
height: 5.0,
),
TextWithIconButtonWidget(
text: "Profile Info",
icon: Icons.account_circle_rounded,
iconToLeft: true,
onClicked: () {
print('Switch to Profile Info');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProfileInfoPage()),
);
},
),
SizedBox(
height: 15.0,
),
TextWithIconButtonWidget(
text: "User Guide",
icon: Icons.assistant_rounded,
iconToLeft: true,
onClicked: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SettingsUserGuide()),
);
},
),
SizedBox(
height: 15.0,
),
TextWithIconButtonWidget(
text: "Give Feedback",
icon: Icons.feedback_rounded,
iconToLeft: true,
onClicked: () {
print('Switch to Give Feedback');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => GiveFeedbackPage()),
);
},
),
SizedBox(
height: 15.0,
),
aboutUsTitle(),
SizedBox(
height: 15.0,
),
aboutUsContainer(),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/PickMyTrash/new_trash_pick_up.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/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:trashpick/Generators/uui_generator.dart';
import 'package:trashpick/Models/user_model.dart';
import 'package:trashpick/Pages/BottomNavBar/PickMyTrash/pick_trash_location.dart';
import 'package:trashpick/Theme/theme_provider.dart';
import 'package:trashpick/Widgets/button_widgets.dart';
import 'dart:io';
import 'package:trashpick/Widgets/primary_app_bar_widget.dart';
import 'package:trashpick/Widgets/secondary_app_bar_widget.dart';
import 'package:trashpick/Widgets/toast_messages.dart';
import '../bottom_nav_bar.dart';
class NewTrashPickUp extends StatefulWidget {
final String accountType;
NewTrashPickUp(this.accountType);
@override
_NewTrashPickUpState createState() => _NewTrashPickUpState();
}
class _NewTrashPickUpState extends State<NewTrashPickUp> {
TextEditingController _trashNameController = new TextEditingController();
TextEditingController _trashDescriptionController =
new TextEditingController();
TextEditingController _trashLocationController = new TextEditingController();
int charLength = 0;
File _image;
final String userProfileID = FirebaseAuth.instance.currentUser.uid.toString();
// Uploading Process
bool isStartToUpload = false;
bool isUploadComplete = false;
bool isAnError = false;
double circularProgressVal;
// Temp until delete
CollectionReference imgRef;
firebase_storage.Reference ref;
String imageURL;
final firestoreInstance = FirebaseFirestore.instance;
String formattedDate = DateFormat('dd-MM-yyyy').format(DateTime.now());
String formattedTime = DateFormat('kk:mm:a').format(DateTime.now());
String trashID = new UUIDGenerator().uuidV4();
// ------------------------------ Trash Type Selector ------------------------------ \\
Map<String, bool> trashTypeValues = {
'Plastic & Polythene': false,
'Glass': false,
'Paper': false,
'Metal & Coconut Shell': false,
'Clinical Waste': false,
'E-Waste': false,
};
List trashTypeArray = [];
List trashTypes;
getCheckboxItems() {
trashTypeArray.clear();
trashTypeValues.forEach((key, value) {
if (value == true) {
trashTypeArray.add(key);
}
});
trashTypes = trashTypeArray;
//print(trashTypeArray);
//print(trashTypes);
}
// ------------------------------ Location Picker ------------------------------ \\
String locationName = "My Location";
String userHomeLocation = "My Home";
int locationTypeID;
final userReference = FirebaseFirestore.instance.collection('Users');
final FirebaseAuth auth = FirebaseAuth.instance;
Position _currentPosition;
List _trashLocationDetails;
String userCurrentAddress = "No Location Selected!";
String selectedFromMapAddress = "No Location Selected!";
String trashLocationAddress = "No Location Selected!";
double trashLocationLatitude, trashLocationLongitude;
// ------------------------------ Date Picker ------------------------------ \\
String startDate = DateTime.now().day.toString() +
"/" +
DateTime.now().month.toString() +
"/" +
DateTime.now().year.toString();
String returnDate = DateTime.now().day.toString() +
"/" +
DateTime.now().month.toString() +
"/" +
DateTime.now().year.toString();
DateTime _dateS = DateTime(2021, 07, 17);
DateTime _dateR = DateTime(2021, 07, 18);
// ------------------------------ Time Picker ------------------------------ \\
String startTime = "7:15 AM";
String returnTime = "8:15 AM";
TimeOfDay _timeS = TimeOfDay(hour: 7, minute: 15);
TimeOfDay _timeR = TimeOfDay(hour: 8, minute: 15);
var now = DateTime.now().hour;
var nowt = DateTime.now().minute;
TimeOfDay releaseTime = TimeOfDay(hour: 15, minute: 0);
String nowTime = TimeOfDay(hour: 15, minute: 0).toString();
void _startTime() async {
final TimeOfDay newTime = await showTimePicker(
context: context,
initialTime: _timeS,
);
if (newTime != null) {
setState(() {
_timeS = newTime;
startTime = _timeS.format(context);
});
}
}
void _returnTime() async {
final TimeOfDay newTime = await showTimePicker(
context: context,
initialTime: _timeR,
);
if (newTime != null) {
setState(() {
_timeR = newTime;
returnTime = _timeR.format(context);
});
}
}
_onChanged(String value) {
setState(() {
charLength = value.length;
});
}
_imgFromCamera() async {
File image = await ImagePicker.pickImage(
source: ImageSource.camera, imageQuality: 50);
setState(() {
_image = image;
});
}
_imgFromGallery() async {
File image = await ImagePicker.pickImage(
source: ImageSource.gallery, imageQuality: 50);
setState(() {
_image = image;
});
}
void _showPicker(context) {
showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return SafeArea(
child: Container(
child: new Wrap(
children: <Widget>[
new ListTile(
leading: new Icon(Icons.photo_library),
title: new Text('Photo Library'),
onTap: () {
_imgFromGallery();
Navigator.of(context).pop();
}),
new ListTile(
leading: new Icon(Icons.photo_camera),
title: new Text('Camera'),
onTap: () {
_imgFromCamera();
Navigator.of(context).pop();
},
),
],
),
),
);
});
}
void ifAnError() {
Navigator.pop(context);
setState(() {
isStartToUpload = false;
isUploadComplete = false;
isAnError = true;
//Navigator.pop(context);
showAlertDialog(context);
});
}
void sendErrorCode(String error) {
ToastMessages().toastError(error, context);
ifAnError();
}
void sendSuccessCode() {
print("Post Add Success!");
Navigator.pop(context);
setState(() {
isStartToUpload = false;
isUploadComplete = true;
});
showAlertDialog(context);
}
showAlertDialog(BuildContext context) {
// show the dialog
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: !isUploadComplete
? Center(child: Text("Uploading Post"))
: Center(child: Text("Upload Success")),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (!isUploadComplete)
!isAnError
? Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30.0,
),
CircularProgressIndicator(
value: circularProgressVal,
strokeWidth: 6,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.teal.shade700),
),
SizedBox(
height: 30.0,
),
Text("Please wait until your post is upload.",
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 16.0)
.copyWith(color: Colors.grey.shade900)),
],
)
: Container(
child: Column(
children: [
Text("Error!",
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
)),
SizedBox(
height: 50.0,
),
new ButtonWidget(
text: "Try Again",
textColor: AppThemeData().whiteColor,
color: AppThemeData().redColor,
onClicked: () {
Navigator.pop(context);
}),
],
))
else
Center(
child: Padding(
padding: const EdgeInsets.only(top: 5.0),
child: Column(
children: [
Image.asset(
'assets/icons/icon_recycle.png',
height: 50,
width: 50,
),
SizedBox(height: 30),
Text("Post has uploaded!",
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 22.0)
.copyWith(
color: Colors.grey.shade900,
fontWeight: FontWeight.bold)),
SizedBox(height: 50),
new ButtonWidget(
text: "Continue",
textColor: AppThemeData().whiteColor,
color: AppThemeData().primaryColor,
onClicked: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
BottomNavBar(widget.accountType),
),
(route) => false,
);
}),
],
),
),
)
],
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0))),
);
},
);
},
);
}
Future<void> uploadImagesToStorage() async {
try {
ref = firebase_storage.FirebaseStorage.instance
.ref()
//.child('Posts/$userProfileID/$postID/${Path.basename(_image.path)}');
.child('Trash Pick Ups/$userProfileID/$trashID/$trashID');
await ref.putFile(_image);
String downloadURL = await firebase_storage.FirebaseStorage.instance
.ref()
//.child('Posts/$userProfileID/$postID/${Path.basename(_image.path)}')
.child('Trash Pick Ups/$userProfileID/$trashID/$trashID')
.getDownloadURL();
imageURL = downloadURL.toString();
print("Image Uploaded to Firebase Storage!");
print("Image URL: " + imageURL);
addPostToFireStore(imageURL);
} catch (e) {
print(e.toString());
ifAnError();
}
}
Future<void> addPostToFireStore(String trashImage) async {
firestoreInstance
.collection('Users')
.doc(userProfileID)
.collection('Trash Pick Ups')
.doc(trashID)
.set({
'trashID': trashID,
'postedDate': formattedDate + ", " + formattedTime,
'trashName': _trashNameController.text,
'trashDescription': _trashDescriptionController.text,
'trashImage': trashImage,
'trashTypes': trashTypes,
'trashLocationAddress': trashLocationAddress,
'trashLocationLocation':
new GeoPoint(trashLocationLatitude, trashLocationLongitude),
'startDate': startDate,
'returnDate': returnDate,
'startTime': startTime,
'returnTime': returnTime,
})
.then(
(value) => sendSuccessCode(),
)
.catchError((error) => sendErrorCode(error.toString()));
}
/*void validatePost() {
if (_newPostCaptionController.text.isEmpty ||
_newPostCaptionController.text == null) {
ToastMessages().toastError("Please enter trash caption", context);
} else if (_image == null) {
ToastMessages().toastError("Please select image", context);
} else {
showAlertDialog(context);
uploadImagesToStorage();
}
}*/
_getCurrentUserLocation() async {
try {
Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
forceAndroidLocationManager: true)
.then((Position position) {
setState(() {
_currentPosition = position;
});
_getCurrentUserAddressFromLatLng(
_currentPosition.latitude, _currentPosition.longitude);
}).catchError((e) {
print(e);
});
} catch (error) {
ToastMessages().toastError(error, context);
}
}
_getCurrentUserAddressFromLatLng(latitude, longitude) async {
try {
List<Placemark> p = await placemarkFromCoordinates(latitude, longitude);
Placemark place = p[0];
setState(() {
if (place != null) {
trashLocationLatitude = latitude;
trashLocationLongitude = longitude;
_trashLocationDetails = [
latitude, // 00
longitude, // 01
"${place.name}", // 02
"${place.street}", // 03
"${place.postalCode}", // 04
"${place.administrativeArea}", // 05
"${place.subAdministrativeArea}", // 06
"${place.thoroughfare}", // 07
"${place.subThoroughfare}", // 08
"${place.locality}", // 09
"${place.subLocality}", // 10
"${place.country}", // 11
"${place.isoCountryCode}", // 12
];
userCurrentAddress = ""
"${_trashLocationDetails[0].toString()}, "
"${_trashLocationDetails[1].toString()}, "
"${_trashLocationDetails[2].toString()}, "
"${_trashLocationDetails[3].toString()}, "
"${_trashLocationDetails[4].toString()}, "
"${_trashLocationDetails[5].toString()}, "
"${_trashLocationDetails[6].toString()}, "
"${_trashLocationDetails[7].toString()}, "
"${_trashLocationDetails[8].toString()}, "
"${_trashLocationDetails[9].toString()}, "
"${_trashLocationDetails[10].toString()}, "
"${_trashLocationDetails[11].toString()}, "
"${_trashLocationDetails[12].toString()}";
/*ToastMessages().toastSuccess("Location Selected: \n"
"$_trashLocationAddress", context);*/
} else {
ToastMessages().toastSuccess("No Address", context);
}
});
} catch (error) {
ToastMessages().toastError(error.toString(), context);
print("ERROR=> _getTrashLocationAddressFromLatLng: $error");
}
}
void _startDate() async {
final DateTime newDate = await showDatePicker(
context: context,
initialDate: _dateS,
firstDate: DateTime(2021, 1),
lastDate: DateTime(2031, 1),
helpText: 'Select a date',
);
if (newDate != null) {
setState(() {
_dateS = newDate;
startDate = _dateS.day.toString() +
"/" +
_dateS.month.toString() +
"/" +
_dateS.year.toString();
});
}
}
void _returnDate() async {
final DateTime newDate = await showDatePicker(
context: context,
initialDate: _dateR,
firstDate: DateTime(2017, 1),
lastDate: DateTime(2022, 7),
helpText: 'Select a date',
);
if (newDate != null) {
setState(() {
_dateR = newDate;
returnDate = _dateR.day.toString() +
"/" +
_dateR.month.toString() +
"/" +
_dateR.year.toString();
});
}
}
printTrashPickUpDetails() {
String info =
"------------------------- Trash Pick Up Details -------------------------\n"
"Trash Name: " +
_trashNameController.text +
"\n" +
"Trash Description: " +
_trashDescriptionController.text +
"\n" +
"Trash Image: " +
_image.toString() +
"\n" +
"Trash Types: " +
trashTypes.toString() +
"\n" +
"Trash Location Address: " +
trashLocationAddress.toString() +
"\n" +
"Trash Location Latitude: " +
trashLocationLatitude.toString() +
"\n" +
"Trash Location Longitude: " +
trashLocationLongitude.toString() +
"\n" +
"Start Date: $startDate\n" +
"Return Date: $returnDate\n" +
"Start Time: $startTime\n" +
"Return Time: $returnTime\n";
print(info);
}
void validatePickUp() {
if (_trashNameController.text.isEmpty) {
new ToastMessages().toastError("Cannot leave trash name", context);
} else if (_trashDescriptionController.text.isEmpty) {
new ToastMessages().toastError("Cannot leave trash description", context);
} else if (_image == null) {
new ToastMessages().toastError("Please select an image", context);
} else if (trashTypes.isEmpty) {
new ToastMessages()
.toastError("Please select at least one type", context);
} else if (trashLocationAddress == "No Location Selected!") {
new ToastMessages().toastError("Please select a location", context);
} else if (startDate.isEmpty) {
new ToastMessages().toastError("Please select Start Date", context);
} else if (returnDate.isEmpty) {
new ToastMessages().toastError("Please select Return Date", context);
} else if (_dateS.day + _dateS.month + _dateS.year >
_dateR.day + _dateR.month + _dateR.year) {
new ToastMessages()
.toastError("Return date cannot be early than Start Date", context);
} else if (startTime.isEmpty) {
new ToastMessages().toastError("Please Select Start Time", context);
} else if (returnTime.isEmpty) {
new ToastMessages().toastError("Please select Return Time", context);
} else if (startDate == returnDate && _timeS.hour > _timeR.hour) {
new ToastMessages().toastError(
"Return Time cannot be early than Start Time on same day", context);
} else {
printTrashPickUpDetails();
showAlertDialog(context);
uploadImagesToStorage();
}
//printTrashPickUpDetails();
}
@override
void initState() {
_getCurrentUserLocation();
super.initState();
}
@override
Widget build(BuildContext context) {
void navigateAndDisplaySelection(BuildContext context) async {
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PickTrashLocation(_currentPosition)),
);
setState(() {
if (result == null) {
selectedFromMapAddress = "No Location Selected!";
} else {
_trashLocationDetails = result;
selectedFromMapAddress = ""
"${_trashLocationDetails[0].toString()}, "
"${_trashLocationDetails[1].toString()}, "
"${_trashLocationDetails[2].toString()}, "
"${_trashLocationDetails[3].toString()}, "
"${_trashLocationDetails[4].toString()}, "
"${_trashLocationDetails[5].toString()}, "
"${_trashLocationDetails[6].toString()}, "
"${_trashLocationDetails[7].toString()}, "
"${_trashLocationDetails[8].toString()}, "
"${_trashLocationDetails[9].toString()}, "
"${_trashLocationDetails[10].toString()}, "
"${_trashLocationDetails[11].toString()}, "
"${_trashLocationDetails[12].toString()}";
trashLocationAddress = selectedFromMapAddress;
}
});
}
showInfoAlert(BuildContext context) {
String infoTitle = "Guide to select location";
String infoMessage =
"To select a location, just press on the map and selected place will marked with this marker.";
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(infoTitle),
content: Container(
height: 160.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
infoMessage,
style: TextStyle(fontWeight: FontWeight.normal),
),
Image.asset(
'assets/icons/icon_bin.png',
scale: 1.0,
)
],
),
),
actions: <Widget>[
TextButton(
child: Text(
"Ok and Select Location",
style: TextStyle(color: AppThemeData().primaryColor),
),
onPressed: () {
Navigator.pop(context);
navigateAndDisplaySelection(context);
/* Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
PickTrashLocation(_currentPosition)),
);*/
},
),
],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10.0))),
);
},
);
}
garbageTypes() {
return Container(
height: 430.0,
child: ListView(
physics: NeverScrollableScrollPhysics(),
children: trashTypeValues.keys.map((String key) {
Color color;
String description;
switch (key) {
case "Plastic & Polythene":
color = Colors.orange.shade700;
description = "Plastic & Polythene";
break;
case "Glass":
color = Colors.red;
description = "Glass";
break;
case "Paper":
color = Colors.blue;
description = "Paper";
break;
case "Metal & Coconut Shell":
color = Colors.black;
description = "Metal & Coconut Shell";
break;
case "Clinical Waste":
color = Colors.yellow;
description = "Clinical Waste";
break;
case "E-Waste":
color = Colors.grey.shade200;
description = "E-Waste";
break;
default:
color = Colors.grey.shade100;
description = "Other";
}
return new CheckboxListTile(
secondary: Container(
color: color,
height: 30.0,
width: 30.0,
),
title: new Text(key),
subtitle: Text(description),
value: trashTypeValues[key],
onChanged: (bool value) {
setState(() {
trashTypeValues[key] = value;
});
},
);
}).toList(),
),
);
}
/*Widget getMyHomeAddress(){
return FutureBuilder(
future: userReference.doc(auth.currentUser.uid).get(),
builder: (context, dataSnapshot) {
if (!dataSnapshot.hasData) {
_trashLocationController =
new TextEditingController(text: "No Location Selected!");
return TextFormField(
controller: _trashLocationController,
style: TextStyle(fontWeight: FontWeight.normal),
decoration: InputDecoration(
prefixIcon: Icon(
Icons.home_rounded,
color: Theme.of(context).iconTheme.color,
size: 35.0,
),
focusedBorder: UnderlineInputBorder(
borderSide: const BorderSide(color: Colors.black),
),
),
keyboardType: TextInputType.text,
);
} else {
UserModelClass userModelClass =
UserModelClass.fromDocument(dataSnapshot.data);
_trashLocationController =
new TextEditingController(text: userModelClass.homeAddress);
return TextFormField(
controller: _trashLocationController,
style: TextStyle(fontWeight: FontWeight.normal),
decoration: InputDecoration(
prefixIcon: Icon(
Icons.home_rounded,
color: Theme.of(context).iconTheme.color,
size: 35.0,
),
focusedBorder: UnderlineInputBorder(
borderSide: const BorderSide(color: Colors.black),
),
),
keyboardType: TextInputType.text,
);
}
},
);
}*/
Widget trashLocation() {
Widget widget;
switch (locationName) {
case "Current Location":
widget = Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.location_on_rounded,
color: Theme.of(context).iconTheme.color,
size: 35.0,
),
Text(
"Current Location",
style: TextStyle(
fontSize: Theme.of(context).textTheme.headline6.fontSize,
fontWeight: FontWeight.bold),
),
],
);
break;
case "Select from Map":
widget = Center(
child: MinButtonWidget(
text: "Select from Map",
color: Theme.of(context).backgroundColor,
onClicked: () {
print("Pressed: Select from Map");
showInfoAlert(context);
},
),
);
break;
default:
widget = Container();
}
return widget;
}
radioButtonList() {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Radio(
value: 1,
groupValue: locationTypeID,
onChanged: (val) {
setState(() {
locationName = 'Current Location';
locationTypeID = 1;
trashLocationAddress = userCurrentAddress;
});
},
),
Text(
'Current Location',
style: new TextStyle(
fontSize: Theme.of(context).textTheme.subtitle1.fontSize),
),
Radio(
value: 2,
groupValue: locationTypeID,
onChanged: (val) {
setState(() {
locationName = 'Select from Map';
locationTypeID = 2;
trashLocationAddress = selectedFromMapAddress;
});
},
),
Text(
'Select from Map',
style: new TextStyle(
fontSize: Theme.of(context).textTheme.subtitle1.fontSize,
),
),
],
),
],
);
}
dateSelectCard(String title, VoidCallback onCardTap, String dateType) {
return Container(
alignment: Alignment.topLeft,
width: 150,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: TextStyle(
fontSize: 14.0,
fontWeight: FontWeight.bold,
color: Colors.grey.shade600),
),
SizedBox(
height: 10.0,
),
ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Container(
color: Colors.grey.shade200,
child: new GestureDetector(
onTap: onCardTap,
child: new Container(
height: 50.0,
width: 150.0,
color: Colors.white,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.calendar_today_rounded,
size: 20.0,
),
SizedBox(
width: 10.0,
),
Text(
dateType,
style: TextStyle(fontWeight: FontWeight.bold),
),
],
)),
))),
),
],
),
);
}
timeSelectCard(String title, VoidCallback onCardTap, String timeType) {
return Container(
alignment: Alignment.topLeft,
width: 150,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: TextStyle(
fontSize: 14.0,
fontWeight: FontWeight.bold,
color: Colors.grey.shade600),
),
SizedBox(
height: 10.0,
),
ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Container(
color: Colors.grey.shade200,
child: new GestureDetector(
onTap: onCardTap,
child: new Container(
height: 50.0,
width: 150.0,
color: Colors.white,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.access_time_rounded,
size: 20.0,
),
SizedBox(
width: 10.0,
),
Text(
timeType,
style: TextStyle(fontWeight: FontWeight.bold),
),
],
)),
))),
),
],
),
);
}
return Scaffold(
appBar: SecondaryAppBar(
title: "Schedule a Trash Pick Up",
appBar: AppBar(),
widgets: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: Icon(
Icons.cancel_rounded,
size: 30.0,
),
)
],
),
body: SingleChildScrollView(
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
controller: _trashNameController,
style: TextStyle(fontWeight: FontWeight.normal),
decoration: InputDecoration(
contentPadding: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0),
hintText: "Give a name to the trash",
labelText: 'Trash Name',
focusedBorder: UnderlineInputBorder(
borderSide: const BorderSide(color: Colors.black),
),
labelStyle: TextStyle(
color: Colors.grey.shade900,
fontWeight: FontWeight.bold),
),
keyboardType: TextInputType.text,
),
SizedBox(
height: 20.0,
),
TextFormField(
controller: _trashDescriptionController,
style: TextStyle(fontWeight: FontWeight.normal),
decoration: InputDecoration(
contentPadding: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0),
helperText: "$charLength",
hintText: "Say something about trash",
labelText: 'Trash Description',
focusedBorder: UnderlineInputBorder(
borderSide: const BorderSide(color: Colors.black),
),
labelStyle: TextStyle(
color: Colors.grey.shade900,
fontWeight: FontWeight.bold),
),
onChanged: _onChanged,
maxLines: null,
keyboardType: TextInputType.multiline,
),
SizedBox(
height: 20.0,
),
Text(
"Pick Trash Image",
style: TextStyle(
fontSize: Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 20.0,
),
Center(
child: GestureDetector(
onTap: () {
_showPicker(context);
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
),
alignment: Alignment.center,
child: _image != null
? Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.white,
),
child: Image.file(
_image,
width: MediaQuery.of(context).size.width,
height: 300,
fit: BoxFit.cover,
),
)
: Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(10)),
width: MediaQuery.of(context).size.width,
height: 300,
child: Column(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: [
Text(
"Press to select image",
style: TextStyle(
fontSize: Theme.of(context)
.textTheme
.headline6
.fontSize,
fontWeight: FontWeight.normal,
),
textAlign: TextAlign.center,
),
Icon(
Icons.camera_alt_rounded,
size: 80.0,
color: Colors.grey.shade700,
),
],
),
),
),
),
),
SizedBox(
height: 20.0,
),
Text(
"Select Trash Types",
style: TextStyle(
fontSize: Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.bold),
),
garbageTypes(),
SizedBox(
height: 20.0,
),
Text(
"Select Location",
style: TextStyle(
fontSize: Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.bold),
),
radioButtonList(),
trashLocation(),
SizedBox(
height: 20.0,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Trash Location",
style: TextStyle(
fontSize:
Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10.0,
),
Text(
"$trashLocationAddress",
style: TextStyle(
fontSize:
Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.normal),
),
],
),
SizedBox(
height: 20.0,
),
Text(
"Select Available Date Period",
style: TextStyle(
fontSize: Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 20.0,
),
Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
dateSelectCard("Start Date", _startDate, startDate),
dateSelectCard("Return Date", _returnDate, returnDate),
],
),
),
),
SizedBox(
height: 20.0,
),
Text(
"Select Available Time Period",
style: TextStyle(
fontSize: Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 20.0,
),
Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
timeSelectCard(
"Start Time", _startTime, _timeS.format(context)),
timeSelectCard(
"Return Time", _returnTime, _timeR.format(context)),
],
),
),
),
MinButtonWidget(
onClicked: () {
getCheckboxItems();
//printTrashPickUpDetails();
validatePickUp();
},
color: AppThemeData().secondaryColor,
text: "OK",
),
SizedBox(
height: 40.0,
),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/PickMyTrash/pick_trash_location.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:trashpick/Theme/theme_provider.dart';
import 'package:trashpick/Widgets/marker_details_cards.dart';
import 'package:trashpick/Widgets/primary_app_bar_widget.dart';
import 'package:trashpick/Widgets/secondary_app_bar_widget.dart';
import 'package:trashpick/Widgets/toast_messages.dart';
class PickTrashLocation extends StatefulWidget {
PickTrashLocation(this.currentPosition);
final Position currentPosition;
@override
_PickTrashLocationState createState() => _PickTrashLocationState();
}
class _PickTrashLocationState extends State<PickTrashLocation> {
Widget _googleMapWidget;
GoogleMapController _googleMapController;
String _currentAddress;
List _trashLocationDetails;
BitmapDescriptor trashLocationMarkerIcon;
Map<MarkerId, Marker> trashLocationMarker = <MarkerId, Marker>{};
@override
void initState() {
_googleMapWidget = loadingMap();
setTrashLocationMarkerIcon();
super.initState();
}
// ---------------------------------- CURRENT USER ---------------------------------- \\
_getCurrentUserAddressFromLatLng() async {
try {
List<Placemark> p = await placemarkFromCoordinates(
widget.currentPosition.latitude, widget.currentPosition.longitude);
Placemark place = p[0];
setState(() {
if (place != null) {
_currentAddress = "${place.name}, "
"${place.street}, "
"${place.locality}, "
"${place.country}";
} else {
_currentAddress = "No Address";
}
_googleMapWidget = mapWidget();
});
} catch (error) {
ToastMessages().toastError(error, context);
}
}
// ---------------------------------- COMMON MAP ---------------------------------- \\
Widget loadingMap() {
return Center(
child: CircularProgressIndicator(),
);
}
setTrashLocationMarkerIcon() async {
trashLocationMarkerIcon = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(devicePixelRatio: 5.0), 'assets/icons/icon_bin.png');
}
_getTrashLocationAddressFromLatLng(latitude, longitude) async {
try {
List<Placemark> p = await placemarkFromCoordinates(latitude, longitude);
Placemark place = p[0];
setState(() {
if (place != null) {
_trashLocationDetails = [
latitude,
longitude,
"${place.name}",
"${place.street}",
"${place.postalCode}",
"${place.administrativeArea}",
"${place.subAdministrativeArea}",
"${place.thoroughfare}",
"${place.subThoroughfare}",
"${place.locality}",
"${place.subLocality}",
"${place.country}",
"${place.isoCountryCode}",
];
/*ToastMessages().toastSuccess("Location Selected: \n"
"$_trashLocationAddress", context);*/
} else {
ToastMessages().toastSuccess("No Address", context);
}
});
} catch (error) {
ToastMessages().toastError(error.toString(), context);
print("ERROR=> _getTrashLocationAddressFromLatLng: $error");
}
}
Widget mapWidget() {
return GoogleMap(
mapType: MapType.normal,
myLocationEnabled: true,
myLocationButtonEnabled: true,
initialCameraPosition: CameraPosition(
target: LatLng(
widget.currentPosition.latitude, widget.currentPosition.longitude),
zoom: 8.5,
),
onMapCreated: (GoogleMapController controller) {
_googleMapController = controller;
},
compassEnabled: true,
tiltGesturesEnabled: false,
onLongPress: (latLang) {
_addMarkerLongPressed(latLang);
print("Long Pressed");
print("$latLang");
},
markers: Set<Marker>.of(trashLocationMarker.values),
);
}
Future _addMarkerLongPressed(LatLng latLang) async {
setState(() {
final MarkerId markerId = MarkerId("TrashLocationID");
Marker marker = Marker(
markerId: markerId,
draggable: true,
position: latLang,
infoWindow: InfoWindow(
title: "Trash here",
snippet: 'This place has trash',
onTap: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return MarkerDetailsCard()
.showSelectLocationDetails(_trashLocationDetails, context);
},
);
},
),
icon: trashLocationMarkerIcon,
);
trashLocationMarker[markerId] = marker;
});
_getTrashLocationAddressFromLatLng(latLang.latitude, latLang.longitude);
GoogleMapController controller = _googleMapController;
controller.animateCamera(CameraUpdate.newLatLngZoom(latLang, 15.0));
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return MarkerDetailsCard()
.showSelectLocationDetails(_trashLocationDetails, context);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: SecondaryAppBar(
title: "Select Location",
appBar: AppBar(),
widgets: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: IconButton(
icon: Icon(
Icons.done_rounded,
size: 30.0,
),
color: Theme.of(context).iconTheme.color,
onPressed: () {
ToastMessages().toastSuccess(
"Location Selected: \n"
"${_trashLocationDetails[0].toString()}, "
"${_trashLocationDetails[0].toString()}, "
"${_trashLocationDetails[6].toString()}, "
"${_trashLocationDetails[5].toString()}",
context);
print(_trashLocationDetails);
Navigator.pop(context, _trashLocationDetails);
},
),
)
],
),
body: SafeArea(
child: Stack(children: [
Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: mapWidget(),
)
]),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/PickMyTrash/pick_my_trash_page.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:trashpick/Pages/BottomNavBar/PickMyTrash/new_trash_pick_up.dart';
import 'package:trashpick/Theme/theme_provider.dart';
import 'package:trashpick/Widgets/button_widgets.dart';
import '../../../Widgets/primary_app_bar_widget.dart';
import '../../../Models/trash_pick_ups_model.dart';
import 'view_trash_details.dart';
class PickMyTrash extends StatefulWidget {
final String accountType;
PickMyTrash(this.accountType);
@override
_PickMyTrashState createState() => _PickMyTrashState();
}
class _PickMyTrashState extends State<PickMyTrash> {
final String userProfileID = FirebaseAuth.instance.currentUser.uid.toString();
final firestoreInstance = FirebaseFirestore.instance;
/* _scheduledTrashPicksList() {
return Text("_scheduledTrashPicksList");
}*/
Widget trashDetailsCard(AsyncSnapshot<QuerySnapshot> snapshot,
TrashPickUpsModel trashPickUpsModel) {
return Container(
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Colors.grey.shade100,
child: InkWell(
splashColor: Colors.blue.withAlpha(30),
onTap: () {
print('Selected Trash: ${trashPickUpsModel.trashID}');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ViewTrashDetails(userProfileID,
trashPickUpsModel.trashID, widget.accountType)),
);
},
child: snapshot.data.docs.length == null
? Container()
: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Image.network(
trashPickUpsModel.trashImage,
fit: BoxFit.cover,
height: 150,
width: 150,
),
),
SizedBox(
width: 10.0,
),
Expanded(
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
trashPickUpsModel.trashName,
style: TextStyle(
fontSize: Theme.of(context)
.textTheme
.headline6
.fontSize,
fontWeight: FontWeight.w500,
color: Theme.of(context).primaryColor),
),
Divider(
color: Theme.of(context).iconTheme.color,
),
Text(
trashPickUpsModel.trashDescription,
textAlign: TextAlign.start,
style: TextStyle(
color:
AppThemeData.lightTheme.iconTheme.color),
),
//Text(trashPickUpsModel.trashLocationAddress),
],
),
),
),
],
),
),
),
);
}
_scheduledTrashPicksList() {
return Container(
height: MediaQuery.of(context).size.height,
//color: Colors.red,
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("Users")
.doc(userProfileID)
.collection('Trash Pick Ups')
.orderBy('postedDate', descending: true)
.snapshots(),
builder: (context, snapshot) {
return !snapshot.hasData
? Container()
: snapshot.data.docs.length.toString() == "0"
? Container(
height: 250.0,
width: 200.0,
child: Column(
children: [
SizedBox(
height: 30.0,
),
Text(
"You have no scheduled trash pick ups yet",
style: TextStyle(
fontSize: Theme.of(context)
.textTheme
.headline6
.fontSize),
),
Image.asset(
'assets/icons/icon_broom.png',
height: 100.0,
width: 100.0,
),
],
),
)
: ListView.builder(
scrollDirection: Axis.vertical,
physics: BouncingScrollPhysics(),
itemCount: snapshot.data.docs.length,
itemBuilder: (BuildContext context, int index) {
TrashPickUpsModel trashPickUpsModel =
TrashPickUpsModel.fromDocument(
snapshot.data.docs[index]);
return trashDetailsCard(snapshot, trashPickUpsModel);
},
);
},
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PrimaryAppBar(
title: "Pick My Trash",
appBar: AppBar(),
widgets: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: Icon(
Icons.transfer_within_a_station_rounded,
color: Theme.of(context).iconTheme.color,
size: 35.0,
),
)
],
),
body: SingleChildScrollView(
child: Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 8.0),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Made for ${widget.accountType}",
style: TextStyle(
fontSize:
Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.bold),
),
],
),
SizedBox(
height: 20.0,
),
MinButtonWidget(
text: "Schedule a Trash Pick Up",
color: Theme.of(context).backgroundColor,
onClicked: () {
print("Pressed: Schedule a Trash Pick Up");
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
NewTrashPickUp(widget.accountType)),
);
},
),
SizedBox(
height: 20.0,
),
Text(
"My Scheduled Trash Pick Ups",
style: TextStyle(
fontSize: Theme.of(context).textTheme.headline6.fontSize,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 20.0,
),
_scheduledTrashPicksList(),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/PickMyTrash/view_trash_details.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:trashpick/Models/trash_pick_ups_model.dart';
import 'package:trashpick/Widgets/button_widgets.dart';
import 'package:trashpick/Widgets/secondary_app_bar_widget.dart';
class ViewTrashDetails extends StatefulWidget {
final String userID, trashID, accountType;
ViewTrashDetails(this.userID, this.trashID, this.accountType);
@override
_ViewTrashDetailsState createState() => _ViewTrashDetailsState();
}
class _ViewTrashDetailsState extends State<ViewTrashDetails> {
final userReference = FirebaseFirestore.instance.collection('Users');
final FirebaseAuth auth = FirebaseAuth.instance;
List trashTypesList;
Widget trashTypesFilter(TrashPickUpsModel trashPickUpsModel) {
return Container(
height: (trashPickUpsModel.trashTypes.length.toDouble() * 45),
child: ListView.builder(
scrollDirection: Axis.vertical,
physics: BouncingScrollPhysics(),
itemCount: trashPickUpsModel.trashTypes.length,
itemBuilder: (BuildContext context, int index) {
Color trashTypeColor;
String trashTypeDescription;
switch (trashPickUpsModel.trashTypes[index]) {
case "Plastic & Polythene":
trashTypeColor = Colors.orange.shade700;
trashTypeDescription = "Plastic & Polythene";
break;
case "Glass":
trashTypeColor = Colors.red;
trashTypeDescription = "Glass";
break;
case "Paper":
trashTypeColor = Colors.blue;
trashTypeDescription = "Paper";
break;
case "Metal & Coconut Shell":
trashTypeColor = Colors.black;
trashTypeDescription = "Metal & Coconut Shell";
break;
case "Clinical Waste":
trashTypeColor = Colors.yellow;
trashTypeDescription = "Clinical Waste";
break;
case "E-Waste":
trashTypeColor = Colors.grey.shade200;
trashTypeDescription = "E-Waste";
break;
default:
trashTypeColor = Colors.grey.shade100;
trashTypeDescription = "Other";
}
return Padding(
padding: const EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0),
child: Row(
children: [
Container(
height: 20.0,
width: 20.0,
color: trashTypeColor,
),
SizedBox(
width: 10.0,
),
Text(trashPickUpsModel.trashTypes[index]),
],
),
);
}),
);
}
trashTitle(String title) {
return Text(
title,
style: TextStyle(
fontSize: Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.bold),
);
}
trashDetailsData(String detailsData) {
return Padding(
padding: const EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 0.0),
child: Text(
detailsData,
style: TextStyle(
fontSize: Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.normal),
),
);
}
trashAvailableDatesTimes(
bool isDate, String titleS, String dataS, String titleR, String dataR) {
IconData typeIcon;
if (isDate) {
typeIcon = Icons.date_range_rounded;
} else {
typeIcon = Icons.access_time_rounded;
}
return Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(
typeIcon,
size: 35.0,
),
SizedBox(
width: 10.0,
),
Column(
children: [
trashTitle(titleS),
trashDetailsData(dataS),
],
),
],
),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(
typeIcon,
size: 35.0,
),
SizedBox(
width: 10.0,
),
Column(
children: [
trashTitle(titleR),
trashDetailsData(dataR),
],
),
],
),
],
);
}
Widget trashDetails() {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("Users")
.doc(widget.userID)
.collection('Trash Pick Ups')
.where('trashID', isEqualTo: widget.trashID)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
//return profileHeaderShimmer();
return Text(
"Data Unavailable",
style: TextStyle(
fontSize: Theme.of(context).textTheme.headline6.fontSize,
fontWeight: FontWeight.bold),
);
} else {
TrashPickUpsModel trashPickUpsModel =
TrashPickUpsModel.fromDocument(snapshot.data.docs[0]);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"${trashPickUpsModel.trashName}",
style: TextStyle(
fontSize: Theme.of(context).textTheme.headline5.fontSize,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 20.0,
),
ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Image.network(
trashPickUpsModel.trashImage,
height: 200.0,
width: MediaQuery.of(context).size.width,
fit: BoxFit.cover,
),
),
SizedBox(
height: 20.0,
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
trashTitle("Trash Location"),
trashDetailsData(trashPickUpsModel.trashLocationAddress),
SizedBox(
height: 20.0,
),
trashTitle("Trash Description"),
trashDetailsData(trashPickUpsModel.trashDescription),
SizedBox(
height: 20.0,
),
trashTitle("Trash Types"),
trashDetailsData(trashPickUpsModel.trashTypes.toString()),
trashTypesFilter(trashPickUpsModel),
trashAvailableDatesTimes(
true,
"Start Date",
trashPickUpsModel.startDate,
"Return Date",
trashPickUpsModel.returnDate),
SizedBox(
height: 20.0,
),
trashAvailableDatesTimes(
false,
"Start Time",
trashPickUpsModel.startTime,
"Return Time",
trashPickUpsModel.returnTime),
SizedBox(
height: 20.0,
),
trashTitle("Posted Date"),
trashDetailsData(trashPickUpsModel.postedDate),
SizedBox(
height: 20.0,
),
Center(
child: widget.accountType == "Trash Picker"
? MinButtonWidget(
text: "Edit Trash Pick Up",
color: Theme.of(context).backgroundColor,
onClicked: () =>
{print("Edit Trash Pick Ups Pressed!")},
)
: Container(),
),
],
),
],
);
}
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: SecondaryAppBar(
title: "About Trash",
appBar: AppBar(),
widgets: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: Image.asset(
"assets/icons/icon_trash_sort.png",
height: 35.0,
width: 35.0,
))
],
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: trashDetails(),
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar
|
mirrored_repositories/trashpick/lib/Pages/BottomNavBar/Home/home_page.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:trashpick/Models/user_model.dart';
import 'package:trashpick/Theme/theme_provider.dart';
import '../../../Widgets/primary_app_bar_widget.dart';
class HomePage extends StatefulWidget {
final String accountType;
HomePage(this.accountType);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final userReference = FirebaseFirestore.instance.collection('Users');
final FirebaseAuth auth = FirebaseAuth.instance;
String badgeType;
@override
void initState() {
_setBadgeType();
super.initState();
}
_setBadgeType() {
if (widget.accountType == "Trash Picker") {
badgeType = "Picker";
} else if (widget.accountType == "Trash Collector") {
badgeType = "Collector";
}
}
_statTitle(String title) {
return Text(
title,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.bold),
);
}
_statDetail(double numberValue, bool isDouble) {
String detailString;
if (isDouble) {
detailString = numberValue.toString();
} else {
detailString = numberValue.toInt().toString();
}
return Text(
detailString,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.bold),
);
}
_badgeRequiresPoints(String points) {
return Text(
points,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: Theme.of(context).textTheme.subtitle1.fontSize,
fontWeight: FontWeight.normal),
);
}
_badgeDesignsWidget(String image, String badgeName, String badgePoints) {
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset(
image,
height: 60.0,
width: 60.0,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_statTitle(badgeName),
_badgeRequiresPoints(badgePoints),
],
)
],
);
}
welcomeHeader() {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("Users")
.where('uuid', isEqualTo: "${auth.currentUser.uid}")
.snapshots(),
builder: (context, dataSnapshot) {
if (!dataSnapshot.hasData) {
//return profileHeaderShimmer();
return Text(
"Hi! ",
style: TextStyle(
fontSize: Theme.of(context).textTheme.headline6.fontSize,
fontWeight: FontWeight.bold),
);
} else {
UserModelClass userModelClass =
UserModelClass.fromDocument(dataSnapshot.data.docs[0]);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Hi! ${userModelClass.name}",
style: TextStyle(
fontSize: Theme.of(context).textTheme.headline6.fontSize,
fontWeight: FontWeight.normal),
),
],
);
}
},
);
}
_profileStats() {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_statTitle("Total Trash Pick Ups"),
SizedBox(
height: 10.0,
),
_statTitle("Total Points"),
],
),
SizedBox(
width: 20.0,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_statDetail(4, false),
SizedBox(
height: 10.0,
),
_statDetail(52, false),
],
)
],
),
Column(
children: [
Image.asset(
'assets/images/badge_starter.png',
height: 70.0,
width: 70.0,
),
SizedBox(
height: 5.0,
),
_statTitle("Starter\n$badgeType"),
],
)
],
);
}
_badgeDetails() {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
widget.accountType == "Trash Picker"
? _statTitle("Schedule more trash pick ups to unlock the,")
: _statTitle("Collect more trash to unlock the,"),
SizedBox(
height: 10.0,
),
_badgeDesignsWidget('assets/images/badge_bronze.png',
"Bronze $badgeType", "100 Points"),
SizedBox(
height: 10.0,
),
_badgeDesignsWidget('assets/images/badge_silver.png',
"Silver $badgeType", "1000 Points"),
SizedBox(
height: 10.0,
),
_badgeDesignsWidget(
'assets/images/badge_gold.png', "Gold $badgeType", "10000 Points"),
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PrimaryAppBar(
title: "TrashPick",
appBar: AppBar(),
widgets: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: Icon(
Icons.home_rounded,
color: Theme.of(context).iconTheme.color,
size: 35.0,
),
)
],
),
body: SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Image.asset(
'assets/logos/trashpick_logo_curved.png',
height: 75.0,
width: 75.0,
),
SizedBox(
height: 10.0,
),
welcomeHeader(),
Center(
child: Text(
"Welcome",
style: TextStyle(
fontSize:
Theme.of(context).textTheme.headline5.fontSize,
fontWeight: FontWeight.bold),
),
),
SizedBox(
height: 20.0,
),
/* Text(
"${widget.accountType}",
style: TextStyle(
fontSize: Theme.of(context).textTheme.headline4.fontSize,
fontWeight: FontWeight.bold),
),*/
_profileStats(),
SizedBox(
height: 30.0,
),
_badgeDetails(),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages
|
mirrored_repositories/trashpick/lib/Pages/OnAppStart/user_guide.dart
|
import 'package:flutter/material.dart';
import 'package:trashpick/Pages/OnAppStart/sign_in_page.dart';
import 'package:trashpick/Pages/OnAppStart/sign_up_page.dart';
import 'package:trashpick/Pages/OnAppStart/welcome_page.dart';
import 'package:trashpick/Theme/theme_provider.dart';
import 'package:trashpick/Widgets/secondary_app_bar_widget.dart';
import 'package:webview_flutter/webview_flutter.dart';
class UserGuidePage extends StatefulWidget {
@override
_UserGuidePageState createState() => _UserGuidePageState();
}
class _UserGuidePageState extends State<UserGuidePage> {
final _key = UniqueKey();
bool isLoading = true;
String siteLink =
"https://sites.google.com/view/trashpick--app-user-guide/home";
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
print("test");
return Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => WelcomePage()),
(Route<dynamic> route) => false,
);
},
child: Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).appBarTheme.backgroundColor,
leading: IconButton(
icon: Icon(Icons.arrow_back_ios_rounded,
color: Theme.of(context).iconTheme.color),
onPressed: () {
print("Go to Welcome Page");
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => WelcomePage()),
(Route<dynamic> route) => false,
);
},
),
title: Text(
"User Guide",
style: Theme.of(context).textTheme.headline6,
),
elevation: Theme.of(context).appBarTheme.elevation,
actions: [
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: TextButton(
child: Text(
"Continue to Sign Up",
style: Theme.of(context).textTheme.subtitle2,
),
onPressed: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => SignUpPage()),
(Route<dynamic> route) => false,
);
print("Switch to Sign Up");
},
),
)
],
),
body: SafeArea(
child: Stack(
children: [
WebView(
key: _key,
initialUrl: siteLink,
javascriptMode: JavascriptMode.unrestricted,
onPageFinished: (finish) {
setState(() {
isLoading = false;
});
},
),
isLoading
? Center(
child: CircularProgressIndicator(),
)
: Stack(),
],
),
),
));
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages
|
mirrored_repositories/trashpick/lib/Pages/OnAppStart/welcome_page.dart
|
import 'package:flutter/material.dart';
import 'package:trashpick/Pages/OnAppStart/sign_in_page.dart';
import 'package:trashpick/Pages/OnAppStart/sign_up_page.dart';
import '../../Theme/theme_provider.dart';
import '../../Widgets/button_widgets.dart';
import 'user_guide.dart';
class WelcomePage extends StatefulWidget {
@override
_WelcomePageState createState() => _WelcomePageState();
}
class _WelcomePageState extends State<WelcomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppThemeData().whiteColor,
body: SafeArea(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(height: 40),
Image.asset(
'assets/logos/trashpick_logo_banner_2.png',
height: 250,
width: 250,
),
SizedBox(height: 30),
new ButtonWithImageWidget(
onClicked: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => SignInPage()),
(Route<dynamic> route) => false,
);
print("Switch to Continue with Email");
},
text: "Continue with Email",
textColor: Colors.white,
image: 'assets/icons/icon_email.png',
color: AppThemeData().secondaryColor,
),
SizedBox(height: 30),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text("New to TrashPick ?",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
)),
SizedBox(width: 10),
new RadiusFlatButtonWidget(
text: "Sign Up",
onClicked: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => UserGuidePage()),
(Route<dynamic> route) => false,
);
print("Switch to Sign Up");
},
),
],
),
],
),
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages
|
mirrored_repositories/trashpick/lib/Pages/OnAppStart/welcome_guide_page.dart
|
import 'package:flutter/material.dart';
import '../../Pages/BottomNavBar/bottom_nav_bar.dart';
import '../../Theme/theme_provider.dart';
import '../../Widgets/button_widgets.dart';
class WelcomeGuidePage extends StatefulWidget {
final String userName, accountTypeName;
WelcomeGuidePage(this.userName, this.accountTypeName);
@override
_WelcomeGuidePageState createState() => _WelcomeGuidePageState();
}
class _WelcomeGuidePageState extends State<WelcomeGuidePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppThemeData().whiteColor,
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Hi " + widget.userName,
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Montserrat',
fontSize:
Theme.of(context).textTheme.headline5.fontSize,
fontWeight: FontWeight.bold)
.copyWith(color: Colors.grey.shade900)),
SizedBox(
height: 50.0,
),
Image.asset(
'assets/logos/trashpick_logo_banner.png',
height: 200.0,
width: 200.0,
),
SizedBox(
height: 20.0,
),
Text("Welcome to TrashPick",
textAlign: TextAlign.center,
style: TextStyle(fontFamily: 'Montserrat', fontSize: 18.0)
.copyWith(color: Colors.grey.shade900)),
SizedBox(
height: 100.0,
),
new ButtonWidget(
color: AppThemeData().secondaryColor,
textColor: AppThemeData().whiteColor,
text: "Continue to Home",
onClicked: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
BottomNavBar(widget.accountTypeName),
),
(route) => false,
);
},
)
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages
|
mirrored_repositories/trashpick/lib/Pages/OnAppStart/check_permissions.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../Pages/OnAppStart/welcome_page.dart';
import '../../Theme/theme_provider.dart';
import '../../Widgets/button_widgets.dart';
class CheckAppPermissions extends StatefulWidget {
@override
_CheckAppPermissionsState createState() => _CheckAppPermissionsState();
}
class _CheckAppPermissionsState extends State<CheckAppPermissions> {
bool locationPermission = false;
bool cameraPermission = false;
bool storagePermission = false;
_requestLocationPermission() async {
print("----------------------- REQUEST LOCATION PERMISSION CALLED!");
final serviceStatus = await Permission.locationWhenInUse.serviceStatus;
final isGpsOn = serviceStatus == ServiceStatus.enabled;
if (!isGpsOn) {
print('TURN ON LOCATION SERVICE BEFORE REQUESTING PERMISSION.');
return;
}
final status = await Permission.locationWhenInUse.request();
if (status == PermissionStatus.granted) {
print('LOCATION PERMISSION GRANTED!');
setState(() {
locationPermission = true;
});
} else if (status == PermissionStatus.denied) {
print('LOCATION PERMISSION DENIED!');
displayPermissionAlert(context, "Location");
print(
"----------------------- DISPLAY_PERMISSION_ALERT - LOCATION CALLED!");
} else if (status == PermissionStatus.permanentlyDenied) {
print('TAKE THE USER TO APP SETTINGS');
await openAppSettings();
}
}
_requestCameraPermission() async {
print("----------------------- REQUEST CAMERA PERMISSION CALLED!");
final status = await Permission.camera.request();
if (status == PermissionStatus.granted) {
print('CAMERA PERMISSION GRANTED!');
setState(() {
cameraPermission = true;
});
} else if (status == PermissionStatus.denied) {
print('CAMERA PERMISSION DENIED!');
displayPermissionAlert(context, "Camera");
print(
"----------------------- DISPLAY_PERMISSION_ALERT - CAMERA CALLED!");
} else if (status == PermissionStatus.permanentlyDenied) {
print('TAKE THE USER TO APP SETTINGS');
await openAppSettings();
}
}
_requestStoragePermission() async {
print("----------------------- REQUEST STORAGE PERMISSION CALLED!");
final status = await Permission.storage.request();
if (status == PermissionStatus.granted) {
print('Storage Permission granted.');
setState(() {
storagePermission = true;
});
} else if (status == PermissionStatus.denied) {
print('Storage Permission denied.');
displayPermissionAlert(context, "Storage");
print(
"----------------------- DISPLAY_PERMISSION_ALERT - STORAGE CALLED!");
} else if (status == PermissionStatus.permanentlyDenied) {
print('TAKE THE USER TO APP SETTINGS');
await openAppSettings();
}
}
_openAppSettings() async {
await openAppSettings();
}
displayPermissionAlert(
BuildContext contextDisplayPermissionAlert, String permissionName) {
Widget cancelButton = TextButton(
child: Text("Cancel"),
onPressed: () {
print('DISPLAY PERMISSION ALERT - CANCELED!');
Navigator.pop(contextDisplayPermissionAlert);
displayPermissionRequest(context);
},
);
Widget continueButton = TextButton(
child: Text("Give Permission"),
onPressed: () {
print("DISPLAY PERMISSION ALERT - GIVE PERMISSION!");
if (permissionName == "Location") {
_requestLocationPermission();
} else if (permissionName == "Camera") {
_requestCameraPermission();
} else if (permissionName == "Storage") {
_requestStoragePermission();
}
Navigator.pop(contextDisplayPermissionAlert);
},
);
AlertDialog alert = AlertDialog(
title: Text("$permissionName Permission Required"),
content: Text("You must have to grant the $permissionName for continue."),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10.0))),
actions: [
cancelButton,
continueButton,
],
);
showDialog(
context: contextDisplayPermissionAlert,
barrierDismissible: false,
builder: (BuildContext contextDisplayPermissionAlert) {
return WillPopScope(
onWillPop: () {
return Future.value(false);
},
child: alert);
},
);
}
displayPermissionRequest(BuildContext contextDisplayPermissionRequest) {
Widget denyButton = TextButton(
child: Text("Quite From App"),
onPressed: () {
print("----------------------- QUITE FROM APP!");
SystemNavigator.pop();
},
);
Widget allowButton = TextButton(
child: Text("Allow Permission"),
onPressed: () async {
print("----------------------- ALLOW PERMISSION PRESSED!");
Navigator.pop(contextDisplayPermissionRequest);
_requestLocationPermission();
},
);
AlertDialog alert = AlertDialog(
title: Text("Permission Required"),
content: Text(
"We request access to your location, camera, and storage space. "
"The app will capture your location in order to locate you and give you access to the map. "
"The camera will be used to capture photographs for use in postings and events. "
"Storage access is looking for photos to use in your picker."),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10.0))),
actions: [
denyButton,
allowButton,
],
);
showDialog(
context: contextDisplayPermissionRequest,
barrierDismissible: false,
builder: (BuildContext contextDisplayPermissionRequest) {
return WillPopScope(
onWillPop: () {
return Future.value(false);
},
child: alert);
},
);
}
@override
void initState() {
print(
"----------------------- CHECK PERMISSION PAGE INITIALIZED -----------------------");
super.initState();
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => showDialog<bool>(
context: context,
builder: (c) => AlertDialog(
title: Text('Exit from TrashPick'),
content: Text('Do you really want to exit'),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10.0))),
actions: [
TextButton(
child: Text('Yes'),
onPressed: () => Navigator.pop(c, true),
),
TextButton(
child: Text('No'),
onPressed: () => Navigator.pop(c, false),
),
],
)),
child: Scaffold(
backgroundColor: AppThemeData().whiteColor,
body: SafeArea(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(height: 20),
Image.asset(
'assets/logos/trashpick_logo_banner.png',
height: 150,
width: 150,
),
SizedBox(height: 30),
Text(
'Permission required ',
style:
TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
),
SizedBox(
height: 20.0,
),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Column(
children: [
Image.asset(
'assets/images/location.png',
scale: 3.0,
),
SizedBox(
height: 10.0,
),
Text(
"Location",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: Theme.of(context)
.textTheme
.subtitle1
.fontSize),
)
],
),
Column(
children: [
Image.asset(
'assets/images/camera.png',
scale: 3.0,
),
SizedBox(
height: 10.0,
),
Text(
"Camera",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: Theme.of(context)
.textTheme
.subtitle1
.fontSize),
)
],
),
Column(
children: [
Image.asset(
'assets/images/storage.png',
scale: 3.0,
),
SizedBox(
height: 10.0,
),
Text(
"Storage",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: Theme.of(context)
.textTheme
.subtitle1
.fontSize),
)
],
),
],
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Text(
"We request access to your location, camera, and storage space. "
"The app will capture your location in order to locate you and give you access to the map. "
"The camera will be used to capture photographs for use in postings and events. "
"Storage access is looking for photos to use in your picker.",
style: TextStyle(
fontSize:
Theme.of(context).textTheme.subtitle1.fontSize),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Column(
children: [
Row(
children: [
locationPermission
? Image.asset(
'assets/icons/icon_approval.png',
scale: 4.0,
)
: Image.asset(
'assets/icons/icon_access_denied.png',
scale: 4.0,
),
TextButton(
child: Text(
'Click to allow location permission',
style: TextStyle(
color: AppThemeData().secondaryColor),
),
onPressed: _requestLocationPermission,
),
],
),
Row(
children: [
cameraPermission
? Image.asset(
'assets/icons/icon_approval.png',
scale: 4.0,
)
: Image.asset(
'assets/icons/icon_access_denied.png',
scale: 4.0,
),
TextButton(
child: Text(
'Click to allow camera permission',
style: TextStyle(
color: AppThemeData().secondaryColor),
),
onPressed: _requestCameraPermission,
),
],
),
Row(
children: [
storagePermission
? Image.asset(
'assets/icons/icon_approval.png',
scale: 4.0,
)
: Image.asset(
'assets/icons/icon_access_denied.png',
scale: 4.0,
),
TextButton(
child: Text(
'Click to allow storage permission',
style: TextStyle(
color: AppThemeData().secondaryColor),
),
onPressed: _requestStoragePermission,
),
],
),
],
),
),
SizedBox(
height: 20.0,
),
locationPermission && cameraPermission && storagePermission
? ButtonWidget(
color: AppThemeData().secondaryColor,
onClicked: () {
print(
"----------------------- Continue to App -----------------------");
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
WelcomePage(),
),
(route) => false,
);
},
text: "Continue to App",
textColor: AppThemeData().whiteColor,
)
: Container(),
],
),
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages
|
mirrored_repositories/trashpick/lib/Pages/OnAppStart/sign_in_page.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:trashpick/Pages/BottomNavBar/bottom_nav_bar.dart';
import 'package:trashpick/Pages/OnAppStart/sign_up_page.dart';
import 'package:trashpick/Pages/OnAppStart/welcome_page.dart';
import '../../Theme/theme_provider.dart';
import '../../Widgets/button_widgets.dart';
import '../../Widgets/toast_messages.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'user_guide.dart';
class SignInPage extends StatefulWidget {
@override
_SignInPageState createState() => _SignInPageState();
}
class _SignInPageState extends State<SignInPage> {
ToastMessages _toastMessages = new ToastMessages();
TextEditingController emailController = TextEditingController();
TextEditingController passwordController = TextEditingController();
bool _isHidden = true;
bool isUserSigned = false;
bool isInValidaAccount = false;
double circularProgressVal;
FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
String accountType;
void _togglePasswordView() {
setState(() {
_isHidden = !_isHidden;
});
}
showAlertDialog(BuildContext context) {
// show the dialog
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: !isUserSigned
? Center(child: Text("Sign In"))
: Center(child: Text("Welcome Back")),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (!isUserSigned)
!isInValidaAccount
? Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30.0,
),
CircularProgressIndicator(
value: circularProgressVal,
strokeWidth: 6,
valueColor: AlwaysStoppedAnimation<Color>(
AppThemeData().primaryColor),
),
SizedBox(
height: 30.0,
),
Text("Signing to your account...",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 16.0)
.copyWith(color: Colors.grey.shade900)),
],
)
: Container(
child: Column(
children: [
Text("Error!",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
)),
SizedBox(
height: 50.0,
),
new ButtonWidget(
text: "Try Again",
color: AppThemeData().redColor,
textColor: AppThemeData().whiteColor,
onClicked: () {
setState(() {
isUserSigned = false;
isInValidaAccount = false;
Navigator.pop(context);
});
}),
],
))
else
Container(
child: Column(
children: [
Text("Welcome!",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
)),
SizedBox(
height: 50.0,
),
Image.asset(
'assets/images/welcome.png',
height: 100,
width: 100,
),
SizedBox(
height: 50.0,
),
new ButtonWidget(
text: "Continue",
textColor: AppThemeData().whiteColor,
color: AppThemeData().primaryColor,
onClicked: () {
Navigator.pop(context);
}),
],
)),
],
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0))),
);
},
);
},
);
}
void ifAnError() {
Navigator.pop(context);
setState(() {
isUserSigned = false;
isInValidaAccount = true;
//Navigator.pop(context);
showAlertDialog(context);
});
}
bool validateUser() {
const pattern = r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$';
final regExp = RegExp(pattern);
if (emailController.text.isEmpty && passwordController.text.isEmpty) {
_toastMessages.toastInfo('Please fill details', context);
} else if (emailController.text.isEmpty) {
_toastMessages.toastInfo('Email is empty', context);
} else if (!regExp.hasMatch(emailController.text)) {
_toastMessages.toastInfo('Email pattern is wrong', context);
} else if (passwordController.text.isEmpty) {
_toastMessages.toastInfo('Password is empty', context);
} else {
print('Validation Success!');
return true;
}
return false;
}
geAccountType(String userID) async {
print("----------------------- CHECK ACCOUNT TYPE -----------------------");
await FirebaseFirestore.instance
.collection('Users')
.doc(userID)
.get()
.then((value) {
accountType = value.data()["accountType"];
});
}
void _signInWithEmailAndPassword() async {
showAlertDialog(context);
setState(() {
isUserSigned = false;
isInValidaAccount = false;
});
try {
UserCredential userCredential = await FirebaseAuth.instance
.signInWithEmailAndPassword(
email: emailController.text, password: passwordController.text);
print(userCredential.user.uid.toString());
await geAccountType(userCredential.user.uid.toString());
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (BuildContext context) => BottomNavBar(accountType),
),
(route) => false,
);
//Navigator.pop(context);
print('User is signed in!');
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
ifAnError();
print('No user found for that email.');
_toastMessages.toastError("No user found for that email", context);
} else if (e.code == 'wrong-password') {
ifAnError();
print('Wrong password provided for that user.');
_toastMessages.toastError("Wrong password provided!", context);
} else {
_toastMessages.toastError("Something Went Wrong.", context);
_toastMessages.toastError(e.toString(), context);
print(e.toString());
}
}
}
Future<void> firebaseSignIn() async {
try {
await _firebaseAuth.signInWithEmailAndPassword(
email: emailController.text, password: passwordController.text);
_toastMessages.toastSuccess("Signed In", context);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
_toastMessages.toastError("No user found for that email.", context);
} else if (e.code == 'wrong-password') {
_toastMessages.toastError(
"Wrong password provided for that user.", context);
} else {
_toastMessages.toastError("Something Went Wrong.", context);
_toastMessages.toastError(e.toString(), context);
print(e.toString());
}
}
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
print("test");
return Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => WelcomePage()),
(Route<dynamic> route) => false,
);
},
child: Scaffold(
backgroundColor: AppThemeData().whiteColor,
body: SafeArea(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Container(
alignment: Alignment.topLeft,
child: IconButton(
icon: Icon(Icons.arrow_back_ios_rounded),
onPressed: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => WelcomePage()),
(Route<dynamic> route) => false,
);
})),
SizedBox(height: 20),
Image.asset(
'assets/logos/trashpick_logo_banner.png',
height: 200,
width: 200,
),
SizedBox(height: 20),
Container(
padding: EdgeInsets.all(10),
height: 70.0,
child: TextFormField(
controller: emailController,
decoration: InputDecoration(
contentPadding: EdgeInsets.zero,
prefixIcon: Icon(Icons.email_outlined),
border: OutlineInputBorder(),
labelText: 'Email',
),
),
),
Container(
padding: EdgeInsets.all(10),
height: 70.0,
child: TextFormField(
obscureText: _isHidden,
controller: passwordController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
prefixIcon: Icon(Icons.lock_outline_rounded),
suffix: InkWell(
onTap: _togglePasswordView,
child: Icon(
_isHidden
? Icons.visibility
: Icons.visibility_off,
color: Colors.grey.shade800,
),
),
).copyWith(isDense: true),
),
),
SizedBox(height: 20),
new ButtonWidget(
textColor: AppThemeData().whiteColor,
color: AppThemeData().secondaryColor,
text: "Sign In",
onClicked: () {
if (validateUser()) {
_signInWithEmailAndPassword();
print("Sign In");
} else {
_toastMessages.toastInfo(
'Try again with correct details!', context);
}
},
),
SizedBox(height: 20),
/* new TextButtonWidget(
onClicked: () {
*/ /* Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => ForgotPassword()),
(Route<dynamic> route) => false,
);*/ /*
print("Switch to Forgot Password!");
},
text: "Forgot Password?"),*/
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text("New to TrashPick?",
style: TextStyle(
fontSize:
Theme.of(context).textTheme.button.fontSize,
fontWeight: FontWeight.bold,
)),
SizedBox(width: 10),
new RadiusFlatButtonWidget(
text: "Sign Up",
onClicked: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => UserGuidePage()),
(Route<dynamic> route) => false,
);
print("Switch to Sign Up");
},
),
],
),
)
],
),
),
))));
}
}
| 0
|
mirrored_repositories/trashpick/lib/Pages
|
mirrored_repositories/trashpick/lib/Pages/OnAppStart/sign_up_page.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:trashpick/Pages/OnAppStart/sign_in_page.dart';
import 'package:trashpick/Pages/OnAppStart/user_guide.dart';
import 'package:trashpick/Pages/OnAppStart/welcome_guide_page.dart';
import 'package:trashpick/Pages/OnAppStart/welcome_page.dart';
import '../../Widgets/toast_messages.dart';
import '../../Theme/theme_provider.dart';
import '../../Widgets/button_widgets.dart';
class SignUpPage extends StatefulWidget {
/* SignUpPage({Key key, this.title}) : super(key: key);
final String title;*/
SignUpPage({this.app});
final FirebaseApp app;
@override
_SignUpPageState createState() => _SignUpPageState();
}
class _SignUpPageState extends State<SignUpPage> {
ToastMessages _toastMessages = new ToastMessages();
FirebaseAuth firebaseAuth = FirebaseAuth.instance;
TextEditingController nameController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController phoneNumberController = TextEditingController();
TextEditingController homeAddressController = TextEditingController();
TextEditingController passwordController = TextEditingController();
TextEditingController confirmPasswordController = TextEditingController();
String defaultUserAvatar =
"https://firebasestorage.googleapis.com/v0/b/trashpick-db.appspot.com/o/Default%20User%20Avatar%2Ftrashpick_user_avatar.png?alt=media&token=734f7e74-2c98-4c27-b982-3ecd072ced79";
bool _isHidden = true;
bool _isHiddenC = true;
double circularProgressVal;
bool isUserCreated = false;
bool isAnError = false;
String formattedDate = DateFormat('dd-MM-yyyy').format(DateTime.now());
String formattedTime = DateFormat('kk:mm:a').format(DateTime.now());
String accountTypeName = "Trash Picker";
int accountTypeID;
void _togglePasswordView() {
setState(() {
_isHidden = !_isHidden;
});
}
void _toggleConfirmPasswordView() {
setState(() {
_isHiddenC = !_isHiddenC;
});
}
bool validateUser() {
const pattern = r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$';
final regExp = RegExp(pattern);
if (nameController.text.isEmpty &&
emailController.text.isEmpty &&
phoneNumberController.text.isEmpty &&
homeAddressController.text.isEmpty &&
passwordController.text.isEmpty &&
confirmPasswordController.text.isEmpty) {
_toastMessages.toastInfo('Please fill details', context);
} else if (nameController.text.isEmpty) {
_toastMessages.toastInfo('Name is empty', context);
} else if (emailController.text.isEmpty) {
_toastMessages.toastInfo('Email is empty', context);
} else if (!regExp.hasMatch(emailController.text)) {
_toastMessages.toastInfo('Email pattern is wrong', context);
} else if (phoneNumberController.text.isEmpty) {
_toastMessages.toastInfo('Phone Number is empty', context);
} else if (homeAddressController.text.isEmpty) {
_toastMessages.toastInfo('Home Address is empty', context);
} else if (passwordController.text.length < 6) {
_toastMessages.toastInfo(
'Password Should Be At Least 6 Characters!', context);
} else if (passwordController.text.isEmpty) {
_toastMessages.toastInfo('Password is empty', context);
} else if (confirmPasswordController.text != passwordController.text) {
_toastMessages.toastInfo('Confirm Password is wrong', context);
} else {
print('Validation Success!');
return true;
}
return false;
}
showAlertDialog(BuildContext context) {
// show the dialog
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: !isUserCreated
? Center(child: Text("Creating Account"))
: Center(child: Text("Account Created")),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (!isUserCreated)
!isAnError
? Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30.0,
),
CircularProgressIndicator(
value: circularProgressVal,
strokeWidth: 6,
valueColor: AlwaysStoppedAnimation<Color>(
AppThemeData().primaryColor),
),
SizedBox(
height: 30.0,
),
Text(
"Hi " +
nameController.text +
", Please wait until we create your account!",
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 16.0)
.copyWith(color: Colors.grey.shade900)),
],
)
: Container(
child: Column(
children: [
Text("Error!",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
)),
SizedBox(
height: 50.0,
),
new ButtonWidget(
text: "Try Again",
textColor: AppThemeData().whiteColor,
color: AppThemeData().redColor,
onClicked: () {
Navigator.pop(context);
}),
],
))
else
Container(
child: Column(
children: [
Text("Welcome!",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
)),
SizedBox(
height: 50.0,
),
Image.asset(
'assets/images/welcome.png',
height: 100,
width: 100,
),
SizedBox(
height: 50.0,
),
new ButtonWidget(
text: "Continue",
textColor: AppThemeData().whiteColor,
color: AppThemeData().primaryColor,
onClicked: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => WelcomeGuidePage(
nameController.text.toString(),
accountTypeName)),
ModalRoute.withName("/WelcomeScreen"));
}),
],
)),
],
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0))),
);
},
);
},
);
}
void ifAnError() {
Navigator.pop(context);
setState(() {
isUserCreated = false;
isAnError = true;
//Navigator.pop(context);
showAlertDialog(context);
});
}
void printSignUpData() {
print("ACCOUNT TYPE: " + "$accountTypeName");
print("NAME: " + nameController.text.toString());
print("EMAIL: " + emailController.text.toString());
print("CONTACT NUMBER: " + phoneNumberController.text.toString());
print("HOME ADDRESS: " + homeAddressController.text.toString());
print("PASSWORD: " + passwordController.text.toString());
print("CONFIRM PASSWORD: " + confirmPasswordController.text.toString());
}
void authenticateUser() async {
showAlertDialog(context);
setState(() {
isUserCreated = false;
isAnError = false;
});
try {
await firebaseAuth.createUserWithEmailAndPassword(
email: emailController.text, password: passwordController.text);
if (FirebaseAuth.instance.currentUser.uid != null) {
print('User Account Authenticated!');
User user = FirebaseAuth.instance.currentUser;
if (!user.emailVerified) {
await user.sendEmailVerification();
print('Verification Email Send!');
}
try {
FirebaseFirestore.instance
.collection("Users")
.doc(FirebaseAuth.instance.currentUser.uid.toString())
.set({
"uuid": FirebaseAuth.instance.currentUser.uid.toString(),
"accountType": "$accountTypeName",
"name": nameController.text,
"email": emailController.text,
"contactNumber": phoneNumberController.text,
"homeAddress": homeAddressController.text,
'password': passwordController.text,
'appearedLocation': new GeoPoint(7.8731, 80.7718),
'lastAppeared': "Not Set",
'accountCreated': "$formattedDate, $formattedTime",
'profileImage': "$defaultUserAvatar",
}).then((value) {
print("User Added to Firestore success");
Navigator.pop(context);
setState(() {
isUserCreated = true;
isAnError = false;
showAlertDialog(context);
});
});
} catch (e) {
print("Failed to Add User to Firestore!: $e");
ifAnError();
}
} else {
print('Failed to User Account Authenticated!');
ifAnError();
}
} catch (e) {
print(e.toString());
if (e.toString() ==
"[firebase_auth/email-already-in-use] The email address is already in use by another account.") {
ifAnError();
new ToastMessages().toastError(
"The email address is already in use by another account", context);
} else {
ifAnError();
print(e.toString());
}
}
}
radioButtonList() {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"Select Account Type",
style: TextStyle(
fontSize: Theme.of(context).textTheme.headline6.fontSize,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Radio(
value: 1,
groupValue: accountTypeID,
onChanged: (val) {
setState(() {
accountTypeName = 'Trash Picker';
accountTypeID = 1;
});
},
),
Text(
'Trash Picker',
style: new TextStyle(fontSize: 17.0),
),
Radio(
value: 2,
groupValue: accountTypeID,
onChanged: (val) {
setState(() {
accountTypeName = 'Trash Collector';
accountTypeID = 2;
});
},
),
Text(
'Trash Collector',
style: new TextStyle(
fontSize: 17.0,
),
),
],
),
],
);
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
print("test");
return Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => UserGuidePage()),
(Route<dynamic> route) => false,
);
},
child: Scaffold(
backgroundColor: AppThemeData().whiteColor,
body: SafeArea(
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(10),
child: Column(
children: [
Container(
alignment: Alignment.topLeft,
child: IconButton(
icon: Icon(Icons.arrow_back_ios_rounded),
onPressed: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => UserGuidePage()),
(Route<dynamic> route) => false,
);
})),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/logos/trashpick_logo_banner.png',
height: 120,
width: 120,
),
SizedBox(width: 10),
Text("Create an account \nwith sign up",
style: TextStyle(
fontSize: Theme.of(context)
.textTheme
.headline5
.fontSize,
fontWeight: FontWeight.bold,
)),
],
),
SizedBox(height: 20),
radioButtonList(),
SizedBox(height: 10),
Padding(
padding: EdgeInsets.all(10),
child: Column(
children: [
TextFormField(
controller: nameController,
decoration: InputDecoration(
contentPadding: EdgeInsets.zero,
prefixIcon: Icon(Icons.account_circle_outlined),
border: OutlineInputBorder(),
labelText: 'Name',
),
),
SizedBox(
height: 20.0,
),
TextFormField(
controller: emailController,
decoration: InputDecoration(
contentPadding: EdgeInsets.zero,
prefixIcon: Icon(Icons.email_outlined),
border: OutlineInputBorder(),
labelText: 'Email',
),
),
SizedBox(
height: 20.0,
),
TextFormField(
controller: phoneNumberController,
keyboardType: TextInputType.phone,
decoration: InputDecoration(
contentPadding: EdgeInsets.zero,
prefixIcon: Icon(Icons.phone_android_rounded),
border: OutlineInputBorder(),
labelText: 'Contact Number',
),
),
SizedBox(
height: 20.0,
),
TextFormField(
controller: homeAddressController,
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: InputDecoration(
prefixIcon: Icon(Icons.home_rounded),
border: OutlineInputBorder(),
labelText: 'Home Address',
),
),
SizedBox(
height: 20.0,
),
TextFormField(
obscureText: _isHidden,
controller: passwordController,
keyboardType: TextInputType.visiblePassword,
decoration: InputDecoration(
contentPadding:
EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
prefixIcon: Icon(Icons.lock_outline_rounded),
border: OutlineInputBorder(),
labelText: 'Password',
suffix: InkWell(
onTap: _togglePasswordView,
child: Icon(
_isHidden
? Icons.visibility
: Icons.visibility_off,
color: Colors.grey.shade800,
),
),
),
),
SizedBox(
height: 20.0,
),
TextFormField(
obscureText: _isHiddenC,
controller: confirmPasswordController,
keyboardType: TextInputType.visiblePassword,
decoration: InputDecoration(
contentPadding:
EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
prefixIcon: Icon(Icons.lock_outline_rounded),
border: OutlineInputBorder(),
labelText: 'Confirm Password',
suffix: InkWell(
onTap: _toggleConfirmPasswordView,
child: Icon(
_isHiddenC
? Icons.visibility
: Icons.visibility_off,
color: Colors.grey.shade800,
),
),
),
),
],
),
),
SizedBox(height: 20),
new ButtonWidget(
textColor: AppThemeData().whiteColor,
color: AppThemeData().secondaryColor,
text: "Sign Up",
onClicked: () {
if (validateUser()) {
printSignUpData();
authenticateUser();
} else {
/*_toastMessages.toastInfo(
'Try again with correct details!');*/
}
},
),
SizedBox(height: 20),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text("Already User?",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
)),
SizedBox(width: 10),
new RadiusFlatButtonWidget(
text: "Sign In",
onClicked: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => SignInPage()),
(Route<dynamic> route) => false,
);
print("Switch to Sign In");
},
),
],
),
)
],
))),
),
),
);
}
}
| 0
|
mirrored_repositories/trashpick/lib
|
mirrored_repositories/trashpick/lib/Widgets/primary_app_bar_widget.dart
|
import 'package:flutter/material.dart';
class PrimaryAppBar extends StatelessWidget implements PreferredSizeWidget {
final String title;
final AppBar appBar;
final List<Widget> widgets;
const PrimaryAppBar({Key key, this.title, this.appBar, this.widgets})
: super(key: key);
@override
Widget build(BuildContext context) {
return AppBar(
backgroundColor: Theme.of(context).appBarTheme.backgroundColor,
automaticallyImplyLeading: false,
title: Text(
title,
style: Theme.of(context).textTheme.headline6,
),
elevation: Theme.of(context).appBarTheme.elevation,
actions: widgets,
);
}
@override
Size get preferredSize => new Size.fromHeight(appBar.preferredSize.height);
}
| 0
|
mirrored_repositories/trashpick/lib
|
mirrored_repositories/trashpick/lib/Widgets/toast_messages.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../Theme/theme_provider.dart';
class ToastMessages {
void toastSuccess(String success, BuildContext context) {
Fluttertoast.showToast(
msg: success,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.black87,
textColor: AppThemeData().whiteColor,
fontSize: Theme.of(context).textTheme.caption.fontSize,
);
}
void toastWarning(String warning, BuildContext context) {
Fluttertoast.showToast(
msg: warning,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.black87,
textColor: AppThemeData().whiteColor,
fontSize: Theme.of(context).textTheme.caption.fontSize,
);
}
void toastInfo(String info, BuildContext context) {
Fluttertoast.showToast(
msg: info,
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.black87,
textColor: AppThemeData().whiteColor,
fontSize: Theme.of(context).textTheme.caption.fontSize,
);
}
void toastError(String error, BuildContext context) {
Fluttertoast.showToast(
msg: error,
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.black87,
textColor: AppThemeData().whiteColor,
fontSize: Theme.of(context).textTheme.caption.fontSize,
);
}
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.