Notes
Notes - notes.io |
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:googleapis/calendar/v3.dart' as calendar;
import 'package:google_sign_in/google_sign_in.dart';
import '../main.dart' show googleSignIn, GoogleHttpClient;
import 'package:firebase_auth/firebase_auth.dart';
class ShoppingListPage extends StatefulWidget {
const ShoppingListPage({super.key});
@override
State<ShoppingListPage> createState() => _ShoppingListPageState();
}
class _ShoppingListPageState extends State<ShoppingListPage> {
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
String? role; // Kullanıcının rolü (FATHER, MOTHER, BOY, GIRL)
DateTime? birthDate; // Kullanıcının doğum tarihi
final String userId = FirebaseAuth.instance.currentUser?.uid ?? '';
Map<String, List<String>> shoppingItems = {};
Map<String, Map<String, dynamic>> categoryDetails = {};
final List<String> categoryTypes = [
"Market",
"Stationery",
"Butcher",
"Greengrocer",
"Other"
];
@override
void initState() {
super.initState();
_loadShoppingData();
_getUserInfo();
}
Future<void> _loadShoppingData() async {
final userDoc = await _firestore.collection('users').doc(userId).get();
final familyRef = userDoc.data()?['familyRef'];
if (familyRef == null) return;
final shoppingDoc = await _firestore
.collection('families')
.doc(familyRef)
.collection('shoppingLists')
.doc('data')
.get();
if (shoppingDoc.exists) {
final data = shoppingDoc.data()!;
setState(() {
shoppingItems = Map<String, List<String>>.from(
(data['shoppingItems'] ?? {}).map(
(key, value) => MapEntry(key, List<String>.from(value)),
),
);
categoryDetails = Map<String, Map<String, dynamic>>.from(
(data['categoryDetails'] ?? {}).map(
(key, value) => MapEntry(key, Map<String, dynamic>.from(value)),
),
);
});
}
}
Future<void> _saveToFirestore() async {
final userDoc = await _firestore.collection('users').doc(userId).get();
final familyRef = userDoc.data()?['familyRef'];
if (familyRef == null) return;
final shoppingDoc = _firestore
.collection('families')
.doc(familyRef)
.collection('shoppingLists')
.doc('data');
await shoppingDoc.set({
'shoppingItems': shoppingItems,
'categoryDetails': categoryDetails,
});
}
void _loopProductDialog(String category) {
TextEditingController controller = TextEditingController();
showDialog(
context: context,
barrierDismissible: false,
builder: (_) => AlertDialog(
title: Text("Add Product to $category"),
content: TextField(
controller: controller,
decoration: const InputDecoration(labelText: "Product Name"),
),
actions: [
TextButton(
style: TextButton.styleFrom(
side: BorderSide(color: Colors.orange[900]!, width: 2),
),
onPressed: () => Navigator.pop(context),
child: Text("Cancel",
style: TextStyle(
color: Colors.orange[900]!, fontWeight: FontWeight.bold)),
),
ElevatedButton(
style:
ElevatedButton.styleFrom(backgroundColor: Colors.orange[900]!),
onPressed: () async {
final text = controller.text.trim();
if (text.isNotEmpty) {
setState(() {
shoppingItems[category] = [...?shoppingItems[category], text];
});
await _saveToFirestore();
}
Navigator.pop(context);
_loopProductDialog(category);
},
child: const Text("Add",
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold)),
),
],
),
);
}
void _addCategoryDialog({String? existingCategory}) {
final isEdit = existingCategory != null;
final existingDetails = isEdit ? categoryDetails[existingCategory] : null;
String selectedType = existingDetails?['type'] ?? categoryTypes.first;
bool enablePoint = existingDetails?['point'] != null;
bool enableDate = existingDetails?['date'] != null;
TextEditingController pointController = TextEditingController(
text: existingDetails?['point']?.toString() ?? '',
);
DateTime? selectedDate;
if (existingDetails?['date'] != null) {
try {
selectedDate = DateFormat('dd MMMM yyyy (EEEE)', 'en_US')
.parse(existingDetails!['date']);
} catch (_) {
selectedDate = null;
}
}
showDialog(
context: context,
builder: (_) => StatefulBuilder(
builder: (context, setState) => AlertDialog(
backgroundColor: Colors.white,
title: Text(isEdit ? "Edit List" : "New List"),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
DropdownButtonFormField<String>(
value: selectedType,
items: categoryTypes
.map((type) =>
DropdownMenuItem(value: type, child: Text(type)))
.toList(),
onChanged: (val) => setState(() => selectedType = val!),
decoration: const InputDecoration(labelText: "Category Type"),
),
Row(
children: [
Checkbox(
value: enablePoint,
onChanged: (val) => setState(() => enablePoint = val!)),
const Text("Add Points")
],
),
if (enablePoint)
TextField(
controller: pointController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(labelText: "Points"),
),
Row(
children: [
Checkbox(
value: enableDate,
onChanged: (val) async {
setState(() => enableDate = val!);
if (val!) {
final picked = await showDatePicker(
context: context,
initialDate: selectedDate ?? DateTime.now(),
firstDate: DateTime(2020),
lastDate: DateTime(2030),
);
if (picked != null) {
setState(() => selectedDate = picked);
} else {
setState(() => enableDate = false);
}
}
},
),
const Text("Add Date")
],
),
if (enableDate)
ElevatedButton(
onPressed: () async {
final picked = await showDatePicker(
context: context,
initialDate: selectedDate ?? DateTime.now(),
firstDate: DateTime(2020),
lastDate: DateTime(2030),
);
if (picked != null) {
setState(() => selectedDate = picked);
}
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.orange[900]!),
child: Text(
selectedDate == null
? "Select Date"
: DateFormat('dd MMMM yyyy (EEEE)', 'en_US')
.format(selectedDate!),
style: const TextStyle(color: Colors.white),
),
),
],
),
),
actions: [
TextButton(
style: TextButton.styleFrom(
side: BorderSide(color: Colors.orange[900]!, width: 2),
),
onPressed: () => Navigator.pop(context),
child: Text("Cancel",
style: TextStyle(
color: Colors.orange[900]!, fontWeight: FontWeight.bold)),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.orange[900]!),
onPressed: () async {
final id = existingCategory ?? DateTime.now().millisecondsSinceEpoch.toString();
final point = enablePoint
? int.tryParse(pointController.text.trim()) ?? 0
: null;
final date = enableDate && selectedDate != null
? DateFormat('dd MMMM yyyy (EEEE)', 'en_US').format(selectedDate!)
: null;
setState(() {
if (isEdit && existingCategory != id) {
shoppingItems.remove(existingCategory);
categoryDetails.remove(existingCategory);
}
shoppingItems[id] = shoppingItems[id] ?? [];
categoryDetails[id] = {
'type': selectedType,
'point': point,
'date': date,
'completed': existingDetails?['completed'] ?? false,
'completedBy': existingDetails?['completedBy'],
'completedDate': existingDetails?['completedDate'],
};
});
if (Navigator.canPop(context)) {
Navigator.pop(context);
}
await _saveToFirestore();
if (!isEdit) {
Future.delayed(const Duration(milliseconds: 300), () {
_loopProductDialog(id);
});
}
},
child: Text(isEdit ? "Edit" : "Create",
style: const TextStyle(color: Colors.white)),
)
],
),
),
);
}
void _showCategoryMenu(String category) {
final isCompleted = categoryDetails[category]?['completed'] == true;
showModalBottomSheet(
context: context,
builder: (_) {
final List<Widget> items = [];
if (!isCompleted && _isUserAuthorized()) {
items.add(
ListTile(
leading: const Icon(Icons.check_circle,
color: Colors.blue, weight: 700),
title: const Text("Mark as Completed",
style: TextStyle(
color: Colors.blue, fontWeight: FontWeight.bold)),
onTap: () {
Navigator.pop(context);
_markAsCompletedDialog(category);
},
),
);
items.add(
ListTile(
leading: const Icon(Icons.edit, color: Colors.black),
title: const Text("Edit List",
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.bold)),
onTap: () {
Navigator.pop(context);
_addCategoryDialog(existingCategory: category);
},
),
);
items.add(
ListTile(
leading: const Icon(Icons.delete,
color: Color.fromARGB(255, 255, 17, 0)),
title: const Text("Delete List",
style: TextStyle(
color: Color.fromARGB(255, 255, 17, 0),
fontWeight: FontWeight.bold)),
onTap: () async {
Navigator.pop(context);
setState(() {
shoppingItems.remove(category);
categoryDetails.remove(category);
});
await _saveToFirestore();
},
),
);
}
if (items.isEmpty) {
items.add(const ListTile(
title: Center(
child: Text("You are not authorized to modify this list."),
),
));
}
return Wrap(children: items);
},
);
}
void _editItemDialog(String category, int index) {
TextEditingController controller =
TextEditingController(text: shoppingItems[category]![index]);
showDialog(
context: context,
builder: (_) => AlertDialog(
title: const Text("Edit Product"),
backgroundColor: Colors.white,
content: TextField(
controller: controller,
decoration: const InputDecoration(labelText: "New Product Name"),
),
actions: [
TextButton(
style: TextButton.styleFrom(
side: BorderSide(color: Colors.orange[900]!, width: 2),
),
onPressed: () => Navigator.pop(context),
child: Text("Cancel",
style: TextStyle(
color: Colors.orange[900]!, fontWeight: FontWeight.bold)),
),
ElevatedButton(
style:
ElevatedButton.styleFrom(backgroundColor: Colors.orange[900]!),
onPressed: () async {
if (controller.text.trim().isEmpty) return;
Navigator.pop(context);
setState(() {
shoppingItems[category]![index] = controller.text.trim();
});
await _saveToFirestore();
},
child: const Text("Save", style: TextStyle(color: Colors.white)),
)
],
),
);
}
void _addItemDialog(String category) {
TextEditingController itemController = TextEditingController();
showDialog(
context: context,
builder: (_) => AlertDialog(
backgroundColor: Colors.white,
title: Text("Add Product to $category"),
content: TextField(
controller: itemController,
decoration: const InputDecoration(labelText: "Product Name"),
),
actions: [
TextButton(
style: TextButton.styleFrom(
side: BorderSide(color: Colors.orange[900]!, width: 2),
),
onPressed: () => Navigator.pop(context),
child: Text("Cancel",
style: TextStyle(
color: Colors.orange[900]!, fontWeight: FontWeight.bold)),
),
ElevatedButton(
style:
ElevatedButton.styleFrom(backgroundColor: Colors.orange[900]!),
onPressed: () async {
if (itemController.text.trim().isEmpty) return;
Navigator.pop(context);
setState(() {
shoppingItems[category] = [
...?shoppingItems[category],
itemController.text.trim()
];
});
await _saveToFirestore();
},
child: const Text("Add",
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold)),
)
],
),
);
}
@override
Widget build(BuildContext context) {
debugPrint("🛒 build() called — role=$role, birthDate=$birthDate");
debugPrint("🛒 isAuthorized = ${_isUserAuthorized()}");
final sortedCategories = categoryDetails.keys.toList()
..sort((a, b) {
final aCompleted = categoryDetails[a]?['completed'] == true;
final bCompleted = categoryDetails[b]?['completed'] == true;
if (aCompleted && !bCompleted) return 1;
if (!aCompleted && bCompleted) return -1;
final aDateStr = categoryDetails[a]?['completedDate'];
final bDateStr = categoryDetails[b]?['completedDate'];
if (aCompleted && bCompleted && aDateStr != null && bDateStr != null) {
final aDate = DateTime.tryParse(aDateStr) ?? DateTime(1900);
final bDate = DateTime.tryParse(bDateStr) ?? DateTime(1900);
return aDate.compareTo(bDate);
}
return 0;
});
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.orange[900]!,
elevation: 0,
leading: Padding(
padding: const EdgeInsets.only(left: 20),
child: IconButton(
icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
),
title: const Text(
'Shopping List',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
actions: [
if (role != null && birthDate != null && _isUserAuthorized())
IconButton(
onPressed: () => _addCategoryDialog(),
icon: const Icon(Icons.shopping_cart, color: Colors.white),
)
],
),
body: ListView(
padding: const EdgeInsets.all(12),
children: sortedCategories.map((category) {
final items = shoppingItems[category] ?? [];
final details = categoryDetails[category] ?? {};
final isCompleted = details['completed'] == true;
return Card(
color: isCompleted ? Colors.green[300] : Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: BorderSide(
color: isCompleted ? Colors.green[800]! : Colors.orange[900]!,
width: 2,
),
),
child: ExpansionTile(
iconColor: Colors.orange[900]!,
collapsedIconColor: Colors.orange[900]!,
title: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
categoryDetails[category]?['type'] ?? category,
textAlign: TextAlign.center,
style: const TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
fontSize: 17.5,
),
),
if (details['point'] != null)
Text("⭐ ${details['point']}"),
if (details['date'] != null)
Text("📅 ${details['date']}"),
],
),
),
if (_isUserAuthorized())
IconButton(
icon: const Icon(Icons.more_vert),
color: Colors.orange[900]!,
onPressed: () => _showCategoryMenu(category),
)
else
const SizedBox.shrink(), // 👈 hiç gösterme
],
),
children: [
...items.asMap().entries.map((e) => ListTile(
title: Text("• ${e.value}"),
trailing: isCompleted || !_isUserAuthorized()
? null
: Wrap(spacing: 12, children: [
IconButton(
icon: Icon(Icons.edit, color: Colors.orange[900]!),
onPressed: () => _editItemDialog(category, e.key),
),
IconButton(
icon: Icon(Icons.delete, color: Colors.orange[900]!),
onPressed: () async {
setState(() => items.removeAt(e.key));
await _saveToFirestore();
},
),
]),
)),
if (!isCompleted && _isUserAuthorized())
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.orange[900]!,
foregroundColor: Colors.white),
onPressed: () => _addItemDialog(category),
child: const Text("Add Product",
style: TextStyle(fontWeight: FontWeight.bold)),
),
],
),
);
}).toList(),
),
);
}
Future<void> _getUserInfo() async {
final userDoc = await _firestore.collection('users').doc(userId).get();
final data = userDoc.data();
print("🔍 USER DATA: $data");
if (userDoc.exists && data != null) {
final rawBirthDate = data['birthDate'];
print("📅 Raw birthDate: $rawBirthDate");
print("🎭 Role: ${data['role']}");
setState(() {
role = data['role'];
if (rawBirthDate is Timestamp) {
birthDate = rawBirthDate.toDate();
} else if (rawBirthDate is String) {
birthDate = DateTime.tryParse(rawBirthDate);
} else {
birthDate = null;
}
});
print("✅ Set state -> role: $role | birthDate: $birthDate");
}
}
bool _isUserAuthorized() {
if (role == null || birthDate == null) return false;
final now = DateTime.now();
int age = now.year - birthDate!.year;
if (now.month < birthDate!.month ||
(now.month == birthDate!.month && now.day < birthDate!.day)) {
age--;
}
return role == "FATHER" ||
role == "MOTHER" ||
((role == "BOY" || role == "GIRL") && age >= 15);
}
void _markAsCompletedDialog(String category) {
showDialog(
context: context,
builder: (_) => AlertDialog(
title: const Text("Complete this list?"),
content: const Text("Do you want to mark this list as completed?"),
actions: [
TextButton(
style: TextButton.styleFrom(
side: BorderSide(color: Colors.orange[900]!, width: 2),
),
onPressed: () => Navigator.pop(context),
child: Text("Cancel",
style: TextStyle(
color: Colors.orange[900]!, fontWeight: FontWeight.bold)),
),
ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.green[700]),
onPressed: () async {
Navigator.pop(context);
// ✅ Puanı al
final int point = categoryDetails[category]?['point'] ?? 0;
// ✅ Kullanıcının mevcut puanını çek
final userRef =
_firestore.collection('users').doc(userId);
final userSnap = await userRef.get();
final currentPoints = userSnap.data()?['shoppingPoints'] ?? 0;
// ✅ Yeni puanı hesapla
final newPoints = currentPoints + point;
// ✅ Firestore'a puanı güncelle
await userRef.update({'shoppingPoints': newPoints});
// ✅ Listeyi tamamlandı olarak işaretle
setState(() {
categoryDetails[category]?['completed'] = true;
categoryDetails[category]?['completedBy'] = userId;
categoryDetails[category]?['completedDate'] =
DateTime.now().toIso8601String();
});
await _saveToFirestore();
},
child: const Text("Yes", style: TextStyle(color: Colors.white)),
),
],
),
);
}
}
![]() |
Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...
With notes.io;
- * You can take a note from anywhere and any device with internet connection.
- * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
- * You can quickly share your contents without website, blog and e-mail.
- * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
- * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.
Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.
Easy: Notes.io doesn’t require installation. Just write and share note!
Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )
Free: Notes.io works for 14 years and has been free since the day it was started.
You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;
Email: [email protected]
Twitter: http://twitter.com/notesio
Instagram: http://instagram.com/notes.io
Facebook: http://facebook.com/notesio
Regards;
Notes.io Team
