repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/fu_uber | mirrored_repositories/fu_uber/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:fu_uber/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/trips11 | mirrored_repositories/trips11/lib/register.dart | import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class MyRegister extends StatelessWidget {
const MyRegister({super.key});
@override
Widget build(BuildContext context) {
String email = '';
String pass = '';
return Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/register.png'), fit: BoxFit.cover)),
child: Scaffold(
backgroundColor: Colors.transparent,
body: Stack(
children: [
Container(
padding: const EdgeInsets.only(left: 35, top: 130),
child: const Text(
"SIGN UP",
style: TextStyle(color: Colors.white, fontSize: 30),
),
),
SingleChildScrollView(
child: Container(
padding: EdgeInsets.only(
top: MediaQuery.of(context).size.height * 0.5,
left: 35,
right: 35),
child: Column(children: [
TextField(
decoration: InputDecoration(
fillColor: Colors.grey,
filled: true,
hintText: "Name",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
),
),
const SizedBox(
height: 30,
),
TextField(
onChanged: ((value) => email = value),
decoration: InputDecoration(
fillColor: Colors.grey,
filled: true,
hintText: "email id",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
),
),
const SizedBox(
height: 30,
),
TextField(
onChanged: ((value) => pass = value),
obscureText: true,
decoration: InputDecoration(
fillColor: Colors.grey,
filled: true,
hintText: "password",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
),
),
const SizedBox(
height: 20,
),
ElevatedButton(
onPressed: () async {
try {
// ignore: unused_local_variable
UserCredential userCredential = await FirebaseAuth
.instance
.createUserWithEmailAndPassword(
email: email, password: pass);
// ignore: use_build_context_synchronously
Navigator.pushNamed(context, 'login');
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
//display a snackbar
SnackBar snackBar = const SnackBar(
content: Text('The password provided is too weak.'),
);
// Find the ScaffoldMessenger in the widget tree
// and use it to show a SnackBar.
ScaffoldMessenger.of(context).showSnackBar(snackBar);
//print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
SnackBar snackBar = const SnackBar(
content: Text(
'The account already exists for that email.'),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
// print('The account already exists for that email.');
}
} catch (e) {
//print(e);
}
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
padding: const EdgeInsets.symmetric(
horizontal: 50, vertical: 10),
textStyle: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold)),
child: const Text('SIGN UP'),
),
const SizedBox(
height: 20,
),
const Text("Already have an account?"),
const SizedBox(
height: 10,
),
ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, 'login');
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
padding: const EdgeInsets.symmetric(
horizontal: 50, vertical: 10),
textStyle: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold)),
child: const Text('SIGN IN'),
),
]),
),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/trips11 | mirrored_repositories/trips11/lib/group.dart | import 'package:flutter/material.dart';
import 'package:open_street_map_search_and_pick/open_street_map_search_and_pick.dart';
import 'package:trips1/createhike.dart';
import 'package:trips1/join.dart';
class Group extends StatefulWidget {
// ignore: use_key_in_widget_constructors
const Group({Key? key});
@override
State<Group> createState() => _GroupState();
}
class _GroupState extends State<Group> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Group'),
),
body: SingleChildScrollView(
child: Column(
children: [
const SizedBox(
height: 100,
child: Center(
child: Text('Address'),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const CreateHike()),
);
},
child: const Text('Create Hike'),
),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const Join()),
);
},
child: const Text('Join Hike'),
),
],
),
SizedBox(
height: 500,
child: Center(
child: OpenStreetMapSearchAndPick(
center: LatLong(23, 89),
buttonColor: Colors.yellow,
buttonText: 'Set Current Location',
onPicked: (pickedData) {
// print(pickedData.latLong.latitude);
// print(pickedData.latLong.longitude);
// print(pickedData.address);
},
),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/trips11 | mirrored_repositories/trips11/lib/description.dart | import 'package:flutter/material.dart';
import 'package:trips1/capture.dart';
import 'package:trips1/group.dart';
import 'package:trips1/home.dart';
class Description extends StatelessWidget {
final String imageUrl;
final String placeName;
final String description;
const Description({
Key? key,
required this.imageUrl,
required this.placeName,
required this.description,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Description"),
),
body: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 600,
width: double.infinity,
child: Image.network(
imageUrl,
fit: BoxFit.contain,
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
'ππ»ππ»ππ»ππ»ππ»ππ»ππ»ππ»ππ»ππ»ππ»ππ»ππ»ππ»ππ»ππ»\n\n$description',
style: const TextStyle(
color: Colors.green,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
),
],
),
),
bottomNavigationBar: BottomAppBar(
color: Colors.transparent,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
IconButton(
icon: const Icon(Icons.home),
color: Colors.white,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const MyHome()),
);
},
),
IconButton(
icon: const Icon(Icons.navigation),
color: Colors.white,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const Group()),
);
},
),
IconButton(
icon: const Icon(
Icons.camera_alt,
color: Colors.white,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const Capture()),
);
},
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/trips11 | mirrored_repositories/trips11/lib/createhike.dart | import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:open_street_map_search_and_pick/open_street_map_search_and_pick.dart';
class CreateHike extends StatefulWidget {
// ignore: use_key_in_widget_constructors
const CreateHike({Key? key});
@override
State<CreateHike> createState() => _CreateHikeState();
}
class _CreateHikeState extends State<CreateHike> {
final CollectionReference _reference =
FirebaseFirestore.instance.collection('hike');
String? startLocation;
String? endLocation;
DateTime? date;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Create Hike'),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => _buildLocationPicker(),
),
).then((value) {
if (value != null) {
setState(() {
startLocation = value;
});
}
});
},
child: const Text('Select Start Location'),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => _buildLocationPicker(),
),
).then((value) {
if (value != null) {
setState(() {
endLocation = value;
});
}
});
},
child: const Text('Select End Location'),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime.now(),
lastDate: DateTime(2100),
).then((value) {
if (value != null) {
setState(() {
date = value;
});
}
});
},
child: const Text('Select Date'),
),
const SizedBox(height: 20),
const Text(
'Start Location:',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
Text(
startLocation ?? 'Not selected',
style: const TextStyle(
fontSize: 16,
color: Colors.blue, // Set start location text color
),
),
const SizedBox(height: 12),
const Text(
'End Location:',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
Text(
endLocation ?? 'Not selected',
style: const TextStyle(
fontSize: 16,
color: Colors.green, // Set end location text color
),
),
const SizedBox(height: 12),
const Text(
'Date:',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
Text(
date?.toString() ?? 'Not selected',
style: const TextStyle(
fontSize: 16,
color: Colors.red, // Set date text color
),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _submitData,
child: const Text('Submit'),
),
],
),
),
);
}
Widget _buildLocationPicker() {
return Scaffold(
appBar: AppBar(
title: const Text('Location Picker'),
),
body: SizedBox(
height: 500,
child: Center(
child: OpenStreetMapSearchAndPick(
center: LatLong(23, 89),
buttonColor: Colors.blue,
buttonText: 'Set Location',
onPicked: (pickedData) {
Navigator.pop(context, pickedData.address);
},
),
),
),
);
}
Future<void> _submitData() async {
if (startLocation == null || endLocation == null || date == null) {
//print('Please fill all the fields');
return;
}
try {
await _reference.add({
'start': startLocation,
'end': endLocation,
'timings': date,
});
// Data saved successfully, show success message or navigate to the next screen
} catch (error) {
// Handle error, show error message or retry logic
// print('Error saving data: $error');
}
}
}
| 0 |
mirrored_repositories/trips11 | mirrored_repositories/trips11/lib/join.dart | import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class Join extends StatefulWidget {
const Join({Key? key}) : super(key: key);
@override
State<Join> createState() => _JoinState();
}
class _JoinState extends State<Join> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Join Hike'),
),
body: _buildHikeList(),
);
}
Widget _buildHikeList() {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('hike').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return const Center(
child: Text(
'Error retrieving data',
style: TextStyle(fontSize: 16),
),
);
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
final hikes = snapshot.data?.docs;
if (hikes == null || hikes.isEmpty) {
return const Center(
child: Text(
'No hikes available',
style: TextStyle(fontSize: 16),
),
);
}
return ListView.builder(
itemCount: hikes.length,
itemBuilder: (BuildContext context, int index) {
final hikeData = hikes[index].data() as Map<String, dynamic>;
final startLocation = hikeData['start'] as String?;
final endLocation = hikeData['end'] as String?;
final timings = hikeData['timings'] as Timestamp?;
return GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Hike Information'),
content: Text(
'The hike starts at ${timings?.toDate().toString()}'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('OK'),
),
],
);
},
);
},
child: Card(
margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
child: ListTile(
title: Text(
'Start Location: $startLocation',
style: const TextStyle(
fontSize: 18, fontWeight: FontWeight.bold),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 8),
Text(
'End Location: $endLocation',
style: const TextStyle(
fontSize: 16,
color: Colors
.blue, // Set the desired color for end location
),
),
const SizedBox(height: 4),
Text(
'Timings: ${timings?.toDate().toString()}',
style: const TextStyle(
fontSize: 14,
color:
Colors.green, // Set the desired color for timings
),
),
const SizedBox(height: 8),
],
),
),
),
);
},
);
},
);
}
}
| 0 |
mirrored_repositories/trips11 | mirrored_repositories/trips11/lib/login.dart | // ignore_for_file: unused_local_variable
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class MyLogin extends StatefulWidget {
const MyLogin({super.key});
@override
State<MyLogin> createState() => _MyLoginState();
}
class _MyLoginState extends State<MyLogin> {
// ignore: unused_element
Future<FirebaseApp> _initializeFirebase() async {
FirebaseApp firebaseApp = await Firebase.initializeApp();
return firebaseApp;
}
//final FirebaseAuth _auth = FirebaseAuth.instance;
// Function to handle sign in
// ignore: unused_element
static Future<User?> _signInWithEmailAndPassword(
{required String email,
required String password,
required BuildContext context}) async {
FirebaseAuth auth = FirebaseAuth.instance;
User? user;
try {
UserCredential userCredential = await auth.signInWithEmailAndPassword(
email: email,
password: password,
);
// Handle successful sign in here
user = userCredential.user;
} on FirebaseAuthException catch (e) {
if (e.code == "user-not-found") {
// print("No User found for that email");
} else if (e.code == "wrong-password") {
//print("Wrong password provided for that user");
} else if (e.code == "invalid-email") {
//print("Invalid email address");
} else {
//print(e.code);
}
// Handle sign in error here
}
return user;
}
@override
Widget build(BuildContext context) {
String email = '';
String pass = '';
return Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/login.png'), fit: BoxFit.cover)),
child: Scaffold(
backgroundColor: Colors.transparent,
body: Stack(
children: [
Container(
padding: const EdgeInsets.only(left: 35, top: 130),
child: const Text(
"Welcome",
style: TextStyle(color: Colors.white, fontSize: 30),
),
),
SingleChildScrollView(
child: Container(
padding: EdgeInsets.only(
top: MediaQuery.of(context).size.height * 0.5,
left: 35,
right: 35),
child: Column(children: [
TextField(
onChanged: ((value) => email = value),
decoration: InputDecoration(
fillColor: Colors.grey,
filled: true,
hintText: "email id",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
),
),
const SizedBox(
height: 30,
),
TextField(
onChanged: ((value) => pass = value),
obscureText: true,
decoration: InputDecoration(
fillColor: Colors.grey,
filled: true,
hintText: "password",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
),
),
const SizedBox(
height: 20,
),
ElevatedButton(
onPressed: () async {
try {
UserCredential userCredential = await FirebaseAuth
.instance
.signInWithEmailAndPassword(
email: email, password: pass);
// ignore: use_build_context_synchronously
Navigator.pushNamed(context, 'home');
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
SnackBar snackBar = const SnackBar(
content: Text('No User found for that email.'),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
} else if (e.code == 'wrong-password') {
SnackBar snackBar = const SnackBar(
content:
Text('Wrong Password provided for that user.'),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
}
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
padding: const EdgeInsets.symmetric(
horizontal: 50, vertical: 10),
textStyle: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold)),
child: const Text('SIGN IN'),
),
const SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton(
onPressed: () {
Navigator.pushNamed(context, 'register');
},
child: const Text('SIGN UP',
style: TextStyle(
decoration: TextDecoration.underline,
fontSize: 18,
color: Color(0xff4c505b))),
),
const SizedBox(
width: 20,
),
TextButton(
onPressed: () {},
child: const Text('FORGOT PASSWORD?',
style: TextStyle(
decoration: TextDecoration.underline,
fontSize: 18,
color: Color(0xff4c505b))),
)
],
)
]),
),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/trips11 | mirrored_repositories/trips11/lib/splash_screen.dart | import 'package:flutter/material.dart';
class MySplash extends StatefulWidget {
const MySplash({super.key});
@override
State<MySplash> createState() => _MySplashState();
}
class _MySplashState extends State<MySplash> {
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child: CircularProgressIndicator(
color: Colors.green,
),
),
);
}
}
| 0 |
mirrored_repositories/trips11 | mirrored_repositories/trips11/lib/capture.dart | import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class Capture extends StatefulWidget {
const Capture({Key? key}) : super(key: key);
@override
State<Capture> createState() => _CaptureState();
}
class _CaptureState extends State<Capture> {
String imageUrl = '';
GlobalKey<FormState> key = GlobalKey();
TextEditingController description = TextEditingController();
final CollectionReference _reference =
FirebaseFirestore.instance.collection('places');
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.green,
title: const Text('Add Description & Images '),
),
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Image.asset("assets/tripitonlogo.png"),
Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
controller: description,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Description',
),
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: IconButton(
icon: const Icon(
Icons.camera_alt,
color: Colors.black,
),
onPressed: () async {
// Open camera or gallery
ImagePicker imagePicker = ImagePicker();
XFile? file =
await imagePicker.pickImage(source: ImageSource.camera);
//print('${file?.path}');
if (file == null) return;
// Create unique file name
String uniqueFileName =
DateTime.now().millisecondsSinceEpoch.toString();
// Upload image to Firebase
Reference referenceRoot = FirebaseStorage.instance.ref();
Reference referenceDirImages = referenceRoot.child('images');
// Create reference for image to be stored in Firebase
Reference referenceImageToUpload =
referenceDirImages.child(uniqueFileName);
SnackBar snackBar = const SnackBar(
content: Text(
'Description and Image added successfully\n\t\t\t\tNow Press Submit Button'),
);
// ignore: use_build_context_synchronously
ScaffoldMessenger.of(context).showSnackBar(snackBar);
try {
// Store the file
await referenceImageToUpload.putFile(File(file.path));
imageUrl = await referenceImageToUpload.getDownloadURL();
} catch (error) {
// print(error);
}
},
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: () async {
String descriptionText = description.text;
Map<String, String> data = {
'description': descriptionText,
'image': imageUrl,
};
_reference.add(data);
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 17.0, horizontal: 10.0),
),
child: const Text('Submit'),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/trips11 | mirrored_repositories/trips11/lib/main.dart | import 'package:flutter/material.dart';
import 'package:trips1/home.dart';
import 'package:trips1/register.dart';
import 'package:firebase_core/firebase_core.dart';
import 'login.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MaterialApp(
initialRoute: 'login',
debugShowCheckedModeBanner: false,
routes: {
'login': (context) => const MyLogin(),
'register': (context) => const MyRegister(),
'home': (context) => const MyHome(),
},
));
}
| 0 |
mirrored_repositories/trips11 | mirrored_repositories/trips11/lib/home.dart | import 'package:flutter/material.dart';
import 'package:trips1/description.dart';
import 'package:trips1/group.dart';
import 'capture.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class MyHome extends StatefulWidget {
const MyHome({super.key});
@override
State<MyHome> createState() => _MyHomeState();
}
class _MyHomeState extends State<MyHome> {
String imageUrl = '';
// final FirebaseStorage _storage = FirebaseStorage.instance;
final CollectionReference _placesReference =
FirebaseFirestore.instance.collection('places');
final CollectionReference _cultural =
FirebaseFirestore.instance.collection('cultural');
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromRGBO(232, 244, 243, 0.765),
drawer: const Drawer(
// Small menu button
child: Text(""), // Menu content,
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Padding(
padding: EdgeInsets.fromLTRB(
16, 40, 16, 8), // Adjust padding as needed
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
width: 30,
),
CircleAvatar(
backgroundImage: AssetImage('assets/register.png'),
),
],
),
),
// Discover text
const Padding(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Text(
'Discover',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
// "Explore the places of the world" text
const Padding(
padding: EdgeInsets.fromLTRB(
16, 8, 16, 24), // Adjust padding as needed
child: Text(
'Explore the places of the world',
style: TextStyle(fontSize: 18, color: Colors.white),
),
),
// Padding(
// padding: const EdgeInsets.fromLTRB(18, 20, 11, 0),
// child: Row(
// children: [
// Expanded(
// child: TextFormField(
// autofocus: true,
// decoration: InputDecoration(
// suffixIcon: const Icon(
// Icons.search,
// color: Colors.black12,
// ),
// hintText: 'Search',
// hintStyle: const TextStyle(color: Colors.black),
// border: OutlineInputBorder(
// borderRadius: BorderRadius.circular(25.7),
// borderSide:
// BorderSide(width: 20.0, color: Colors.black)),
// ),
// ),
// ),
// ],
// ),
// ),
const SizedBox(
height: 30,
),
const Padding(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Text(
'Places and Descriptions',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
const SizedBox(height: 10),
SizedBox(
height: 200,
child: FutureBuilder<QuerySnapshot>(
future: _placesReference.get(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
List<QueryDocumentSnapshot> documents = snapshot.data!.docs;
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: documents.length,
itemBuilder: (context, index) {
String imageUrl = documents[index]['image'];
String description = documents[index]['description'];
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Description(
imageUrl: imageUrl,
placeName: 'Place $index',
description: description,
),
),
);
},
child: Container(
width: 150,
margin: const EdgeInsets.symmetric(
horizontal: 8, vertical: 6),
child: SingleChildScrollView(
child: Column(
children: [
Image.network(imageUrl),
Text(
'Place $index',
style: const TextStyle(
fontSize: 16, color: Colors.white),
),
],
),
),
),
);
},
);
},
),
),
const Padding(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Text(
'Cultural Diversity',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
const SizedBox(height: 10),
SizedBox(
height: 200,
child: FutureBuilder<QuerySnapshot>(
future: _cultural.get(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
List<QueryDocumentSnapshot> documents = snapshot.data!.docs;
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: documents.length,
itemBuilder: (context, index) {
String imageUrl = documents[index]['Imageurl'];
String description = documents[index]['Description'];
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Description(
imageUrl: imageUrl,
placeName: 'Place $index',
description: description,
),
),
);
},
child: Container(
width: 150,
margin: const EdgeInsets.symmetric(
horizontal: 8, vertical: 6),
child: SingleChildScrollView(
child: Column(
children: [
Image.network(imageUrl),
Text(
'Place $index',
style: const TextStyle(
fontSize: 16, color: Colors.white),
),
],
),
),
),
);
},
);
},
),
),
// Groups section
],
),
),
bottomNavigationBar: BottomAppBar(
color: Colors.transparent,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
IconButton(
icon: const Icon(Icons.home),
color: Colors.white,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const MyHome()),
);
},
),
IconButton(
icon: const Icon(Icons.navigation),
color: Colors.white,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const Group()),
);
},
),
IconButton(
icon: const Icon(
Icons.camera_alt,
color: Colors.white,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const Capture()),
);
},
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/trips11 | mirrored_repositories/trips11/test/unit_test_group.dart | import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:open_street_map_search_and_pick/open_street_map_search_and_pick.dart';
import 'package:trips1/group.dart'; // Import the 'Group' widget
void main() {
testWidgets('Test Group widget', (WidgetTester tester) async {
// Build the 'Group' widget and trigger a frame.
await tester.pumpWidget(const MaterialApp(home: Group()));
// Verify that the 'Group' widget is displayed correctly with its children widgets.
// Test that the AppBar title is 'Group'.
expect(find.text('Group'), findsOneWidget);
// Test that the two elevated buttons for 'Create Hike' and 'Join Hike' are present.
expect(find.text('Create Hike'), findsOneWidget);
expect(find.text('Join Hike'), findsOneWidget);
// Test that the 'OpenStreetMapSearchAndPick' widget is present.
expect(find.byType(OpenStreetMapSearchAndPick), findsOneWidget);
// You can perform other interaction tests if applicable. For example,
// you can tap on buttons and verify the results.
// Example: Tap the 'Create Hike' button and verify that it navigates to the 'CreateHike' widget.
await tester.tap(find.text('Create Hike'));
await tester.pumpAndSettle(); // Wait for animations to complete.
expect(find.text('Create Hike Page'),
findsOneWidget); // Assuming 'CreateHike' widget has a title 'Create Hike Page'.
// Example: Tap the 'Join Hike' button and verify that it navigates to the 'Join' widget.
await tester.tap(find.text('Join Hike'));
await tester.pumpAndSettle(); // Wait for animations to complete.
expect(find.text('Join Page'),
findsOneWidget); // Assuming 'Join' widget has a title 'Join Page'.
// You can also simulate interaction with the 'OpenStreetMapSearchAndPick' widget if applicable.
// For example, you can test the onPicked callback.
// Note: Since 'OpenStreetMapSearchAndPick' is a third-party widget, you may not be able to simulate
// all possible interactions in a unit test. Consider using integration tests for more complex interactions.
// Additional test cases can be added to cover other aspects of the 'Group' widget behavior.
});
}
| 0 |
mirrored_repositories/trips11 | mirrored_repositories/trips11/test/widget_test.dart | // import 'package:flutter/material.dart';
// import 'package:flutter_test/flutter_test.dart';
// void main() {
// testWidgets('Test Description Widget', (WidgetTester tester) async {
// // Build the Description widget and trigger a frame.
// // await tester.pumpWidget(
// // MaterialApp(
// // home: Description(
// // imageUrl: 'your_image_url',
// // placeName: 'Place Name',
// // description: 'Description text',
// // ),
// // ),
// // );
// // Verify that the widgets you expect are displayed using 'expect' statements.
// // Find the widgets using 'find.text' and 'find.byType' as appropriate.
// // Example: Verify that the text 'Description text' is present.
// // expect(find.text('Description text'), findsOneWidget);
// // Example: Verify that an Image widget is displayed.
// //expect(find.byType(Image), findsOneWidget);
// // Test widget interactions if applicable. For example, tap on buttons or icons.
// // Here, we can find the home icon button and tap it.
// await tester.tap(find.byIcon(Icons.home));
// await tester.pumpAndSettle(); // Wait for animations to complete.
// // Verify the result of the interaction.
// // For example, you can check if the navigation to the home page was successful.
// expect(find.text('Home Page'), findsOneWidget);
// });
// }
| 0 |
mirrored_repositories/Kpop-Chat | mirrored_repositories/Kpop-Chat/lib/main.dart | import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:kpopchat/business_logic/chat_cubit/chat_cubit.dart';
import 'package:kpopchat/business_logic/internet_checker_cubit.dart';
import 'package:kpopchat/business_logic/real_users_cubit/real_users_cubit.dart';
import 'package:kpopchat/business_logic/virtual_friends_list_cubit/virtual_friends_list_cubit.dart';
import 'package:kpopchat/business_logic/virtual_friends_posts_cubit/virtual_friends_posts_cubit.dart';
import 'package:kpopchat/core/routes/app_routes.dart';
import 'package:kpopchat/business_logic/theme_cubit.dart';
import 'package:kpopchat/business_logic/auth_checker_cubit/auth_checker_cubit.dart';
import 'package:kpopchat/core/utils/initializer.dart';
import 'core/firebase/firebase_setup.dart';
import 'core/routes/route_generator.dart';
import 'core/utils/service_locator.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await FirebaseSetup().initializeFirebase();
await setUpLocator();
RequiredInitializations.initializeFirebaseRemoteConfig();
RequiredInitializations.initializeMobileAds();
runApp(const MyApp());
}
final navigatorKey = GlobalKey<NavigatorState>();
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(create: (context) => AuthCheckerCubit()),
BlocProvider(create: (context) => ThemeCubit()),
BlocProvider(
create: (context) => VirtualFriendsPostsCubit(locator())),
BlocProvider(create: (context) => VirtualFriendsListCubit(locator())),
BlocProvider(create: (context) => RealUsersCubit(locator())),
BlocProvider(create: (context) => ChatCubit(locator())),
BlocProvider(
create: (context) => InternetConnectivityCubit(
locator<InternetConnectionChecker>())),
],
child: ScreenUtilInit(
designSize: const Size(375, 812),
minTextAdapt: true,
splitScreenMode: true,
builder: (context, child) {
return BlocBuilder<ThemeCubit, ThemeData>(
builder: (context, themeToUse) {
BlocProvider.of<ThemeCubit>(context).getTheme();
return MaterialApp(
navigatorKey: navigatorKey,
debugShowCheckedModeBanner: false,
navigatorObservers: [
FirebaseAnalyticsObserver(
analytics: locator<FirebaseAnalytics>())
],
onGenerateRoute: onGenerateRoute,
initialRoute: AppRoutes.authCheckerScreen,
builder: (context, widget) {
return MediaQuery(
data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
child: widget!,
);
},
theme: themeToUse,
);
});
},
));
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/repository/real_users_repo.dart | import 'package:dartz/dartz.dart';
import 'package:kpopchat/core/network/failure_model.dart';
import 'package:kpopchat/data/models/user_model.dart';
abstract class RealUsersRepo {
Future<Either<List<UserModel>, FailureModel>> fetchRealUsersData();
Future<void> updateUserLocationAndGhostModeStatus(UserModel updatedUserData);
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/repository/remote_config_repo.dart | abstract class RemoteConfigRepo {
/// method to get user info like location, internet provided based in user's public IP address
Future<void> getUserInfoFromIP();
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/repository/virtual_friends_repo.dart | import 'package:dartz/dartz.dart';
import 'package:kpopchat/core/network/failure_model.dart';
import 'package:kpopchat/data/models/local_schema_model.dart';
import 'package:kpopchat/data/models/virtual_friend_model.dart';
import 'package:kpopchat/data/models/virtual_friend_post_model.dart';
abstract class VirtualFriendsRepo {
Future<Either<bool, FailureModel>> createVirtualFriend(
{required VirtualFriendModel virtualFriendInfo});
Future<Either<LocalSchemaModelOfLoggedInUser, FailureModel>>
getVirtualFriends();
Future<Either<List<VirtualFriendPostModel>, FailureModel>>
getVirtualFriendsPosts();
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/repository/auth_repo.dart | import 'package:firebase_auth/firebase_auth.dart';
/// User authentication related repo for this app, Have methods to sign in, sign out methods
abstract class AuthRepo {
Future<bool> signInWithGoogle();
Future<void> registerUserProfile(User userInfo);
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/repository/chat_repo.dart | import 'package:dartz/dartz.dart';
import 'package:dash_chat_2/dash_chat_2.dart';
import 'package:kpopchat/core/network/failure_model.dart';
import 'package:kpopchat/data/models/schema_message_model.dart';
import 'package:kpopchat/data/models/schema_virtual_friend_model.dart';
abstract class ChatRepo {
Future<Either<List<SchemaMessageModel>, FailureModel>>
getChatHistoryWithThisFriend(
{required String virtualFriendId, ChatMessage? msgToAdd});
Future<Either<SchemaMessageModel, FailureModel>> getMsgFromVirtualFriend(
SchemaVirtualFriendModel schemaVirtualFriend);
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/repository_implementation/chat_repo_impl.dart | import 'package:dartz/dartz.dart';
import 'package:dash_chat_2/dash_chat_2.dart';
import 'package:flutter/foundation.dart';
import 'package:kpopchat/core/constants/analytics_constants.dart';
import 'package:kpopchat/core/constants/network_constants.dart';
import 'package:kpopchat/core/constants/remote_config_values.dart';
import 'package:kpopchat/core/constants/text_constants.dart';
import 'package:kpopchat/core/network/client/base_client.dart';
import 'package:kpopchat/core/network/failure_model.dart';
import 'package:kpopchat/core/utils/analytics.dart';
import 'package:kpopchat/core/utils/schema_helper.dart';
import 'package:kpopchat/core/utils/shared_preferences_helper.dart';
import 'package:kpopchat/data/models/local_schema_model.dart';
import 'package:kpopchat/data/models/open_ai_resp_model.dart';
import 'package:kpopchat/data/models/schema_message_model.dart';
import 'package:kpopchat/data/models/schema_virtual_friend_model.dart';
import 'package:kpopchat/data/repository/chat_repo.dart';
class ChatRepoImplementation implements ChatRepo {
final SchemaHelper schemaHelper;
final BaseClient baseClient;
ChatRepoImplementation(this.schemaHelper, this.baseClient);
@override
Future<Either<List<SchemaMessageModel>, FailureModel>>
getChatHistoryWithThisFriend(
{required String virtualFriendId, ChatMessage? msgToAdd}) async {
try {
final String? localSchema = await schemaHelper.getLocalSchema();
// if (localSchema == null) {
// return Left(chatHistory);
// }
LocalSchemaModelOfLoggedInUser schemaModelOfLoggedInUser =
LocalSchemaModelOfLoggedInUser.fromLocalSchema(
localSchema: localSchema ?? "{}");
for (SchemaVirtualFriendModel virtualFriend
in schemaModelOfLoggedInUser.virtualFriends ?? []) {
if (virtualFriendId == virtualFriend.info?.id) {
if (msgToAdd != null) {
SchemaMessageModel schemaMessage =
SchemaMessageModel.fromChatMessage(msgToAdd);
// sync msg locally
virtualFriend.chatHistory!.insert(0, schemaMessage);
await SchemaHelper().saveLocalSchema(schemaModelOfLoggedInUser);
}
return Left(virtualFriend.chatHistory!);
}
}
// if there is no records of virtual friend with provided id then also return empty chat history
return const Left([]);
} catch (e) {
debugPrint("exception at chat_repo_implementation.dart: ${e.toString()}");
return Right(
FailureModel(message: "Could not fetch chat history at the moment."));
}
}
@override
Future<Either<SchemaMessageModel, FailureModel>> getMsgFromVirtualFriend(
SchemaVirtualFriendModel schemaVirtualFriend) async {
Map<String, dynamic>? userInfo =
SharedPrefsHelper.getUserProfile()?.toJson();
List<Map<String, dynamic>> previousHistory =
schemaVirtualFriend.toListOfJsonMessages();
Map<String, dynamic> payloadForEdenAI = {
"providers": "openai",
"text": schemaVirtualFriend.chatHistory?.first.message ?? "Hello",
"chatbot_global_action":
"${RemoteConfigValues.systemMsg} ${schemaVirtualFriend.info?.toJson()} ${userInfo != null ? "and information of user you are responding to is: $userInfo" : ""}",
"previous_history":
previousHistory.take(RemoteConfigValues.maxMessagesToTake).toList(),
"temperature": RemoteConfigValues.temperature,
"max_tokens": RemoteConfigValues.maxTokens
};
try {
final response = await baseClient.postRequest(
baseUrl: NetworkConstants.edenAIbaseUrl,
path: NetworkConstants.edenAIChatPath,
data: payloadForEdenAI,
);
OpenAIResponseModel friendResp =
OpenAIResponseModel.fromJson(response?.data);
// log credit consumed to mixpanel
increasePropertyCount(AnalyticsConstants.kPropertyEdenAiCreditSpent,
friendResp.openai?.cost ?? 0);
SchemaMessageModel virtualFriendMsg = SchemaMessageModel(
role: SchemaMessageModel.kKeyVirtualFriendRole,
message: friendResp.openai?.generatedText ?? "Listening...",
createdAt: DateTime.now().toString());
return Left(virtualFriendMsg);
} catch (e) {
debugPrint("Exception getting eden ai resp: ${e.toString()}");
return Right(FailureModel(message: TextConstants.defaultErrorMsg));
}
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/repository_implementation/auth_repo_impl.dart | import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/foundation.dart';
import 'package:kpopchat/core/constants/firestore_collections_constants.dart';
import 'package:kpopchat/core/constants/location_constants.dart';
import 'package:kpopchat/core/utils/analytics.dart';
import 'package:kpopchat/core/utils/loading_utils.dart';
import 'package:kpopchat/core/utils/service_locator.dart';
import 'package:kpopchat/core/utils/shared_preferences_helper.dart';
import 'package:kpopchat/data/models/user_model.dart';
import 'package:kpopchat/presentation/common_widgets/common_widgets.dart';
import 'package:kpopchat/main.dart';
import 'package:kpopchat/data/repository/auth_repo.dart';
import 'package:google_sign_in/google_sign_in.dart';
class AuthRepoImplementation implements AuthRepo {
final GoogleSignIn googleSignIn;
final FirebaseFirestore firestore;
AuthRepoImplementation(this.googleSignIn, this.firestore);
@override
Future<bool> signInWithGoogle() async {
LoadingUtils.showLoadingDialog();
// try {
GoogleSignInAccount? googleUser = await googleSignIn.signIn();
if (googleUser == null) {
LoadingUtils.hideLoadingDialog();
return false;
}
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final OAuthCredential googleAuthCredential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
final UserCredential googleUserCredential = await locator<FirebaseAuth>()
.signInWithCredential(googleAuthCredential);
User? loggedInUser = googleUserCredential.user;
SharedPrefsHelper.saveUserProfileFromLogin(loggedInUser);
setUserIdInAnalytics(SharedPrefsHelper.getUserProfile());
final bool isNewUser =
googleUserCredential.additionalUserInfo?.isNewUser ?? true;
if (isNewUser) {
registerUserProfile(loggedInUser);
}
debugPrint("user creds: ${googleUserCredential.user.toString()}");
CommonWidgets.customFlushBar(
navigatorKey.currentContext!, "sign in success");
return true;
// } catch (e) {
// debugPrint("error sign in with google: ${e.toString()}");
// CommonWidgets.customFlushBar(
// navigatorKey.currentContext!, "sign in fail $e");
// return false;
// }
}
@override
Future<void> registerUserProfile(User? userInfo) async {
try {
if (userInfo != null) {
UserModel userData = UserModel.fromFirebaseCurrentUser(userInfo);
// userData.dateJoined = DateTime.now();
userData.anonymizeLocation = true;
userData.latLong = LocationConstants.userLocationFromIP;
await firestore
.collection(FirestoreCollections.kUsers)
.doc(userInfo.uid)
.set(userData.toJson());
}
} catch (e) {
debugPrint("Could not register user profile: ${e.toString()}");
}
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/repository_implementation/virtual_friends_repo_impl.dart | import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dartz/dartz.dart';
import 'package:flutter/foundation.dart';
import 'package:kpopchat/core/constants/firestore_collections_constants.dart';
import 'package:kpopchat/core/network/failure_model.dart';
import 'package:kpopchat/core/utils/schema_helper.dart';
import 'package:kpopchat/data/models/local_schema_model.dart';
import 'package:kpopchat/data/models/schema_virtual_friend_model.dart';
import 'package:kpopchat/data/models/virtual_friend_model.dart';
import 'package:kpopchat/data/models/virtual_friend_post_model.dart';
import 'package:kpopchat/data/repository/virtual_friends_repo.dart';
import 'package:uuid/uuid.dart';
class VirtualFriendsRepoImplementation implements VirtualFriendsRepo {
final FirebaseFirestore firestore;
VirtualFriendsRepoImplementation(this.firestore);
@override
Future<Either<bool, FailureModel>> createVirtualFriend(
{required VirtualFriendModel virtualFriendInfo}) async {
try {
String virtualFriendId = const Uuid().v1();
virtualFriendInfo.id = virtualFriendId;
await firestore
.collection(FirestoreCollections.kVirtualFriends)
.doc(virtualFriendId)
.set(virtualFriendInfo.toJson());
return const Left(true);
} catch (e) {
debugPrint("error creating virtual friend: ${e.toString()}");
return Right(
FailureModel(message: "Sorry, your virtual friend was not created."));
}
}
@override
Future<Either<LocalSchemaModelOfLoggedInUser, FailureModel>>
getVirtualFriends() async {
try {
// first try to fetch virtual friends locally, if exist locally, provide locally available virtual friends
LocalSchemaModelOfLoggedInUser locallyExistingFriends =
LocalSchemaModelOfLoggedInUser.fromLocalSchema(
localSchema: await SchemaHelper().getLocalSchema() ?? "{}");
if (locallyExistingFriends.virtualFriends!.isNotEmpty) {
debugPrint("Locally");
return Left(locallyExistingFriends);
}
debugPrint("From network");
LocalSchemaModelOfLoggedInUser localSchemaModelOfLoggedInUser =
LocalSchemaModelOfLoggedInUser(virtualFriends: []);
QuerySnapshot virtualFriendsSnapshot = await firestore
.collection(FirestoreCollections.kVirtualFriends)
.orderBy(VirtualFriendModel.kOrder)
.get();
for (DocumentSnapshot friend in virtualFriendsSnapshot.docs) {
VirtualFriendModel virtualFriend =
VirtualFriendModel.fromJson(friend.data() as Map<String, dynamic>);
localSchemaModelOfLoggedInUser.virtualFriends!.add(
SchemaVirtualFriendModel(info: virtualFriend, chatHistory: []));
}
// after fetching virtual friends from network, saving it locally too
await SchemaHelper().saveLocalSchema(localSchemaModelOfLoggedInUser);
return Left(localSchemaModelOfLoggedInUser);
} catch (e) {
debugPrint("error getting virtual friends: ${e.toString()}");
return Right(FailureModel(
message:
"Sorry, your virtual friends are not available at the moment."));
}
}
@override
Future<Either<List<VirtualFriendPostModel>, FailureModel>>
getVirtualFriendsPosts() async {
try {
List<VirtualFriendPostModel> posts = [];
QuerySnapshot postsSnapshot = await firestore
.collection(FirestoreCollections.kVirtualFriendsPosts)
.orderBy(VirtualFriendPostModel.kDatePublished, descending: true)
.get();
for (DocumentSnapshot post in postsSnapshot.docs) {
VirtualFriendPostModel postData = VirtualFriendPostModel.fromJson(
post.data() as Map<String, dynamic>);
posts.add(postData);
}
return Left(posts);
} catch (e) {
debugPrint("Error fetching posts: ${e.toString()}");
return Right(FailureModel(
message: "Sorry, Could not fetch Kpop Fans posts at the moment."));
}
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/repository_implementation/remote_config_repo_impl.dart | import 'package:dartz/dartz.dart';
import 'package:flutter/foundation.dart';
import 'package:kpopchat/core/constants/location_constants.dart';
import 'package:kpopchat/core/constants/network_constants.dart';
import 'package:kpopchat/core/network/client/base_client.dart';
import 'package:kpopchat/core/network/failure_model.dart';
import 'package:kpopchat/core/network/functions/get_parsed_data.dart';
import 'package:kpopchat/data/models/lat_long_model.dart';
import 'package:kpopchat/data/models/user_info_from_ip_model.dart';
import 'package:kpopchat/data/repository/remote_config_repo.dart';
class RemoteConfigRepoImpl implements RemoteConfigRepo {
final BaseClient _client;
RemoteConfigRepoImpl({required BaseClient client}) : _client = client;
@override
Future<void> getUserInfoFromIP() async {
final response = await _client.getRequest(
path: NetworkConstants.urlForIPInfo, requiresAuthorization: false);
Either<UserInfoFromIPModel, FailureModel> infoFromIP =
await getParsedData(response, UserInfoFromIPModel.fromJson);
infoFromIP.fold((receivedInfo) {
LocationConstants.userLocationFromIP =
LatLong(lat: receivedInfo.lat, long: receivedInfo.lon);
debugPrint("REMOTE CONFIG: values from IP received");
}, (r) {
debugPrint("error receiving info from ip: ${r.message}");
});
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/repository_implementation/real_users_repo_impl.dart | import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dartz/dartz.dart';
import 'package:flutter/foundation.dart';
import 'package:kpopchat/core/constants/firestore_collections_constants.dart';
import 'package:kpopchat/core/constants/shared_preferences_keys.dart';
import 'package:kpopchat/core/network/failure_model.dart';
import 'package:kpopchat/core/utils/service_locator.dart';
import 'package:kpopchat/data/models/user_model.dart';
import 'package:kpopchat/data/repository/real_users_repo.dart';
import 'package:shared_preferences/shared_preferences.dart';
class RealUsersRepoImpl extends RealUsersRepo {
final FirebaseFirestore firestore;
RealUsersRepoImpl(this.firestore);
@override
Future<Either<List<UserModel>, FailureModel>> fetchRealUsersData() async {
try {
List<UserModel> realUsers = [];
// Get real users data excluding logged in user
QuerySnapshot realUsersSnapshot =
await firestore.collection(FirestoreCollections.kUsers).get();
for (DocumentSnapshot realUser in realUsersSnapshot.docs) {
UserModel user =
UserModel.fromJson(realUser.data() as Map<String, dynamic>);
realUsers.add(user);
}
return Left(realUsers);
} catch (e) {
debugPrint("error getting real users data: ${e.toString()}");
return Right(
FailureModel(message: "Failed to retreive other users information"));
}
}
@override
Future<void> updateUserLocationAndGhostModeStatus(
UserModel updatedUserData) async {
try {
await firestore
.collection(FirestoreCollections.kUsers)
.doc(updatedUserData.userId)
.set(updatedUserData.toJson());
locator<SharedPreferences>().setString(
SharedPrefsKeys.kUserProfile, jsonEncode(updatedUserData.toJson()));
debugPrint("User location data updated");
} catch (e) {
debugPrint("error updating user loc and ghost mode: ${e.toString()}");
}
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/models/virtual_friend_model.dart | import 'package:dash_chat_2/dash_chat_2.dart';
import 'package:kpopchat/data/models/lat_long_model.dart';
class VirtualFriendModel {
String? id;
int? order;
String? name;
String? country;
String? city;
String? displayPictureUrl;
String? profession;
String? lastUnlockedTime;
List<dynamic>? hobbies;
LatLong? latLong;
int? age;
VirtualFriendModel({
this.id,
this.order,
this.name,
this.country,
this.city,
this.displayPictureUrl,
this.profession,
this.lastUnlockedTime,
this.hobbies,
this.latLong,
});
static const String kId = "id";
static const String kOrder = "order";
static const String kName = "name";
static const String kCountry = "country";
static const String kCity = "city";
static const String kDisplayPictureUrl = "display_picture_url";
static const String kProfession = "profession";
static const String kLastUnlockedTime = "last_unlocked_time";
static const String kHobbies = "hobbies";
static const String kAge = "age";
static const String kLatLong = "latlong";
VirtualFriendModel.fromJson(Map<String, dynamic> json) {
id = json[kId];
order = json[kOrder];
name = json[kName];
country = json[kCountry];
city = json[kCity];
displayPictureUrl = json[kDisplayPictureUrl];
profession = json[kProfession];
lastUnlockedTime = json[kLastUnlockedTime];
hobbies = json[kHobbies];
age = json[kAge];
if (json[kLatLong] != null) {
latLong = LatLong.fromJson(json[kLatLong]);
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> json = <String, dynamic>{};
json[kId] = id;
json[kOrder] = order;
json[kName] = name;
json[kCountry] = country;
json[kCity] = city;
json[kDisplayPictureUrl] = displayPictureUrl;
json[kProfession] = profession;
json[kLastUnlockedTime] = lastUnlockedTime;
json[kHobbies] = hobbies;
json[kAge] = age;
json[kLatLong] = latLong?.toJson();
return json;
}
ChatUser toChatUser() {
return ChatUser(id: id!, profileImage: displayPictureUrl, firstName: name);
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/models/user_info_from_ip_model.dart | class UserInfoFromIPModel {
String? status;
String? country;
String? countryCode;
String? phoneCode;
String? region;
String? regionName;
String? city;
String? zip;
double? lat;
double? lon;
String? timezone;
String? isp;
String? org;
String? as;
String? query;
UserInfoFromIPModel(
{this.status,
this.country,
this.countryCode,
this.region,
this.regionName,
this.city,
this.zip,
this.lat,
this.lon,
this.timezone,
this.isp,
this.org,
this.as,
this.query});
UserInfoFromIPModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
country = json['country'];
countryCode = json['countryCode'];
phoneCode = json['phoneCode'];
region = json['region'];
regionName = json['regionName'];
city = json['city'];
zip = json['zip'];
lat = json['lat'];
lon = json['lon'];
timezone = json['timezone'];
isp = json['isp'];
org = json['org'];
as = json['as'];
query = json['query'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['status'] = status;
data['country'] = country;
data['countryCode'] = countryCode;
data['phoneCode'] = phoneCode;
data['region'] = region;
data['regionName'] = regionName;
data['city'] = city;
data['zip'] = zip;
data['lat'] = lat;
data['lon'] = lon;
data['timezone'] = timezone;
data['isp'] = isp;
data['org'] = org;
data['as'] = as;
data['query'] = query;
return data;
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/models/lat_long_model.dart | import 'package:location/location.dart';
class LatLong {
double? lat;
double? long;
LatLong({this.lat, this.long});
static const String kLat = "latitude";
static const String kLong = "longitude";
LatLong.fromJson(Map<String, dynamic> json) {
lat = json[kLat];
long = json[kLong];
}
Map<String, dynamic> toJson() {
return {
kLat: lat,
kLong: long,
};
}
LocationData toLocationData() {
return LocationData.fromMap(toJson());
}
}
/// Usable in Friends Map Screen with value notifier when there is need to zoom on user's location
class LatLongAndZoom {
LatLong? latLong;
double? zoom;
LatLongAndZoom({this.latLong, this.zoom});
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/models/local_schema_model.dart | import 'dart:convert';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:kpopchat/core/utils/schema_helper.dart';
import 'package:kpopchat/core/utils/service_locator.dart';
import 'package:kpopchat/data/models/schema_virtual_friend_model.dart';
class LocalSchemaModelOfLoggedInUser {
List<SchemaVirtualFriendModel>? virtualFriends;
LocalSchemaModelOfLoggedInUser({this.virtualFriends});
static const String kVirtualFriends = "virtual_friends";
/// Provide whole schema in string, id of logged in user and get model of schema for this logged in user
LocalSchemaModelOfLoggedInUser.fromLocalSchema(
{required String localSchema}) {
String? loggedInUserId = locator<FirebaseAuth>().currentUser?.uid;
List<dynamic>? friendsInSchema = jsonDecode(localSchema)[loggedInUserId];
virtualFriends ??= [];
if (friendsInSchema != null) {
for (Map<String, dynamic> eachVirtualFriend in friendsInSchema) {
virtualFriends!
.add(SchemaVirtualFriendModel.fromJson(eachVirtualFriend));
}
}
}
/// To be used to save virtual friends data from network to local schema
Future<Map<String, dynamic>> toJson() async {
String? loggedInUserId = locator<FirebaseAuth>().currentUser?.uid;
Map<String, dynamic> localSchema =
jsonDecode(await SchemaHelper().getLocalSchema() ?? "{}");
List<Map<String, dynamic>> virtualFriendsToStoreInSchema = [];
for (SchemaVirtualFriendModel vf in virtualFriends!) {
virtualFriendsToStoreInSchema.add(vf.toJson());
}
localSchema[loggedInUserId!] = virtualFriendsToStoreInSchema;
return localSchema;
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/models/open_ai_resp_model.dart | class OpenAIResponseModel {
Openai? openai;
OpenAIResponseModel({this.openai});
OpenAIResponseModel.fromJson(Map<String, dynamic> json) {
openai = json['openai'] != null ? Openai.fromJson(json['openai']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
if (openai != null) {
data['openai'] = openai!.toJson();
}
return data;
}
}
class Openai {
String? status;
String? generatedText;
List<Message>? message;
double? cost;
Openai({this.status, this.generatedText, this.message, this.cost});
Openai.fromJson(Map<String, dynamic> json) {
status = json['status'];
generatedText = json['generated_text'];
if (json['message'] != null) {
message = <Message>[];
json['message'].forEach((v) {
message!.add(Message.fromJson(v));
});
}
cost = json['cost'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['status'] = status;
data['generated_text'] = generatedText;
if (message != null) {
data['message'] = message!.map((v) => v.toJson()).toList();
}
data['cost'] = cost;
return data;
}
}
class Message {
String? role;
String? message;
Message({this.role, this.message});
Message.fromJson(Map<String, dynamic> json) {
role = json['role'];
message = json['message'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['role'] = role;
data['message'] = message;
return data;
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/models/schema_message_model.dart | // below class is used to deserialize data of values in conversations array of each virtual friends stored in schema
import 'package:dash_chat_2/dash_chat_2.dart';
import 'package:kpopchat/core/utils/shared_preferences_helper.dart';
class SchemaMessageModel {
String? role;
String? message;
String? createdAt;
bool? botReplied;
SchemaMessageModel(
{this.role, this.message, this.createdAt, this.botReplied});
static const String kKeyRole = "role";
static const String kKeyMsg = "message";
static const String kKeyCreatedAt = "createdAt";
static const String kKeyFollowUpTime = "followupTime";
static const String kKeybotReplied = "reply";
/// msg can be from three entity which are (system, assistant and user)
/// so below static constats are kept
static const String kKeySystemRole = "system";
static const String kKeyVirtualFriendRole = "assistant";
static const String kKeyUserRole = "user";
SchemaMessageModel.fromJson(Map<String, dynamic> json) {
role = json[kKeyRole];
message = json[kKeyMsg];
createdAt = json[kKeyCreatedAt];
botReplied = json[kKeybotReplied];
}
Map<String, dynamic> toJson() {
return {kKeyRole: role, kKeyMsg: message, kKeyCreatedAt: createdAt};
}
SchemaMessageModel.fromChatMessage(ChatMessage msg) {
bool msgIsByUser =
SharedPrefsHelper.getUserProfile()?.userId == msg.user.id;
role = msgIsByUser
? SchemaMessageModel.kKeyUserRole
: SchemaMessageModel.kKeyVirtualFriendRole;
message = msg.text;
createdAt = msg.createdAt.toString();
}
ChatMessage toChatMessage(ChatUser msgSender) {
return ChatMessage(
text: message ?? "",
user: msgSender,
createdAt: DateTime.parse(createdAt!).toLocal());
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/models/schema_virtual_friend_model.dart | import 'package:dash_chat_2/dash_chat_2.dart';
import 'package:kpopchat/core/utils/shared_preferences_helper.dart';
import 'package:kpopchat/data/models/schema_message_model.dart';
import 'package:kpopchat/data/models/user_model.dart';
import 'virtual_friend_model.dart';
class SchemaVirtualFriendModel {
VirtualFriendModel? info;
List<SchemaMessageModel>? chatHistory;
SchemaVirtualFriendModel({this.info, this.chatHistory});
static const String kInfo = "info";
static const String kChatHistory = "chat_history";
SchemaVirtualFriendModel.fromJson(Map<String, dynamic> json) {
info = VirtualFriendModel.fromJson(json[kInfo]);
chatHistory ??= [];
for (Map<String, dynamic> msg in json[kChatHistory] ?? []) {
chatHistory?.add(SchemaMessageModel.fromJson(msg));
}
}
Map<String, dynamic> toJson() {
List<Map<String, dynamic>> history = [];
for (SchemaMessageModel msg in chatHistory ?? []) {
history.add(msg.toJson());
}
return {kInfo: info?.toJson(), kChatHistory: history};
}
List<ChatMessage> toListOfChatMessages() {
List<ChatMessage> listOfChatMessages = [];
UserModel? loggedInUser = SharedPrefsHelper.getUserProfile();
ChatUser user = ChatUser(
id: loggedInUser!.userId!,
profileImage: loggedInUser.photoURL,
firstName: loggedInUser.displayName);
ChatUser friend = ChatUser(
id: info!.id!,
profileImage: info!.displayPictureUrl,
firstName: info!.name);
for (SchemaMessageModel eachMsg in chatHistory!) {
final bool msgIsByUser = eachMsg.role == SchemaMessageModel.kKeyUserRole;
final ChatMessage msg =
eachMsg.toChatMessage(msgIsByUser ? user : friend);
listOfChatMessages.add(msg);
}
return listOfChatMessages;
}
List<Map<String, dynamic>> toListOfJsonMessages() {
List<Map<String, dynamic>> listOfMessages = [];
for (SchemaMessageModel eachMsg in chatHistory!) {
listOfMessages.add(eachMsg.toJson());
}
return listOfMessages;
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/models/virtual_friend_post_model.dart | import 'package:flutter/foundation.dart';
import 'package:kpopchat/data/models/virtual_friend_model.dart';
class VirtualFriendPostModel {
String? postId;
DateTime? datePublished;
VirtualFriendModel? poster;
String? caption;
int? viewsCount;
VirtualFriendPostModel(
{this.postId,
this.datePublished,
this.poster,
this.caption,
this.viewsCount});
static const String kDatePublished = "date_published";
static const String kPostId = "post_id";
static const String kPoster = "poster";
static const String kCaption = "caption";
static const String kViewsCount = "views_count";
Map<String, dynamic> toJson() => {
kDatePublished: datePublished,
kPostId: postId,
kPoster: poster?.toJson(),
kCaption: caption,
kViewsCount: viewsCount
};
VirtualFriendPostModel.fromJson(Map<String, dynamic> json) {
postId = json[kPostId];
try {
datePublished = json[kDatePublished].toDate();
} catch (e) {
datePublished = DateTime.now();
debugPrint("Error parsing post date: ${e.toString()} ");
}
poster = VirtualFriendModel.fromJson(json[kPoster]);
caption = json[kCaption];
viewsCount = json[kViewsCount];
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/data | mirrored_repositories/Kpop-Chat/lib/data/models/user_model.dart | import 'package:firebase_auth/firebase_auth.dart';
import 'package:kpopchat/data/models/lat_long_model.dart';
class UserModel {
String? userId;
String? displayName;
String? email;
bool? emailVerified;
bool? isAnonymous;
String? photoURL;
int? kpopScore;
LatLong? latLong;
bool? anonymizeLocation;
// DateTime? dateJoined;
static const String kUid = "uid";
static const String kDisplayName = "displayName";
static const String kEmail = "email";
static const String kEmailVerified = "isEmailVerified";
static const String kIsAnonymous = "isAnonymous";
static const String kPhotoURL = "photoURL";
static const String kScore = "score";
static const String kLatLong = "lat_long";
static const String kAnonymizeLocation = "anonymize_location";
// static const String kDateJoined = "date_joined";
UserModel.fromJson(Map<String, dynamic> json) {
userId = json[kUid];
displayName = json[kDisplayName];
email = json[kEmail];
emailVerified = json[kEmailVerified];
isAnonymous = json[kIsAnonymous];
photoURL = json[kPhotoURL];
kpopScore = json[kScore];
if (json[kLatLong] != null && json[kLatLong] != "null") {
latLong = LatLong.fromJson(json[kLatLong]);
}
anonymizeLocation = json[kAnonymizeLocation] ?? true;
// try {
// dateJoined = json[kDateJoined] == null
// ? DateTime.now()
// : DateTime.parse(json[kDateJoined]);
// } catch (e) {
// debugPrint("Error parsing date ${e}");
// }
}
UserModel.fromFirebaseCurrentUser(User currentUser) {
userId = currentUser.uid;
displayName = currentUser.displayName;
email = currentUser.email;
emailVerified = currentUser.emailVerified;
isAnonymous = currentUser.isAnonymous;
photoURL = currentUser.photoURL;
}
Map<String, dynamic> toJson() {
return {
kUid: userId,
kDisplayName: displayName,
kEmail: email,
kEmailVerified: emailVerified,
kIsAnonymous: isAnonymous,
kPhotoURL: photoURL,
kScore: kpopScore,
kLatLong: latLong?.toJson(),
kAnonymizeLocation: anonymizeLocation,
// if (dateJoined != null) kDateJoined: dateJoined.toString(),
};
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/network/failure_model.dart | import 'package:kpopchat/core/constants/text_constants.dart';
class FailureModel {
String? message;
FailureModel({this.message});
FailureModel.fromJson(Map<String, dynamic> json) {
message = json['message'] ?? TextConstants.defaultErrorMsg;
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core/network | mirrored_repositories/Kpop-Chat/lib/core/network/client/base_client.dart | import 'package:dio/dio.dart';
abstract class BaseClient {
Future<Response<dynamic>?> getRequest({
String baseUrl = "",
Map<String, String>? optionalHeaders,
Map<String, dynamic>? queryParameters,
required String path,
bool showDialog = false,
bool shouldCache = true,
bool requiresAuthorization = true,
});
Future<Response<dynamic>?> postRequest({
String baseUrl = "",
Map<String, String>? optionalHeaders,
Map<String, dynamic>? data,
required String path,
bool showDialog = false,
bool requiresAuthorization = true,
});
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core/network | mirrored_repositories/Kpop-Chat/lib/core/network/client/base_client_impl.dart | import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:kpopchat/core/network/client/base_client.dart';
import 'package:kpopchat/core/network/functions/get_header.dart';
import 'package:kpopchat/presentation/common_widgets/network_call_loading_widgets.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
class BaseClientImplementation extends BaseClient {
@override
Future<Response<dynamic>?> getRequest({
String baseUrl = "",
Map<String, String>? optionalHeaders,
Map<String, dynamic>? queryParameters,
required String path,
bool showDialog = false,
bool shouldCache = true,
bool requiresAuthorization = true,
}) async {
Response? response;
if (showDialog) {
showLoadingDialog();
}
try {
Map<String, String> header =
getHeader(requiresAuthorization: requiresAuthorization);
if (optionalHeaders != null) {
header.addAll(optionalHeaders);
}
Dio dio = Dio();
if (kDebugMode) {
dio.interceptors.add(PrettyDioLogger(
error: true,
requestBody: true,
requestHeader: true,
request: false,
responseBody: false,
));
}
response = await dio.get(
baseUrl + path,
options: Options(
headers: header,
sendTimeout: const Duration(seconds: 40),
receiveTimeout: const Duration(seconds: 40),
),
);
debugPrint("post req resp: $response");
} catch (e) {
debugPrint("post req exception: $e");
}
if (showDialog) hideLoadingDialog();
return response;
}
@override
Future<Response<dynamic>?> postRequest({
String baseUrl = "",
Map<String, String>? optionalHeaders,
Map<String, dynamic>? data,
required String path,
bool showDialog = false,
bool requiresAuthorization = true,
}) async {
Response? response;
if (showDialog) {
showLoadingDialog();
}
try {
Map<String, String> header =
getHeader(requiresAuthorization: requiresAuthorization);
if (optionalHeaders != null) {
header.addAll(optionalHeaders);
}
Dio dio = Dio();
if (kDebugMode) {
dio.interceptors.add(PrettyDioLogger(
error: true,
requestBody: true,
requestHeader: true,
request: false,
responseBody: false,
));
}
response = await dio.post(
baseUrl + path,
options: Options(
headers: header,
sendTimeout: const Duration(seconds: 40),
receiveTimeout: const Duration(seconds: 40),
),
data: data,
);
debugPrint("post req resp: $response");
} catch (e) {
debugPrint("post req exception: $e");
}
if (showDialog) hideLoadingDialog();
return response;
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core/network | mirrored_repositories/Kpop-Chat/lib/core/network/functions/get_parsed_data.dart | import 'package:dartz/dartz.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:kpopchat/core/network/failure_model.dart';
List<int> successStatusCodes = [200, 201, 202, 204];
Future<Either<T, FailureModel>> getParsedData<T>(
Response? response, dynamic fromJson) async {
if (response != null && successStatusCodes.contains(response.statusCode)) {
//handle success here
if (response.data is Map) {
try {
return Left(fromJson(response.data));
} catch (e) {
debugPrint("Error parsing data: $e");
// return Right(Failure.fromJson({}));
return Right(FailureModel.fromJson(response.data));
}
} else if (response.statusCode == 204) {
// status code 204 means success but no response data
return left(fromJson);
} else {
return Right(
FailureModel.fromJson({}),
);
}
} else {
Map<String, dynamic>? failedRespData;
try {
failedRespData = response?.data;
} catch (e) {
debugPrint("Could not parse backend response as map");
failedRespData = {};
}
return Right(
FailureModel.fromJson(failedRespData ?? {}),
);
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core/network | mirrored_repositories/Kpop-Chat/lib/core/network/functions/get_header.dart | import 'package:kpopchat/core/constants/network_constants.dart';
Map<String, String> getHeader({
bool requiresAuthorization = true,
}) {
return {
"Content-Type": "application/json",
if (requiresAuthorization)
"Authorization": "Bearer ${NetworkConstants.edenAIKey}",
};
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/constants/google_ads_test_id.dart | /// Below constants are the test ad id for different kinds of Google Ads
class GoogleAdsTestId {
static const String kTestBannerAdId =
'ca-app-pub-3940256099942544/6300978111';
static const String kTestInterstitialAdId =
'ca-app-pub-3940256099942544/1033173712';
static const String kTestRewardedAdId =
'ca-app-pub-3940256099942544/5224354917';
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/constants/text_constants.dart | class TextConstants {
static const kNunitoFont = "Nunito";
static const kBarlowFont = "Barlow";
static const appName = "Kpop Chat";
static const appNameKorean = "μΌμ΄ν μ±ν
";
static const defaultErrorMsg =
"Oops! It seems like there was a technical hiccup. Please try again later.";
static const String areYouSure = "Are you sure you want to";
static const String closeAppTitle = "$areYouSure close this app?";
static const String logoutTitle = "$areYouSure sign out?";
static const String logoutText = "Sign out";
static const String noInternetMsg =
"Please check your internet connection and try again later.";
static const String writeYourMsgHint = "Chat about Kpop...";
static const String reportPostTitle = "Report this Kpop Fan's post?";
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/constants/firebase_remote_config_keys.dart | class RemoteConfigKeys {
static const String kKeyEdenAI = "eden_ai_key";
static const String kKeySystemMsg = "system_msg_key";
static const String kKeyTemperature = "temperature";
static const String kKeyMaxTokens = "max_tokens";
static const String kKeyMaxMsgsToTake = "max_messages_to_take";
static const String kKeyChatRewardUnlockTimeInMins =
"chat_reward_unlock_time_in_mins";
static const String kKeyMessagesToAllowAfterShowingOneAd =
"messages_to_allow_after_showing_one_ad";
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/constants/decoration_constants.dart | class DecorationConstants {
static const double borderRadiusOfBubbleMsg = 25;
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/constants/location_constants.dart | import 'package:kpopchat/data/models/lat_long_model.dart';
class LocationConstants {
/// assign its value on app launch (service locator)
static LatLong? userLocationFromIP;
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/constants/color_constants.dart | import 'package:flutter/material.dart';
class ColorConstants {
static const Color primaryColor = Colors.blue;
static const Color primaryColorPink = Colors.pinkAccent;
static const Color darkPrimaryColor = Colors.white;
static const Color unCheckedColorDarkTheme = Colors.black26;
static const Color unCheckedColorLightTheme =
Color.fromARGB(255, 193, 223, 255);
static const Color bgColorOfBotMsgLightTheme = Color(0xFFF4F4F4);
static const Color lightTextColor = Color(0xFF344563);
static const Color blackBGForDarkTheme = Colors.black12;
static const Color bgColorOfBotMsgDarkTheme = Colors.white10;
static const Color oxFF545454 = Color(0xFF545454);
static const Color oxFFE8ECF4 = Color(0xFFE8ECF4);
static const Color oxFF6A707C = Color(0xFF6A707C);
static const Color successColor = Color(0xFF1DD75B);
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/constants/network_constants.dart | class NetworkConstants {
static const String baseUrl = "";
static const String edenAIbaseUrl = "https://api.edenai.run/";
static const String edenAIChatPath = "v2/text/chat";
static String edenAIKey = "";
static const String policyUrl =
"https://aprashantz.github.io/kpop-chat-policy/";
static const String urlForIPInfo = "http://ip-api.com/json";
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/constants/analytics_constants.dart | class AnalyticsConstants {
/// to be used when sign in with google btn is clicked
static const String kEventSignInClick = "sign_in_clicked";
/// to be used when user is actually signed in and navigated to dashboard
static const String kEventSignedIn = "signed_in";
static const String kEventMenuScreenClicked = "menu_clicked";
static const String kEventSignOut = "signed_out";
static const String kEventPolicyClicked = "policy_clicked";
static const String kProperyMsgSentCount = "total_messages_sent";
static const String kPropertyRewardsEarned = "rewards_earned";
static const String kPropertyEdenAiCreditSpent = "edenai_credit_spent";
/// maps analytics constats
static const String kClickedPreciseLocation = "precise_location_clicked";
static const String kClickedGhostMode = "ghost_mode_clicked";
static const String kClickedVirtualFriendMapMarker =
"vitual_friend_marker_clicked";
static const String kClickedRealUserMapMarker = "real_user_marker_clicked";
// below is ad events and properties
static const String kEventBannerAdLoaded = "banner_ad_loaded";
static const String kEventBannerAdOpened = "banner_ad_opened";
static const String kEventBannerAdClicked = "banner_ad_clicked";
static const String kEventBannerAdApproxPaid = "banner_ad_paid";
static const String kEventInterstitialAdShowed = "interstitial_ad_shown";
static const String kEventRewardedAdEarnedReward =
"rewarded_ad_earned_reward";
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/constants/remote_config_values.dart | class RemoteConfigValues {
/// to be later updated from firebase remote config
static String systemMsg =
"Act as an hardcore Kpop fan and respond like how a Kpop fan would reply to that. Do not make long message reply. Respond like how humans casually text/message on social media using slangs or shortcut texting style. The provided json data has information of you. It is your personal identity and you should respond/ act like a human (hardcore Kpop fan). Always try to make the conversation related to Kpop and be interactive. Ask about kpop to the user, what do they like and similar stuffs just like how two friends who like kpop would interact. If user tries to talk about other topics other than kpop, divert the topic back to Kpop.";
static double temperature = 0.5;
static int maxTokens = 40;
static int maxMessagesToTake = 5;
static int chatRewardUnlockTimeInMins = 60;
static int msgsToAllowAfterShowingOneAd = 6;
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/constants/asset_path_constants.dart | class AssetPathConstants {
static const String kSpiralLines = "assets/spiral_lines.svg";
static const String kGoogleLogo = "assets/google_logo.png";
static const String kLogoNoBG = "assets/logo_no_bg.PNG";
static const String kLogoIcon = "assets/logo_icon.jpg";
static const String kDefaultProfilePic = "assets/default_dp.jpg";
static const String kComposeIcon = "assets/compose_icon.png";
static const String kWaitingGirlGIF = "assets/waiting_girl.gif";
static const String kWaitingDogGIF = "assets/waiting_dog.gif";
static const String kFriendsJPG = "assets/friends.jpg";
static const String kMedalPNG = "assets/medal.png";
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/constants/firestore_collections_constants.dart | class FirestoreCollections {
static const String kVirtualFriends = "virtual_friends";
static const String kUsers = "users";
static const String kVirtualFriendsPosts = "virtual_friends_posts";
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/constants/shared_preferences_keys.dart | /// Class that holds keys of shared preferences
class SharedPrefsKeys {
static const String isDarkMode = "is_dark_mode";
static const String kSchemaKey = "local_schema";
static const String kUserProfile = "user_profile";
static const String kFriendLastUnlockTime = "friend_last_unlock_time";
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/routes/app_routes.dart | class AppRoutes {
static const String authCheckerScreen = "/auth-checker-screen";
static const String signInScreen = "/sign-in-screen";
static const String dashboardScreen = "/dashboard-screen";
static const String virtualFriendsListScreen = "/virtual-friends-list-screen";
static const String chatScreen = "/chat-screen";
static const String friendProfileScreen = "/friend-profile-screen";
static const String menuScreen = "/menu-screen";
static const String adminPostMonitorScreen = "/admin-post-monitor-screen";
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/routes/route_generator.dart | import 'package:flutter/cupertino.dart';
import 'package:kpopchat/admin_controls/admin_post_monitor.dart';
import 'package:kpopchat/data/models/virtual_friend_model.dart';
import 'package:kpopchat/presentation/screens/auth_checker_screen.dart';
import 'package:kpopchat/presentation/screens/chat_screen/chat_screen.dart';
import 'package:kpopchat/presentation/screens/dashboard_screen/dashboard_screen.dart';
import 'package:kpopchat/presentation/screens/menu_screen.dart';
import 'package:kpopchat/presentation/screens/sign_in_screen.dart';
import 'package:kpopchat/presentation/screens/virtual_friend_profile_screen.dart';
import 'app_routes.dart';
Route<dynamic> onGenerateRoute(RouteSettings settings) {
Object? argument = settings.arguments;
switch (settings.name) {
case AppRoutes.authCheckerScreen:
return CupertinoPageRoute(
builder: (context) => const AuthCheckerScreen());
case AppRoutes.signInScreen:
return CupertinoPageRoute(builder: (context) => const SignInScreen());
case AppRoutes.dashboardScreen:
return CupertinoPageRoute(builder: (context) => const DashboardScreen());
case AppRoutes.menuScreen:
return CupertinoPageRoute(builder: (context) => const MenuScreen());
case AppRoutes.chatScreen:
return CupertinoPageRoute(
builder: (context) =>
ChatScreen(virtualFriend: argument as VirtualFriendModel));
case AppRoutes.friendProfileScreen:
return CupertinoPageRoute(
builder: (context) => VirtualFriendProfileScreen(
friendInfo: argument as VirtualFriendModel));
// FYI AdminPostMonitorScreen is gitignored
case AppRoutes.adminPostMonitorScreen:
return CupertinoPageRoute(builder: (context) => AdminPostMonitorScreen());
default:
return CupertinoPageRoute(builder: (context) => const SignInScreen());
}
}
pageRouteBuilder({required Widget screen}) {
return PageRouteBuilder(
transitionDuration: const Duration(milliseconds: 200),
pageBuilder: (context, animation, secondaryAnimation) => screen,
transitionsBuilder: (context, animation, secondaryAnimation, child) {
var begin = const Offset(-1.0, 0.0);
var end = Offset.zero;
var tween = Tween(begin: begin, end: end);
var offsetAnimation = animation.drive(tween);
return SlideTransition(
position: offsetAnimation,
child: child,
);
},
);
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/themes/light_theme.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kpopchat/core/constants/color_constants.dart';
import 'package:kpopchat/core/constants/text_constants.dart';
final lightTheme = ThemeData(
brightness: Brightness.light,
// useMaterial3: true,
fontFamily: TextConstants.kBarlowFont,
primaryColor: ColorConstants.primaryColor,
colorScheme: const ColorScheme.light(
primary: ColorConstants.primaryColor,
primaryContainer: Color(0xFF212121),
onPrimary: ColorConstants.primaryColor,
secondary: Colors.white,
onSecondary: Colors.white,
tertiary: ColorConstants.unCheckedColorLightTheme,
onTertiary: ColorConstants.bgColorOfBotMsgLightTheme,
// error: Colors.red,
// onError: Colors.red,
background: Colors.white,
// onBackground: Colors.white,
// surface: Colors.white,
// onSurface: AppColors.primaryColor,
),
iconTheme: const IconThemeData(
color: ColorConstants.primaryColor,
),
checkboxTheme: CheckboxThemeData(
fillColor: MaterialStateProperty.all(ColorConstants.primaryColor),
checkColor: MaterialStateProperty.all(Colors.white),
),
dividerTheme: DividerThemeData(
color: Colors.grey.withOpacity(0.5),
),
// dialogBackgroundColor: Colors.white,
// dialogTheme: DialogTheme(
// backgroundColor: Colors.white,
// contentTextStyle: TextStyle(
// color: AppColors.lightTextColor,
// fontSize: 16.sp,
// fontWeight: FontWeight.normal,
// ),
// titleTextStyle: TextStyle(
// color: AppColors.lightTextColor,
// fontSize: 18.sp,
// fontWeight: FontWeight.normal,
// ),
// ),
// radioTheme: RadioThemeData(
// fillColor: MaterialStateProperty.all(AppColors.primaryColor)),
// cardColor: Colors.white,
// switchTheme: SwitchThemeData(
// thumbColor: MaterialStateProperty.all<Color>(AppColors.primaryColor),
// trackColor:
// MaterialStateProperty.all(const Color.fromRGBO(35, 116, 225, 0.2))),
// scaffoldBackgroundColor: Colors.white,
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
backgroundColor: ColorConstants.primaryColor,
foregroundColor: Colors.white,
textStyle: TextStyle(color: Colors.white, fontSize: 18.sp),
)),
appBarTheme: AppBarTheme(
elevation: 0,
backgroundColor: Colors.grey,
systemOverlayStyle: SystemUiOverlayStyle(
// statusBarBrightness: Brightness.light,
statusBarColor: Colors.grey,
statusBarIconBrightness: Brightness.dark,
),
titleTextStyle: TextStyle(
color: Colors.black,
fontSize: 15.sp,
),
actionsIconTheme:
const IconThemeData(color: ColorConstants.lightTextColor),
),
// bottomAppBarTheme: BottomAppBarTheme(
// // color: AppColors.lightScaffoldColor,
// ),
// bottomAppBarColor: AppColors.lightScaffoldColor,
hintColor: Colors.grey,
floatingActionButtonTheme: const FloatingActionButtonThemeData(
foregroundColor: Colors.white,
backgroundColor: ColorConstants.primaryColor,
),
listTileTheme:
const ListTileThemeData(iconColor: ColorConstants.primaryColor));
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/themes/dark_theme.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kpopchat/core/constants/color_constants.dart';
import 'package:kpopchat/core/constants/text_constants.dart';
final darkTheme = ThemeData(
brightness: Brightness.dark,
primaryColor: ColorConstants.darkPrimaryColor,
fontFamily: TextConstants.kBarlowFont,
colorScheme: const ColorScheme.dark(
primary: ColorConstants.darkPrimaryColor,
primaryContainer: Color(0xFFF5F5F5),
onPrimary: ColorConstants.blackBGForDarkTheme,
secondary: Color(0xFF9E9E9E),
onSecondary: Colors.black12,
background: Colors.black,
tertiary: ColorConstants.unCheckedColorDarkTheme,
onTertiary: ColorConstants.bgColorOfBotMsgDarkTheme,
// Define other colors for dark theme
),
iconTheme: const IconThemeData(
color: ColorConstants.darkPrimaryColor,
),
appBarTheme: AppBarTheme(
elevation: 0,
backgroundColor: Colors.grey[800],
systemOverlayStyle: SystemUiOverlayStyle(
statusBarColor: Colors.black,
statusBarIconBrightness: Brightness.light,
),
titleTextStyle: TextStyle(
color: Colors.white,
fontSize: 15.sp,
),
actionsIconTheme: const IconThemeData(color: Color(0xFFF5F5F5)),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
backgroundColor: ColorConstants.blackBGForDarkTheme,
foregroundColor: Colors.white,
textStyle: TextStyle(color: Colors.black, fontSize: 18.sp),
)),
floatingActionButtonTheme: const FloatingActionButtonThemeData(
foregroundColor: Colors.white,
backgroundColor: Colors.black54,
),
checkboxTheme: CheckboxThemeData(
fillColor: MaterialStateProperty.all(Colors.white),
checkColor: MaterialStateProperty.all(Colors.black),
),
);
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/utils/admob_services.dart | import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:kpopchat/core/constants/analytics_constants.dart';
import 'package:kpopchat/core/utils/analytics.dart';
import 'package:kpopchat/main.dart';
class AdMobServices {
static BannerAdListener bannerAdListener = BannerAdListener(
onAdLoaded: (ad) {
if (!kDebugMode) {
logEventInAnalytics(AnalyticsConstants.kEventBannerAdLoaded);
}
debugPrint('Ad loaded.');
},
onAdFailedToLoad: (ad, error) {
ad.dispose();
debugPrint('ad failed to load: $error');
},
onAdOpened: (ad) {
if (!kDebugMode) {
logEventInAnalytics(AnalyticsConstants.kEventBannerAdOpened);
}
debugPrint('Ad opened');
},
onAdClosed: (ad) => debugPrint('Ad closed'),
onAdClicked: (ad) {
if (!kDebugMode) {
logEventInAnalytics(AnalyticsConstants.kEventBannerAdClicked);
}
debugPrint('Ad clicked');
},
onPaidEvent: (ad, valueMicros, precision, currencyCode) {
if (!kDebugMode) {
logEventInAnalytics(AnalyticsConstants.kEventBannerAdApproxPaid);
}
debugPrint('Ad paid event');
},
);
static Future<BannerAd> getBannerAdByGivingAdId(String bannerAdId) async {
final AnchoredAdaptiveBannerAdSize? size =
await AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(
MediaQuery.of(navigatorKey.currentContext!).size.width.truncate());
return BannerAd(
size: size ?? AdSize.banner,
adUnitId: bannerAdId,
listener: AdMobServices.bannerAdListener,
request: const AdRequest());
}
static Future<void> showInterstitialAd(
ValueNotifier<InterstitialAd?> interstitialAdNotifier,
Function() callBackToLoadInterstitialAd) async {
if (interstitialAdNotifier.value != null) {
interstitialAdNotifier.value!.fullScreenContentCallback =
FullScreenContentCallback(
onAdDismissedFullScreenContent: (ad) {
ad.dispose();
callBackToLoadInterstitialAd();
},
onAdFailedToShowFullScreenContent: (ad, error) {
debugPrint("failed to show interstitial ad");
ad.dispose();
callBackToLoadInterstitialAd();
},
onAdShowedFullScreenContent: (ad) {
if (!kDebugMode) {
logEventInAnalytics(AnalyticsConstants.kEventInterstitialAdShowed);
}
debugPrint("Showed Interstitial ad full screen content");
},
);
interstitialAdNotifier.value!.show();
interstitialAdNotifier.value = null;
}
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/utils/get_view_count_string.dart | /// function to get views count in integer and returns string views count without providing exact view count
String getViewCount(int viewCount) {
if (viewCount < 5) {
return viewCount.toString();
} else if (viewCount < 10) {
return "5+";
} else if (viewCount < 20) {
return "10+";
} else if (viewCount < 30) {
return "20+";
} else if (viewCount < 50) {
return "30+";
} else if (viewCount < 100) {
return "50+";
} else {
int nearestHundred = (viewCount + 99) ~/ 100 * 100;
return "$nearestHundred+";
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/utils/date_to_string.dart | import 'package:intl/intl.dart';
String dateToString(String? dateTimeInString) {
if (dateTimeInString == null || dateTimeInString == "") return "";
DateTime dateTime = DateTime.parse(dateTimeInString);
final now = DateTime.now();
final difference = now.difference(dateTime);
if (difference.inSeconds < 60) {
return 'Just now';
} else if (difference.inMinutes < 60) {
final minutes = difference.inMinutes;
return '$minutes ${minutes == 1 ? 'minute' : 'minutes'} ago';
} else if (difference.inHours < 24) {
final hours = difference.inHours;
return '$hours ${hours == 1 ? 'hour' : 'hours'} ago';
} else if (difference.inDays < 4) {
final days = difference.inDays;
return '$days ${days == 1 ? 'day' : 'days'} ago';
} else {
return DateFormat('dd MMMM yyyy').format(dateTime);
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/utils/get_geo_location_of_user.dart | import 'package:flutter/foundation.dart';
import 'package:kpopchat/core/constants/location_constants.dart';
import 'package:kpopchat/core/utils/service_locator.dart';
import 'package:location/location.dart';
/// Determine the current position of the device.
Future<LocationData?> getUserLocationData() async {
Location location = locator<Location>();
bool serviceEnabled;
PermissionStatus permissionStatus;
// Test if location services are enabled.
serviceEnabled = await location.serviceEnabled();
if (!serviceEnabled) {
// Location services are not enabled don't continue
// accessing the position and request users of the
// App to enable the location services.
// return Future.error('Location services are disabled.');
serviceEnabled = await location.requestService();
debugPrint("Location services are disabled.");
if (!serviceEnabled) {
return LocationConstants.userLocationFromIP?.toLocationData();
}
}
permissionStatus = await await location.hasPermission();
if (permissionStatus == PermissionStatus.denied) {
permissionStatus = await location.requestPermission();
if (permissionStatus == PermissionStatus.denied) {
// Permissions are denied, next time you could try
// requesting permissions again (this is also where
// Android's shouldShowRequestPermissionRationale
// returned true. According to Android guidelines
// your App should show an explanatory UI now.
// return Future.error('Location permissions are denied');
debugPrint("Location permissions are denied");
return LocationConstants.userLocationFromIP?.toLocationData();
}
}
if (permissionStatus == PermissionStatus.deniedForever) {
// Permissions are denied forever, handle appropriately.
// return Future.error(
// 'Location permissions are permanently denied, we cannot request permissions.');
debugPrint(
"Location permissions are permanently denied, we cannot request permissions.");
return LocationConstants.userLocationFromIP?.toLocationData();
}
// When we reach here, permissions are granted and we can
// continue accessing the position of the device.
debugPrint("Location permissions are granted");
return await location.getLocation();
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/utils/shared_preferences_helper.dart | import 'dart:convert';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:kpopchat/business_logic/auth_checker_cubit/auth_checker_cubit.dart';
import 'package:kpopchat/core/constants/remote_config_values.dart';
import 'package:kpopchat/core/constants/shared_preferences_keys.dart';
import 'package:kpopchat/core/utils/service_locator.dart';
import 'package:kpopchat/data/models/user_model.dart';
import 'package:kpopchat/main.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SharedPrefsHelper {
static void clearAll() {
locator<SharedPreferences>().remove(SharedPrefsKeys.kUserProfile);
}
static void saveUserProfileFromLogin(User? userToSave) {
if (userToSave != null) {
Map<String, dynamic> userData =
UserModel.fromFirebaseCurrentUser(userToSave).toJson();
locator<SharedPreferences>()
.setString(SharedPrefsKeys.kUserProfile, jsonEncode(userData));
}
}
static void setNewUnlockTime(String virtualFriendId) {
Map<String, dynamic> unlockRecords = jsonDecode(locator<SharedPreferences>()
.getString(SharedPrefsKeys.kFriendLastUnlockTime) ??
"{}");
unlockRecords[virtualFriendId] = DateTime.now().toString();
locator<SharedPreferences>().setString(
SharedPrefsKeys.kFriendLastUnlockTime, jsonEncode(unlockRecords));
}
static void increaseKpopScore() {
String? userData =
locator<SharedPreferences>().getString(SharedPrefsKeys.kUserProfile);
if (userData != null) {
UserModel userValues = UserModel.fromJson(jsonDecode(userData));
int currentScore = userValues.kpopScore ?? 0;
userValues.kpopScore = currentScore + 1;
Map<String, dynamic> updatedRecords = userValues.toJson();
locator<SharedPreferences>()
.setString(SharedPrefsKeys.kUserProfile, jsonEncode(updatedRecords));
}
}
static bool lastUnlockWasWithinAnHour(String virtualFriendId) {
Map<String, dynamic> unlockRecords = jsonDecode(locator<SharedPreferences>()
.getString(SharedPrefsKeys.kFriendLastUnlockTime) ??
"{}");
String? lastUnlock = unlockRecords[virtualFriendId];
if (lastUnlock == null) {
return false;
}
DateTime lastUnlockTime = DateTime.parse(lastUnlock);
Duration difference = DateTime.now().difference(lastUnlockTime);
debugPrint("Time difference in minutes: ${difference.inMinutes}");
return difference.inMinutes < RemoteConfigValues.chatRewardUnlockTimeInMins
? true
: false;
}
static UserModel? getUserProfile() {
String? userData =
locator<SharedPreferences>().getString(SharedPrefsKeys.kUserProfile);
if (userData == null) {
BlocProvider.of<AuthCheckerCubit>(navigatorKey.currentContext!)
.signOutUser();
return null;
}
return UserModel.fromJson(jsonDecode(userData));
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/utils/analytics.dart | import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/foundation.dart';
import 'package:kpopchat/core/utils/service_locator.dart';
import 'package:kpopchat/data/models/user_model.dart';
import 'package:mixpanel_flutter/mixpanel_flutter.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';
import 'package:uuid/uuid.dart';
Future<void> logEventInAnalytics(String eventName,
{Map<String, dynamic>? parameters}) async {
// log to firebase analytics
locator<FirebaseAnalytics>()
.logEvent(name: eventName, parameters: parameters);
// log to mixpanel
locator<Mixpanel>().track(eventName, properties: parameters);
debugPrint("Log event: $eventName");
}
Future<void> setUserIdInAnalytics(UserModel? loggedInUser) async {
if (loggedInUser != null) {
// set user id in firebase analytics
locator<FirebaseAnalytics>().setUserId(id: loggedInUser.userId);
// set user id in mixpanel
Mixpanel mp = locator<Mixpanel>();
mp.identify(loggedInUser.userId ?? const Uuid().v1());
mp.getPeople().set("\$name", loggedInUser.displayName);
mp.getPeople().set("\$email", loggedInUser.email);
mp.getPeople().set("\$avatar", loggedInUser.photoURL);
OneSignal.login(loggedInUser.userId ?? const Uuid().v1());
debugPrint("Set user id to analytics");
}
}
Future<void> setUserPropertiesInAnalytics(
String propertyKey, String propertyValue) async {
// set user properties in firebase analytics
locator<FirebaseAnalytics>()
.setUserProperty(name: propertyKey, value: propertyValue);
// set user properties in mixpanel
locator<Mixpanel>().getPeople().set("\$$propertyKey", propertyValue);
debugPrint("Set user properties, $propertyKey: $propertyValue");
}
Future<void> increasePropertyCount(
String propertyKey, double increaseBy) async {
// in mixpanel
locator<Mixpanel>().getPeople().increment(propertyKey, increaseBy);
debugPrint("Increased property count");
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/utils/schema_helper.dart | import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:kpopchat/business_logic/auth_checker_cubit/auth_checker_cubit.dart';
import 'package:kpopchat/core/constants/shared_preferences_keys.dart';
import 'package:kpopchat/core/utils/service_locator.dart';
import 'package:kpopchat/data/models/local_schema_model.dart';
import 'package:kpopchat/main.dart';
class SchemaHelper {
Future<String?> getLocalSchema() async {
String? localSchema;
try {
localSchema = await locator<FlutterSecureStorage>()
.read(key: SharedPrefsKeys.kSchemaKey);
} catch (e) {
debugPrint("debug: Catched while reading secure storage.");
BlocProvider.of<AuthCheckerCubit>(navigatorKey.currentContext!)
.signOutUser();
}
return localSchema;
}
/// To be used to save virtual friends data from network to local schema
Future<void> saveLocalSchema(
LocalSchemaModelOfLoggedInUser localSchema) async {
Map<String, dynamic> localSchemaInJson = await localSchema.toJson();
await locator<FlutterSecureStorage>().write(
key: SharedPrefsKeys.kSchemaKey, value: jsonEncode(localSchemaInJson));
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/utils/loading_utils.dart | import 'package:flutter/material.dart';
import 'package:kpopchat/main.dart';
import 'package:kpopchat/presentation/common_widgets/loading_overlay_screen.dart';
class LoadingUtils {
static showLoadingDialog() {
showGeneralDialog(
context: navigatorKey.currentContext!,
barrierDismissible: false,
pageBuilder: (_, __, ___) {
return LoadingOverlayScreen();
},
);
}
static hideLoadingDialog() {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
Navigator.of(navigatorKey.currentContext!).pop();
});
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/utils/initializer.dart | import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:kpopchat/core/constants/firebase_remote_config_keys.dart';
import 'package:kpopchat/core/constants/network_constants.dart';
import 'package:kpopchat/core/constants/remote_config_values.dart';
import 'package:kpopchat/core/utils/service_locator.dart';
/// contains diff services to initialize at beginning
class RequiredInitializations {
static void initializeFirebaseRemoteConfig() {
FirebaseRemoteConfig rc = locator<FirebaseRemoteConfig>();
rc.fetchAndActivate();
NetworkConstants.edenAIKey = rc.getString(RemoteConfigKeys.kKeyEdenAI);
RemoteConfigValues.systemMsg = rc.getString(RemoteConfigKeys.kKeySystemMsg);
RemoteConfigValues.temperature =
rc.getDouble(RemoteConfigKeys.kKeyTemperature);
RemoteConfigValues.maxTokens = rc.getInt(RemoteConfigKeys.kKeyMaxTokens);
RemoteConfigValues.maxMessagesToTake =
rc.getInt(RemoteConfigKeys.kKeyMaxMsgsToTake);
RemoteConfigValues.chatRewardUnlockTimeInMins =
rc.getInt(RemoteConfigKeys.kKeyChatRewardUnlockTimeInMins);
RemoteConfigValues.msgsToAllowAfterShowingOneAd =
rc.getInt(RemoteConfigKeys.kKeyMessagesToAllowAfterShowingOneAd);
}
static void initializeMobileAds() {
MobileAds.instance.initialize();
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/utils/service_locator.dart | import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get_it/get_it.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:kpopchat/admin_controls/admin_repo.dart';
import 'package:kpopchat/core/constants/env_keys_constants.dart';
import 'package:kpopchat/core/firebase/firebase_options.dart';
import 'package:kpopchat/core/network/client/base_client.dart';
import 'package:kpopchat/core/network/client/base_client_impl.dart';
import 'package:kpopchat/core/utils/schema_helper.dart';
import 'package:kpopchat/data/repository/auth_repo.dart';
import 'package:kpopchat/data/repository/chat_repo.dart';
import 'package:kpopchat/data/repository/data_filter_repo.dart';
import 'package:kpopchat/data/repository/real_users_repo.dart';
import 'package:kpopchat/data/repository/remote_config_repo.dart';
import 'package:kpopchat/data/repository/virtual_friends_repo.dart';
import 'package:kpopchat/data/repository_implementation/auth_repo_impl.dart';
import 'package:kpopchat/data/repository_implementation/chat_repo_impl.dart';
import 'package:kpopchat/data/repository_implementation/real_users_repo_impl.dart';
import 'package:kpopchat/data/repository_implementation/remote_config_repo_impl.dart';
import 'package:kpopchat/data/repository_implementation/virtual_friends_repo_impl.dart';
import 'package:location/location.dart';
import 'package:mixpanel_flutter/mixpanel_flutter.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
final locator = GetIt.instance;
setUpLocator() async {
Mixpanel mixpanel =
await Mixpanel.init(EnvKeys.mixpanelToken, trackAutomaticEvents: true);
mixpanel.setLoggingEnabled(true);
locator.registerSingleton<Mixpanel>(mixpanel);
if (kDebugMode) {
OneSignal.Debug.setLogLevel(OSLogLevel.verbose);
}
OneSignal.initialize(EnvKeys.oneSignalAppId);
SharedPreferences prefs = await SharedPreferences.getInstance();
FirebaseRemoteConfig rc = FirebaseRemoteConfig.instance;
locator.registerSingleton<SharedPreferences>(prefs);
locator.registerFactory(() => FirebaseAuth.instance);
locator.registerSingleton(InternetConnectionChecker());
locator.registerSingleton(FirebaseAnalytics.instance);
locator.registerSingleton(FlutterLocalNotificationsPlugin());
locator.registerFactory<FlutterSecureStorage>(
() => const FlutterSecureStorage());
locator.registerFactory<GoogleSignIn>(() => GoogleSignIn(
clientId: DefaultFirebaseOptions.currentPlatform.iosClientId));
locator.registerFactory<AuthRepo>(
() => AuthRepoImplementation(locator(), locator()));
locator.registerFactory(() => SchemaHelper());
locator.registerFactory<BaseClient>(() => BaseClientImplementation());
locator.registerFactory<ChatRepo>(
() => ChatRepoImplementation(locator(), locator()));
locator.registerFactory<FirebaseFirestore>(() => FirebaseFirestore.instance);
locator.registerFactory<VirtualFriendsRepo>(
() => VirtualFriendsRepoImplementation(locator()));
locator.registerFactory<RealUsersRepo>(() => RealUsersRepoImpl(locator()));
locator.registerSingleton<FirebaseRemoteConfig>(rc);
locator.registerFactory<RemoteConfigRepo>(
() => RemoteConfigRepoImpl(client: locator()));
locator.registerSingleton(Location());
locator.registerFactory<DataFilterRepo>(() => DataFilterRepo());
locator.registerFactory<AdminRepo>(() => AdminRepo(locator()));
// fetching values from network during service locator invokation
Future.wait([
locator<RemoteConfigRepo>().getUserInfoFromIP(),
]);
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/firebase/firebase_options.dart | // File generated by FlutterFire CLI.
// ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
import 'package:flutter/foundation.dart'
show defaultTargetPlatform, TargetPlatform;
import 'package:kpopchat/core/constants/env_keys_constants.dart';
/// Default [FirebaseOptions] for use with your Firebase apps.
///
/// Example:
/// ```dart
/// import 'firebase_options.dart';
/// // ...
/// await Firebase.initializeApp(
/// options: DefaultFirebaseOptions.currentPlatform,
/// );
/// ```
class DefaultFirebaseOptions {
static FirebaseOptions get currentPlatform {
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return android;
case TargetPlatform.iOS:
return ios;
case TargetPlatform.windows:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for windows - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.linux:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for linux - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
default:
throw UnsupportedError(
'DefaultFirebaseOptions are not supported for this platform.',
);
}
}
static const FirebaseOptions android = FirebaseOptions(
apiKey: EnvKeys.apiKeyAndroid,
appId: EnvKeys.appIdAndroid,
messagingSenderId: EnvKeys.messagingSenderId,
projectId: EnvKeys.projectId,
storageBucket: EnvKeys.storageBucket,
);
static const FirebaseOptions ios = FirebaseOptions(
apiKey: EnvKeys.apiKeyIos,
appId: EnvKeys.appIdIos,
messagingSenderId: EnvKeys.messagingSenderId,
projectId: EnvKeys.projectId,
storageBucket: EnvKeys.storageBucket,
iosClientId: EnvKeys.iosClientId,
iosBundleId: EnvKeys.bundleId,
);
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/core | mirrored_repositories/Kpop-Chat/lib/core/firebase/firebase_setup.dart | import 'dart:io';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/foundation.dart';
import 'package:kpopchat/core/constants/text_constants.dart';
import 'firebase_options.dart';
class FirebaseSetup {
//Constructor for Firebase Setup
FirebaseSetup();
//Initilalizing firebase
Future<void> initializeFirebase() async {
await Firebase.initializeApp(
name: Platform.isAndroid ? (TextConstants.appName) : null,
options: DefaultFirebaseOptions.currentPlatform);
FlutterError.onError = (errorDetails) {
FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails);
};
PlatformDispatcher.instance.onError = (error, stack) {
FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
return true;
};
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib | mirrored_repositories/Kpop-Chat/lib/business_logic/theme_cubit.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:kpopchat/core/constants/shared_preferences_keys.dart';
import 'package:kpopchat/core/utils/service_locator.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../core/themes/dark_theme.dart';
import '../core/themes/light_theme.dart';
class ThemeCubit extends Cubit<ThemeData> {
ThemeCubit() : super(lightTheme);
getTheme() async {
bool isDark =
locator<SharedPreferences>().getBool(SharedPrefsKeys.isDarkMode) ??
false;
await Future.delayed(Duration.zero);
if (isDark) {
emit(darkTheme);
changeOverlayColor(true);
} else {
emit(lightTheme);
changeOverlayColor(false);
}
}
changeTheme() async {
bool isDarkCurrently = state == darkTheme;
locator<SharedPreferences>()
.setBool(SharedPrefsKeys.isDarkMode, !isDarkCurrently);
changeOverlayColor(!isDarkCurrently);
emit(isDarkCurrently ? lightTheme : darkTheme);
}
}
changeOverlayColor(bool isDark) {
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(statusBarColor: Colors.grey));
}
| 0 |
mirrored_repositories/Kpop-Chat/lib | mirrored_repositories/Kpop-Chat/lib/business_logic/internet_checker_cubit.dart | import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
class InternetConnectivityCubit extends Cubit<bool> {
final InternetConnectionChecker connectionChecker;
late StreamSubscription<InternetConnectionStatus> _subscription;
InternetConnectivityCubit(this.connectionChecker) : super(true) {
// for now stream is not required, so below invokation is commented
// _subscribeToConnectivityChanges();
}
// for stream
// void _subscribeToConnectivityChanges() {
// _subscription = connectionChecker.onStatusChange.listen((status) {
// if (status == InternetConnectionStatus.connected) {
// emit(true);
// } else {
// emit(false);
// }
// });
// }
// method when bool value is required and not stream
Future<bool> isInternetConnected() async {
bool isConnected = await connectionChecker.hasConnection;
return isConnected;
}
@override
Future<void> close() {
_subscription.cancel();
return super.close();
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/business_logic | mirrored_repositories/Kpop-Chat/lib/business_logic/virtual_friends_list_cubit/virtual_friends_list_cubit.dart | import 'package:dartz/dartz.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:kpopchat/business_logic/virtual_friends_list_cubit/virtual_friends_list_state.dart';
import 'package:kpopchat/core/constants/text_constants.dart';
import 'package:kpopchat/core/network/failure_model.dart';
import 'package:kpopchat/data/models/local_schema_model.dart';
import 'package:kpopchat/data/models/virtual_friend_model.dart';
import 'package:kpopchat/data/repository/virtual_friends_repo.dart';
import 'package:kpopchat/main.dart';
import 'package:kpopchat/presentation/common_widgets/common_widgets.dart';
class VirtualFriendsListCubit extends Cubit<VirtualFriendsListState> {
final VirtualFriendsRepo virtualFriendsRepo;
VirtualFriendsListCubit(this.virtualFriendsRepo)
: super(VirtualFriendsInitialState());
LocalSchemaModelOfLoggedInUser? loadedSchemaOfFriends;
void resetVirtualFriendsListState() {
emit(VirtualFriendsInitialState());
}
void getVirtualFriends() async {
Either<LocalSchemaModelOfLoggedInUser, FailureModel> response =
await virtualFriendsRepo.getVirtualFriends();
response.fold((l) {
loadedSchemaOfFriends = l;
emit(VirtualFriendsLoadedState(l));
}, (r) {
emit(ErrorLoadingVirtualFriendsState(
r.message ?? TextConstants.defaultErrorMsg));
});
}
void createVirtualFriend() async {
VirtualFriendModel friendToCreate = VirtualFriendModel(
name: "Carlos Flores",
country: "Mexico",
city: "Tijuana",
displayPictureUrl:
"https://i.ibb.co/hmC6xYp/Screenshot-2023-09-09-at-12-58-09-PM.png",
profession: "Nurse",
hobbies: ["Volunteering", "German Beer", "Surfing", "Cycling", "Kpop"]);
Either<bool, FailureModel> response = await virtualFriendsRepo
.createVirtualFriend(virtualFriendInfo: friendToCreate);
response.fold((l) {
if (l) {
BlocProvider.of<VirtualFriendsListCubit>(navigatorKey.currentContext!)
.getVirtualFriends();
CommonWidgets.customFlushBar(
navigatorKey.currentContext!, "${friendToCreate.name} is added.");
}
}, (r) {
CommonWidgets.customFlushBar(navigatorKey.currentContext!,
r.message ?? TextConstants.defaultErrorMsg);
});
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/business_logic | mirrored_repositories/Kpop-Chat/lib/business_logic/virtual_friends_list_cubit/virtual_friends_list_state.dart | import 'package:kpopchat/data/models/local_schema_model.dart';
abstract class VirtualFriendsListState {}
class VirtualFriendsInitialState extends VirtualFriendsListState {}
class VirtualFriendsLoadedState extends VirtualFriendsListState {
final LocalSchemaModelOfLoggedInUser localSchemaModelOfLoggedInUser;
VirtualFriendsLoadedState(this.localSchemaModelOfLoggedInUser);
}
class ErrorLoadingVirtualFriendsState extends VirtualFriendsListState {
final String errorMsg;
ErrorLoadingVirtualFriendsState(this.errorMsg);
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/business_logic | mirrored_repositories/Kpop-Chat/lib/business_logic/auth_checker_cubit/auth_checker_cubit.dart | import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:kpopchat/business_logic/virtual_friends_list_cubit/virtual_friends_list_cubit.dart';
import 'package:kpopchat/core/routes/app_routes.dart';
import 'package:kpopchat/core/utils/service_locator.dart';
import 'package:kpopchat/core/utils/shared_preferences_helper.dart';
import 'package:kpopchat/main.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';
class AuthCheckerCubit extends Cubit<AuthStates> {
AuthCheckerCubit() : super(AuthStates.loadingState);
GoogleSignIn googleSignIn = locator<GoogleSignIn>();
FirebaseAuth firebaseAuth = locator<FirebaseAuth>();
/// Emits loggedOutState if firebase currentUser is null,
/// otherwise emits loggedInState
void checkUserAuth() async {
await Future.delayed(Duration.zero);
final User? loggedInUser = firebaseAuth.currentUser;
emit(loggedInUser != null
? AuthStates.loggedInState
: AuthStates.loggedOutState);
}
/// Sign out from google and navigate to sign in screen
void signOutUser() async {
SharedPrefsHelper.clearAll();
locator<FlutterSecureStorage>().deleteAll();
await googleSignIn.disconnect();
await googleSignIn.signOut();
await firebaseAuth.signOut();
OneSignal.logout();
emit(AuthStates.loggedOutState);
Navigator.of(navigatorKey.currentContext!)
.pushNamedAndRemoveUntil(AppRoutes.signInScreen, (route) => false);
BlocProvider.of<VirtualFriendsListCubit>(navigatorKey.currentContext!)
.resetVirtualFriendsListState();
}
}
enum AuthStates { loadingState, loggedInState, loggedOutState }
| 0 |
mirrored_repositories/Kpop-Chat/lib/business_logic | mirrored_repositories/Kpop-Chat/lib/business_logic/virtual_friends_posts_cubit/virtual_friends_posts_state.dart | import 'package:kpopchat/data/models/virtual_friend_post_model.dart';
abstract class VirtualFriendsPostsState {}
class InitialPostsState extends VirtualFriendsPostsState {}
class PostsLoadedState extends VirtualFriendsPostsState {
final List<VirtualFriendPostModel> loadedPosts;
PostsLoadedState({required this.loadedPosts});
}
class ErrorLoadingPostsState extends VirtualFriendsPostsState {
final String errorMsg;
ErrorLoadingPostsState({required this.errorMsg});
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/business_logic | mirrored_repositories/Kpop-Chat/lib/business_logic/virtual_friends_posts_cubit/virtual_friends_posts_cubit.dart | import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:kpopchat/business_logic/virtual_friends_posts_cubit/virtual_friends_posts_state.dart';
import 'package:kpopchat/core/constants/text_constants.dart';
import 'package:kpopchat/data/repository/virtual_friends_repo.dart';
class VirtualFriendsPostsCubit extends Cubit<VirtualFriendsPostsState> {
final VirtualFriendsRepo friendsRepo;
VirtualFriendsPostsCubit(this.friendsRepo) : super(InitialPostsState());
void fetchPosts() async {
emit(InitialPostsState());
final response = await friendsRepo.getVirtualFriendsPosts();
response.fold((l) {
emit(PostsLoadedState(loadedPosts: l));
}, (r) {
emit(ErrorLoadingPostsState(
errorMsg: r.message ?? TextConstants.defaultErrorMsg));
});
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/business_logic | mirrored_repositories/Kpop-Chat/lib/business_logic/chat_cubit/chat_cubit.dart | import 'package:dartz/dartz.dart';
import 'package:dash_chat_2/dash_chat_2.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:kpopchat/core/constants/remote_config_values.dart';
import 'package:kpopchat/core/constants/text_constants.dart';
import 'package:kpopchat/core/network/failure_model.dart';
import 'package:kpopchat/core/utils/service_locator.dart';
import 'package:kpopchat/core/utils/shared_preferences_helper.dart';
import 'package:kpopchat/data/models/schema_message_model.dart';
import 'package:kpopchat/data/models/schema_virtual_friend_model.dart';
import 'package:kpopchat/data/models/user_model.dart';
import 'package:kpopchat/data/models/virtual_friend_model.dart';
import 'package:kpopchat/data/repository/chat_repo.dart';
import 'package:kpopchat/data/repository/data_filter_repo.dart';
import 'package:kpopchat/main.dart';
import 'package:kpopchat/presentation/common_widgets/common_widgets.dart';
part 'chat_state.dart';
class ChatCubit extends Cubit<ChatState> {
final ChatRepo chatRepo;
ChatCubit(this.chatRepo) : super(ChatLoadingState());
UserModel? loggedInUser = SharedPrefsHelper.getUserProfile();
/// this property to be used to show interstitial ad
/// after sending three messages, we are targeting to show interstitial ad to user
/// After showing ad, need to reset this to zero, and increase by 1 evertime user sends a msg
/// again when it reaches 6, we show ad
int messagesSent = 0;
int limit = RemoteConfigValues.msgsToAllowAfterShowingOneAd;
bool shouldShowChatInterstitialAd() {
messagesSent += 1;
if (messagesSent <= limit) {
return false;
}
messagesSent = 0; // resetting
return true;
}
/// to track chat screen is open or not with any virtual friends
Map<String, bool> chatScreenOpen = {};
/// to track what logged in user is currently typing so that draft(unsent/msg in textfield) msg can be preserved back when user comes back from other screen to chat screen
Map<String, String> userMsgOnTextfield = {};
/// to track virtual friends who are typing
Map<String, bool> isVirtualFriendTyping = {};
/// to get chat history between logged in user and selected virtual friend
void loadChatHistory(VirtualFriendModel virtualFriend) async {
final Either<List<SchemaMessageModel>, FailureModel> response =
await chatRepo.getChatHistoryWithThisFriend(
virtualFriendId: virtualFriend.id!);
List<ChatMessage> chatHistoryToEmit = [];
response.fold((chatHistory) {
SchemaVirtualFriendModel schemaVirtualFriendModel =
SchemaVirtualFriendModel(
info: virtualFriend, chatHistory: chatHistory);
chatHistoryToEmit = schemaVirtualFriendModel.toListOfChatMessages();
bool friendIsTyping = isVirtualFriendTyping[virtualFriend.id] ?? false;
emit(friendIsTyping
? FriendTypingState(
chatHistory: chatHistoryToEmit,
typingUsers: [virtualFriend.toChatUser()],
virtualFriendId: virtualFriend.id!)
: ChatLoadedState(
chatHistory: chatHistoryToEmit,
virtualFriendId: virtualFriend.id!));
}, (r) {
debugPrint("error fetching chat history: ${r.message}");
emit(ChatLoadedState(
chatHistory: chatHistoryToEmit, virtualFriendId: virtualFriend.id!));
});
}
void sendNewMsgToFriend(
ChatMessage userNewMsg, VirtualFriendModel virtualFriend) async {
String virtualFriendId = virtualFriend.id!;
ChatUser chatUserFriend = virtualFriend.toChatUser();
final Either<List<SchemaMessageModel>, FailureModel> response =
await chatRepo.getChatHistoryWithThisFriend(
virtualFriendId: virtualFriendId, msgToAdd: userNewMsg);
response.fold((updatedSchemaMsgs) async {
SchemaVirtualFriendModel schemaVirtualFriendModel =
SchemaVirtualFriendModel(
info: virtualFriend, chatHistory: updatedSchemaMsgs);
List<ChatMessage> updatedChatHistory =
schemaVirtualFriendModel.toListOfChatMessages();
isVirtualFriendTyping[virtualFriendId] = true;
emit(
// isVirtualFriendTyping[virtualFriendId] ?? false
// ?
FriendTypingState(
chatHistory: updatedChatHistory,
typingUsers: [chatUserFriend],
virtualFriendId: virtualFriendId)
// :
// ChatLoadedState(
// chatHistory: updatedChatHistory,
// virtualFriendId: virtualFriendId)
);
final friendMsgResponse =
await chatRepo.getMsgFromVirtualFriend(schemaVirtualFriendModel);
friendMsgResponse.fold((friendMsg) async {
locator<DataFilterRepo>()
.filterChat(userNewMsg.text, friendMsg.message ?? "null");
final Either<List<SchemaMessageModel>, FailureModel>
msgsWithBotNewMsgResp = await chatRepo.getChatHistoryWithThisFriend(
virtualFriendId: virtualFriendId,
msgToAdd: friendMsg.toChatMessage(virtualFriend.toChatUser()));
msgsWithBotNewMsgResp.fold((msgsWithFriendNewMsg) {
SchemaVirtualFriendModel schemaVirtualFriendModel =
SchemaVirtualFriendModel(
info: virtualFriend, chatHistory: msgsWithFriendNewMsg);
List<ChatMessage> updatedChatHistoryWithBotNewMsg =
schemaVirtualFriendModel.toListOfChatMessages();
emit(ChatLoadedState(
chatHistory: updatedChatHistoryWithBotNewMsg,
virtualFriendId: virtualFriendId));
isVirtualFriendTyping[virtualFriendId] = false;
}, (r) {
debugPrint("error saving bot new msg: ${r.message}");
});
}, (r) {
isVirtualFriendTyping[virtualFriendId] = false;
CommonWidgets.customFlushBar(navigatorKey.currentContext!,
r.message ?? TextConstants.defaultErrorMsg);
debugPrint("error getting bot msg: ${r.message}");
});
}, (r) {
isVirtualFriendTyping[virtualFriendId] = false;
debugPrint("error saving user msg: ${r.message}");
});
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/business_logic | mirrored_repositories/Kpop-Chat/lib/business_logic/chat_cubit/chat_state.dart | part of 'chat_cubit.dart';
abstract class ChatState {
const ChatState();
}
class ChatLoadingState extends ChatState {
String? virtualFriendId;
ChatLoadingState({this.virtualFriendId});
}
class ErrorReceivingBotMsgState extends ChatState {
ErrorReceivingBotMsgState();
}
class ChatLoadedState extends ChatState {
List<ChatMessage> chatHistory;
String virtualFriendId;
ChatLoadedState({required this.chatHistory, required this.virtualFriendId});
}
class FriendTypingState extends ChatState {
List<ChatMessage> chatHistory;
List<ChatUser> typingUsers;
String virtualFriendId;
FriendTypingState(
{required this.chatHistory,
required this.typingUsers,
required this.virtualFriendId});
}
class ErrorState extends ChatState {}
| 0 |
mirrored_repositories/Kpop-Chat/lib/business_logic | mirrored_repositories/Kpop-Chat/lib/business_logic/real_users_cubit/real_users_cubit.dart | import 'dart:convert';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:kpopchat/business_logic/real_users_cubit/real_users_state.dart';
import 'package:kpopchat/core/constants/shared_preferences_keys.dart';
import 'package:kpopchat/core/constants/text_constants.dart';
import 'package:kpopchat/core/utils/service_locator.dart';
import 'package:kpopchat/core/utils/shared_preferences_helper.dart';
import 'package:kpopchat/data/models/user_model.dart';
import 'package:kpopchat/data/repository/real_users_repo.dart';
import 'package:shared_preferences/shared_preferences.dart';
class RealUsersCubit extends Cubit<RealUsersState> {
final RealUsersRepo realUsersRepo;
RealUsersCubit(this.realUsersRepo) : super(RealUsersInitialState());
List<UserModel> loadedRealUsers = [];
void fetchRealUsers() async {
final response = await realUsersRepo.fetchRealUsersData();
response.fold((l) {
// separate logged in user data with other real users
UserModel loggedInUserRecord = SharedPrefsHelper.getUserProfile()!;
for (UserModel realUser in l) {
if (realUser.userId != loggedInUserRecord.userId) {
loadedRealUsers.add(realUser);
} else {
locator<SharedPreferences>().setString(
SharedPrefsKeys.kUserProfile, jsonEncode(realUser.toJson()));
}
}
emit(RealUsersLoadedState(loadedRealUsers));
}, (r) {
emit(ErrorLoadingRealUsersState(
r.message ?? TextConstants.defaultErrorMsg));
});
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/business_logic | mirrored_repositories/Kpop-Chat/lib/business_logic/real_users_cubit/real_users_state.dart | import 'package:kpopchat/data/models/user_model.dart';
abstract class RealUsersState {}
class RealUsersInitialState extends RealUsersState {}
class RealUsersLoadedState extends RealUsersState {
final List<UserModel> realUsers;
RealUsersLoadedState(this.realUsers);
}
class ErrorLoadingRealUsersState extends RealUsersState {
final String errorMsg;
ErrorLoadingRealUsersState(this.errorMsg);
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation | mirrored_repositories/Kpop-Chat/lib/presentation/common_widgets/network_call_loading_widgets.dart | import 'package:flutter/material.dart';
import 'package:kpopchat/main.dart';
showLoadingDialog() {
showDialog(
barrierDismissible: false,
barrierColor: Colors.transparent,
context: navigatorKey.currentContext!,
builder: (appContext) {
return Material(
color: Colors.grey.withOpacity(0.4),
child: const SizedBox(
height: 150,
child: Center(
child: CircularProgressIndicator(),
),
),
);
},
);
}
hideLoadingDialog() {
Navigator.of(navigatorKey.currentContext!).pop();
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation | mirrored_repositories/Kpop-Chat/lib/presentation/common_widgets/common_decorations.dart | import 'package:flutter/material.dart';
import 'package:kpopchat/core/constants/color_constants.dart';
class CommonDecoration {
static LinearGradient appPrimaryGradientBackground() {
return const LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [ColorConstants.primaryColor, ColorConstants.primaryColorPink]);
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation | mirrored_repositories/Kpop-Chat/lib/presentation/common_widgets/loading_overlay_screen.dart | import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
class LoadingOverlayScreen extends StatelessWidget {
const LoadingOverlayScreen({super.key});
@override
Widget build(BuildContext context) {
return BackdropFilter(
filter: ImageFilter.blur(sigmaX: 4, sigmaY: 3),
child: SafeArea(
child: Stack(
children: [
const Center(
child: SpinKitCircle(color: Colors.black),
),
Container(
height: MediaQuery.of(context).size.height,
color: Colors.white.withOpacity(0),
),
],
),
));
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation | mirrored_repositories/Kpop-Chat/lib/presentation/common_widgets/bool_bottom_sheet.dart | // this bottom sheet to be used in places like:
// onWillPop property, post delete feature
// takes title text, yes/true button text
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kpopchat/presentation/common_widgets/custom_text.dart';
import 'common_widgets.dart';
Future<bool?> booleanBottomSheet(
{required BuildContext context,
required String titleText,
Color? bgColorOfPrimaryButton,
Color? colorOfTextInPrimaryButton,
required String boolTrueText}) {
return showModalBottomSheet<bool>(
elevation: 1,
context: context,
isScrollControlled: true,
shape: CommonWidgets.buildCircularBorderOnTop30r(),
builder: (BuildContext context) {
return Padding(
padding: EdgeInsets.all(18.sp),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
CommonWidgets.buildLineInBottomSheet(),
SizedBox(height: 8.h),
CustomText(
text: titleText,
size: 15.sp,
isBold: true,
),
SizedBox(height: 24.h),
SizedBox(
width: double.infinity,
height: 50.h,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: bgColorOfPrimaryButton),
onPressed: () {
Navigator.of(context).pop(true);
},
child: CustomText(
text: boolTrueText,
isBold: true,
textColor: colorOfTextInPrimaryButton,
),
),
),
// ),
Padding(
padding: EdgeInsets.symmetric(vertical: 18.0.h),
child: InkWell(
onTap: () => Navigator.of(context).pop(false),
child: Container(
alignment: Alignment.center,
width: double.infinity,
height: 48.h,
child: const CustomText(text: "Cancel"))),
)
],
),
);
},
);
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation | mirrored_repositories/Kpop-Chat/lib/presentation/common_widgets/common_widgets.dart | import 'package:another_flushbar/flushbar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'custom_text.dart';
class CommonWidgets {
static PreferredSize customAppBar(
BuildContext context,
Widget appBarContents,
) {
return PreferredSize(
preferredSize: Size.fromHeight(70.h),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: EdgeInsets.symmetric(horizontal: 10.w),
child: appBarContents,
),
SizedBox(height: 13.h),
Divider(
height: 2.h,
thickness: 0.5.sp,
)
],
),
);
}
static customFlushBar(BuildContext context, String message) {
Flushbar(
backgroundColor: Theme.of(context).primaryColor,
flushbarPosition: FlushbarPosition.TOP,
messageText: CustomText(
text: message,
alignCenter: true,
textColor: Theme.of(context).colorScheme.background,
),
duration: const Duration(seconds: 1),
).show(context);
}
static Widget buildBannerAd(BannerAd? bannerAd) {
return bannerAd != null
? Container(
color: Colors.transparent,
height: bannerAd.size.height.toDouble(),
width: double.infinity,
child: AdWidget(ad: bannerAd),
)
: const SizedBox();
}
static Widget buildLineInBottomSheet() =>
Center(child: Container(color: Colors.grey, width: 88.w, height: 4.h));
/// fyi: being used in bool bottomsheet, error bottomsheet
static RoundedRectangleBorder buildCircularBorderOnTop30r() {
return RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30.r),
topRight: Radius.circular(30.r),
));
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation | mirrored_repositories/Kpop-Chat/lib/presentation/common_widgets/cached_image_widget.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:kpopchat/core/constants/asset_path_constants.dart';
import 'package:kpopchat/core/constants/color_constants.dart';
class CachedImageWidget extends StatelessWidget {
const CachedImageWidget({
super.key,
required this.imageUrl,
});
final String imageUrl;
@override
Widget build(BuildContext context) {
return CachedNetworkImage(
imageUrl: imageUrl,
fit: BoxFit.cover,
placeholder: (context, url) => const LinearProgressIndicator(
color: ColorConstants.unCheckedColorLightTheme,
),
errorWidget: (context, url, error) =>
Image.asset(AssetPathConstants.kDefaultProfilePic));
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation | mirrored_repositories/Kpop-Chat/lib/presentation/common_widgets/custom_text.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
// as we need different font size of text,
//making a custom text widget to accept
//required properties from arguments
class CustomText extends StatelessWidget {
final String text;
final double size;
final bool isBold;
final bool alignCenter;
final Color? textColor;
final FontWeight? fontWeight;
const CustomText(
{super.key,
required this.text,
this.size = 16,
this.isBold = false,
this.alignCenter = false,
this.fontWeight,
this.textColor});
@override
Widget build(BuildContext context) {
return Text(
text,
textAlign: alignCenter ? TextAlign.center : null,
style: TextStyle(
fontSize: size.sp,
fontWeight:
fontWeight ?? (isBold ? FontWeight.bold : FontWeight.normal),
color: textColor),
);
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation | mirrored_repositories/Kpop-Chat/lib/presentation/common_widgets/cached_circle_avatar.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:kpopchat/core/constants/asset_path_constants.dart';
class CachedCircleAvatar extends StatelessWidget {
final String imageUrl;
final double? radius;
const CachedCircleAvatar({super.key, required this.imageUrl, this.radius});
@override
Widget build(BuildContext context) {
return CachedNetworkImage(
imageUrl: imageUrl,
imageBuilder: (context, imageProvider) {
return CircleAvatar(
backgroundColor: Colors.transparent,
backgroundImage: imageProvider,
radius: radius,
);
},
placeholder: (context, url) =>
PlaceholderForCachedCircleAvatar(radius: radius),
errorWidget: (context, url, error) {
return PlaceholderForCachedCircleAvatar(radius: radius);
},
);
}
}
class PlaceholderForCachedCircleAvatar extends StatelessWidget {
const PlaceholderForCachedCircleAvatar({
super.key,
required this.radius,
});
final double? radius;
@override
Widget build(BuildContext context) {
return CircleAvatar(
backgroundColor: Colors.transparent,
backgroundImage: const AssetImage(AssetPathConstants.kDefaultProfilePic),
radius: radius,
);
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation/widgets | mirrored_repositories/Kpop-Chat/lib/presentation/widgets/sign_in_screen_widgets/app_name_on_top_widget.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kpopchat/presentation/common_widgets/custom_text.dart';
import 'package:kpopchat/core/constants/text_constants.dart';
class AppNameOnTopOfScreen extends StatelessWidget {
const AppNameOnTopOfScreen({
super.key,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top: 70.61.h),
child: const CustomText(
text: "${TextConstants.appName}\n${TextConstants.appNameKorean}",
textColor: Colors.white,
size: 20,
isBold: true,
alignCenter: true,
));
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation/widgets | mirrored_repositories/Kpop-Chat/lib/presentation/widgets/sign_in_screen_widgets/sign_in_with_google_btn.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kpopchat/presentation/common_widgets/custom_text.dart';
import 'package:kpopchat/core/constants/asset_path_constants.dart';
import 'package:kpopchat/core/constants/color_constants.dart';
class SignInWithGoogleBtn extends StatelessWidget {
final Function() onTap;
const SignInWithGoogleBtn({super.key, required this.onTap});
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 24.w),
child: Container(
height: 56.h,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.onSecondary,
border: Border.all(color: ColorConstants.oxFFE8ECF4),
borderRadius: BorderRadius.all(Radius.circular(500.sp)),
),
child: InkWell(
onTap: onTap,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(AssetPathConstants.kGoogleLogo,
height: 22.h, width: 22.w),
SizedBox(width: 16.w),
const CustomText(
text: "Sign In with Google",
fontWeight: FontWeight.w600,
size: 14,
textColor: ColorConstants.oxFF6A707C)
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation/widgets | mirrored_repositories/Kpop-Chat/lib/presentation/widgets/sign_in_screen_widgets/spiral_lines_widget.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:kpopchat/core/constants/asset_path_constants.dart';
class SpiralLinesWidget extends StatelessWidget {
const SpiralLinesWidget({
super.key,
});
@override
Widget build(BuildContext context) {
return Positioned(
left: -40.w,
top: -310.h,
child: SvgPicture.asset(AssetPathConstants.kSpiralLines));
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation/widgets | mirrored_repositories/Kpop-Chat/lib/presentation/widgets/menu_screen_widgets/menu_list_tile.dart | import 'package:flutter/material.dart';
import 'package:kpopchat/presentation/common_widgets/custom_text.dart';
class CustomListTile extends StatelessWidget {
final String title;
final Color titleColor;
final IconData leadingIcon;
final Function() onTap;
const CustomListTile({
super.key,
required this.title,
required this.leadingIcon,
required this.onTap,
required this.titleColor,
});
@override
Widget build(BuildContext context) {
return ListTile(
title: CustomText(
text: title,
textColor: titleColor,
isBold: true,
),
leading: Icon(
leadingIcon,
color: titleColor,
),
onTap: onTap,
);
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation/widgets | mirrored_repositories/Kpop-Chat/lib/presentation/widgets/menu_screen_widgets/menu_app_bar.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kpopchat/presentation/common_widgets/custom_text.dart';
Row buildAppBarForMenuScreen(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: const Icon(CupertinoIcons.back)),
CustomText(
text: "My Profile",
size: 20.sp,
isBold: true,
textColor: Theme.of(context).primaryColor,
),
SizedBox(width: 20.w)
],
);
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation/widgets | mirrored_repositories/Kpop-Chat/lib/presentation/widgets/chat_screen_widgets/chat_screen_app_bar.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kpopchat/core/routes/app_routes.dart';
import 'package:kpopchat/data/models/virtual_friend_model.dart';
import 'package:kpopchat/presentation/common_widgets/cached_circle_avatar.dart';
import 'package:kpopchat/presentation/common_widgets/common_widgets.dart';
import 'package:kpopchat/presentation/common_widgets/custom_text.dart';
import 'package:kpopchat/presentation/widgets/chat_screen_widgets/online_status_widget.dart';
PreferredSize chatScreenAppBar(
BuildContext context, VirtualFriendModel virtualFriend) {
final String imageUrl = virtualFriend.displayPictureUrl!;
return CommonWidgets.customAppBar(
context,
Row(
children: [
IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: const Icon(CupertinoIcons.back)),
SizedBox(width: 17.w),
GestureDetector(
onTap: () {
Navigator.of(context).pushNamed(AppRoutes.friendProfileScreen,
arguments: virtualFriend);
},
child: Row(children: [
CachedCircleAvatar(imageUrl: imageUrl),
SizedBox(width: 20.w),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CustomText(
text: "${virtualFriend.name}",
isBold: true,
size: 20.sp,
textColor: Theme.of(context).primaryColor,
),
SizedBox(height: 1.h),
const OnlineStatusWidget()
],
)
]),
),
],
));
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation/widgets | mirrored_repositories/Kpop-Chat/lib/presentation/widgets/chat_screen_widgets/chat_screen_decorations.dart | // using in message inputing text field of chat screen
import 'package:dart_emoji/dart_emoji.dart';
import 'package:dash_chat_2/dash_chat_2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:intl/intl.dart';
import 'package:kpopchat/core/constants/color_constants.dart';
import 'package:kpopchat/core/constants/decoration_constants.dart';
import 'package:kpopchat/core/constants/text_constants.dart';
import 'package:kpopchat/data/models/virtual_friend_model.dart';
import 'package:kpopchat/main.dart';
import 'custom_msg_avatar_widget.dart';
// using in message inputing text field of chat screen
InputDecoration messageInputDecoration() {
return defaultInputDecoration(
fillColor: Colors.transparent,
hintStyle: TextStyle(
color: Colors.grey, fontSize: 13.sp, fontWeight: FontWeight.bold),
hintText: TextConstants.writeYourMsgHint);
}
// using in message inputing toolbar of chat screen
BoxDecoration messageInputToolbarStyle() {
return BoxDecoration(
color: Theme.of(navigatorKey.currentContext!).colorScheme.onSecondary,
borderRadius: BorderRadius.circular(30.r),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.2),
blurRadius: 4.r,
offset: const Offset(0, 2),
),
],
);
}
// box decoration of message (either send by user or by bot)
BoxDecoration messageBoxDecoration(bool isMsgOfUser, String msg) {
return defaultMessageDecoration(
color: EmojiUtil.hasOnlyEmojis(msg)
? Colors.transparent
: isMsgOfUser
? ColorConstants.primaryColor
: Theme.of(navigatorKey.currentContext!).colorScheme.onTertiary,
borderTopLeft: DecorationConstants.borderRadiusOfBubbleMsg,
borderTopRight:
isMsgOfUser ? 0 : DecorationConstants.borderRadiusOfBubbleMsg,
borderBottomLeft:
isMsgOfUser ? DecorationConstants.borderRadiusOfBubbleMsg : 0,
borderBottomRight: DecorationConstants.borderRadiusOfBubbleMsg,
);
}
// used to customize message style and message box decoration
MessageOptions chatbotMessageOptionsBuilder(
BuildContext context, VirtualFriendModel virtualFriend, ChatUser user) {
return MessageOptions(
messagePadding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
marginSameAuthor: EdgeInsets.only(top: 8.h),
marginDifferentAuthor: EdgeInsets.only(top: 35.h),
avatarBuilder: (chatUser, onPressAvatar, onLongPressAvatar) {
return CustomMsgAvatarWidget(
context: context, virtualFriend: virtualFriend);
// return DefaultAvatar(
// user: widget.bot,
// size: 30.r,
// fallbackImage: AssetImage(ImagePaths.defaultDP),
// onPressAvatar: (chatUser) {
// Navigator.pushNamed(context, AppRoutes.botProfileScreen,
// arguments: BotProfileScreenModel(
// schemaBotModel: widget.schemaBotModel,
// isChoosingBot: false));
// },
// );
},
showTime: true,
timeFormat: DateFormat.jm(),
// FYI: textColor is color of text of other users in chat bubble
// if messageTextBuilder property is commented, below two properites to be used
textColor: Theme.of(context).colorScheme.primaryContainer,
currentUserTextColor: Colors.white,
// messageTextBuilder: (message, previousMessage, nextMessage) {
// bool isMsgOfUser = message.user.id == widget.user.id;
// return Text(
// message.text,
// style: messageStyle(isMsgOfUser, message.text),
// );
// },
messageDecorationBuilder: (message, previousMessage, nextMessage) {
bool isMsgOfUser = message.user.id == user.id;
return messageBoxDecoration(isMsgOfUser, message.text);
},
);
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation/widgets | mirrored_repositories/Kpop-Chat/lib/presentation/widgets/chat_screen_widgets/online_status_widget.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kpopchat/core/constants/color_constants.dart';
class OnlineStatusWidget extends StatelessWidget {
const OnlineStatusWidget({super.key});
@override
Widget build(BuildContext context) {
Color onlineStatusColor = ColorConstants.successColor;
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircleAvatar(
backgroundColor: onlineStatusColor,
radius: 5.r,
),
SizedBox(width: 4.r),
Text(
"Online",
style: TextStyle(
fontSize: 17.sp,
color: onlineStatusColor,
),
)
],
);
}
}
class RecentlyActiveWidget extends StatelessWidget {
const RecentlyActiveWidget({super.key});
@override
Widget build(BuildContext context) {
Color onlineStatusColor = ColorConstants.primaryColor;
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircleAvatar(
backgroundColor: onlineStatusColor,
radius: 5.r,
),
SizedBox(width: 4.r),
Text(
"Recently Joined",
style: TextStyle(
fontSize: 17.sp,
color: onlineStatusColor,
),
)
],
);
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation/widgets | mirrored_repositories/Kpop-Chat/lib/presentation/widgets/chat_screen_widgets/custom_msg_avatar_widget.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kpopchat/core/routes/app_routes.dart';
import 'package:kpopchat/data/models/virtual_friend_model.dart';
import 'package:kpopchat/presentation/common_widgets/cached_circle_avatar.dart';
class CustomMsgAvatarWidget extends StatelessWidget {
const CustomMsgAvatarWidget({
super.key,
required this.context,
required this.virtualFriend,
});
final BuildContext context;
final VirtualFriendModel virtualFriend;
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(left: 10.w, right: 8.w),
child: GestureDetector(
onTap: () {
Navigator.pushNamed(context, AppRoutes.friendProfileScreen,
arguments: virtualFriend);
},
child: CachedCircleAvatar(
radius: 15.r, imageUrl: virtualFriend.displayPictureUrl ?? ""),
),
);
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation/widgets | mirrored_repositories/Kpop-Chat/lib/presentation/widgets/virtual_friends_list_screen_widgets/zero_virtual_friends_widget.dart | import 'package:flutter/material.dart';
import 'package:kpopchat/presentation/common_widgets/custom_text.dart';
class ZeroVirtualFriendsWidget extends StatelessWidget {
const ZeroVirtualFriendsWidget({
super.key,
});
@override
Widget build(BuildContext context) {
return const Center(
child: CustomText(
text: "No any virtual friends at the moment",
isBold: true,
));
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation/widgets | mirrored_repositories/Kpop-Chat/lib/presentation/widgets/virtual_friends_list_screen_widgets/app_bar.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kpopchat/core/constants/analytics_constants.dart';
import 'package:kpopchat/core/constants/text_constants.dart';
import 'package:kpopchat/core/routes/app_routes.dart';
import 'package:kpopchat/core/utils/analytics.dart';
import 'package:kpopchat/presentation/common_widgets/common_widgets.dart';
import 'package:kpopchat/presentation/common_widgets/custom_text.dart';
PreferredSize conversationsScreenAppBar(BuildContext context,
{bool isForPostsScreen = false}) {
return CommonWidgets.customAppBar(
context,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CustomText(
text: isForPostsScreen
? "@Kpop Posts"
: "@" + TextConstants.appName,
textColor: Theme.of(context).primaryColor,
size: 20.sp,
isBold: true),
buildMenuButton(context),
// IconButton(
// onPressed: () {
// // BlocProvider.of<VirtualFriendsListCubit>(context)
// // .createVirtualFriend();
// },
// icon: const Icon(Icons.create))
],
),
),
);
}
IconButton buildMenuButton(BuildContext context) {
return IconButton(
onPressed: () {
logEventInAnalytics(AnalyticsConstants.kEventMenuScreenClicked);
Navigator.pushNamed(context, AppRoutes.menuScreen);
},
icon: Icon(
Icons.menu,
size: 25.sp,
));
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation | mirrored_repositories/Kpop-Chat/lib/presentation/screens/sign_in_screen.dart | import 'dart:io';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kpopchat/core/constants/analytics_constants.dart';
import 'package:kpopchat/core/utils/analytics.dart';
import 'package:kpopchat/presentation/common_widgets/common_decorations.dart';
import 'package:kpopchat/presentation/common_widgets/common_widgets.dart';
import 'package:kpopchat/presentation/common_widgets/custom_text.dart';
import 'package:kpopchat/core/constants/asset_path_constants.dart';
import 'package:kpopchat/core/constants/color_constants.dart';
import 'package:kpopchat/core/constants/network_constants.dart';
import 'package:kpopchat/core/routes/app_routes.dart';
import 'package:kpopchat/core/utils/service_locator.dart';
import 'package:kpopchat/main.dart';
import 'package:kpopchat/presentation/widgets/sign_in_screen_widgets/sign_in_with_google_btn.dart';
import 'package:kpopchat/data/repository/auth_repo.dart';
import 'package:url_launcher/url_launcher.dart';
import '../widgets/sign_in_screen_widgets/app_name_on_top_widget.dart';
import '../widgets/sign_in_screen_widgets/spiral_lines_widget.dart';
class SignInScreen extends StatefulWidget {
const SignInScreen({super.key});
@override
State<SignInScreen> createState() => _SignInScreenState();
}
class _SignInScreenState extends State<SignInScreen> {
// bool isLoading = false;
TapGestureRecognizer? _policyRecognizer;
@override
void initState() {
_policyRecognizer = TapGestureRecognizer()
..onTap = () {
logEventInAnalytics(AnalyticsConstants.kEventPolicyClicked);
_launchUrl(NetworkConstants.policyUrl);
};
super.initState();
}
Future<void> _launchUrl(url) async {
if (!await launchUrl(Uri.parse(url))) {
throw 'Could not launch $url';
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
gradient: CommonDecoration.appPrimaryGradientBackground()),
child: buildSignInOverallWidget(),
),
);
}
Widget buildSignInOverallWidget() {
return Center(
child: Column(children: [
const AppNameOnTopOfScreen(),
const Spacer(),
Stack(clipBehavior: Clip.none, alignment: Alignment.topLeft, children: [
const SpiralLinesWidget(),
Positioned(
top: -310.h,
left: 80.w,
child: CircleAvatar(
radius: 110.r,
backgroundImage: const AssetImage(AssetPathConstants.kLogoIcon),
),
),
Container(
width: double.infinity,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.onSecondary.withOpacity(0.8),
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30.r),
topRight: Radius.circular(30.r),
),
),
child: Column(
children: [
Padding(
padding: EdgeInsets.only(top: 18.h),
child: CommonWidgets.buildLineInBottomSheet(),
),
const WelcomeText(),
const PleaseLoginText(),
SignInWithGoogleBtn(onTap: () async {
logEventInAnalytics(AnalyticsConstants.kEventSignInClick);
if (await locator<AuthRepo>().signInWithGoogle()) {
// sign in success
logEventInAnalytics(AnalyticsConstants.kEventSignedIn);
Navigator.of(navigatorKey.currentContext!)
.pushNamedAndRemoveUntil(
AppRoutes.dashboardScreen, (route) => false);
}
}),
PolicyWidget(policyRecognizer: _policyRecognizer),
],
),
),
Positioned(
top: -140,
child: Image.asset(
AssetPathConstants.kWaitingGirlGIF,
width: 200,
),
),
// Positioned(
// top: -120,
// left: 200,
// child: Image.asset(
// AssetPathConstants.kWaitingDogGIF,
// width: 180,
// ),
// ),
])
]),
);
}
}
class PolicyWidget extends StatelessWidget {
const PolicyWidget({
super.key,
required TapGestureRecognizer? policyRecognizer,
}) : _policyRecognizer = policyRecognizer;
final TapGestureRecognizer? _policyRecognizer;
@override
Widget build(BuildContext context) {
return Padding(
padding:
EdgeInsets.only(top: 31.h, bottom: Platform.isAndroid ? 24.h : 35.h),
child: Text.rich(TextSpan(
style: TextStyle(
fontSize: 16.sp, height: 1.44, fontWeight: FontWeight.w400),
text: "By signing in, I agree to the ",
children: [
TextSpan(
text: 'TOS & Privacy Policy',
recognizer: _policyRecognizer,
style: const TextStyle(
height: 1.44,
fontFamily: 'Barlow',
fontWeight: FontWeight.bold,
color: ColorConstants.primaryColor))
])),
);
}
}
class PleaseLoginText extends StatelessWidget {
const PleaseLoginText({
super.key,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top: 7.h, bottom: 31.h),
child: const CustomText(
text: "Welcome to the ultimate K-pop fan haven!",
size: 16,
textColor: ColorConstants.oxFF545454,
),
);
}
}
class WelcomeText extends StatelessWidget {
const WelcomeText({
super.key,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top: 35.h),
child: const CustomText(
text: "Yayyy!!",
isBold: true,
size: 35,
textColor: ColorConstants.oxFF545454,
),
);
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation | mirrored_repositories/Kpop-Chat/lib/presentation/screens/virtual_friend_profile_screen.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:kpopchat/core/constants/color_constants.dart';
import 'package:kpopchat/core/constants/google_ads_id.dart';
import 'package:kpopchat/core/utils/admob_services.dart';
import 'package:kpopchat/data/models/virtual_friend_model.dart';
import 'package:kpopchat/presentation/common_widgets/cached_image_widget.dart';
import 'package:kpopchat/presentation/common_widgets/custom_text.dart';
import 'package:simple_tags/simple_tags.dart';
class VirtualFriendProfileScreen extends StatefulWidget {
final VirtualFriendModel friendInfo;
const VirtualFriendProfileScreen({super.key, required this.friendInfo});
@override
State<VirtualFriendProfileScreen> createState() =>
_VirtualFriendProfileScreenState();
}
class _VirtualFriendProfileScreenState
extends State<VirtualFriendProfileScreen> {
// ValueNotifier<BannerAd?> friendProfileScreenBannerAd =
// ValueNotifier<BannerAd?>(null);
ValueNotifier<InterstitialAd?> friendProfileInterstitialAd =
ValueNotifier<InterstitialAd?>(null);
bool interstitialAdShown = false;
@override
void initState() {
_loadInterstitialAd();
super.initState();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// _loadBannerAd();
}
void _showInterstitialAd() async {
await AdMobServices.showInterstitialAd(friendProfileInterstitialAd, () {
_loadInterstitialAd();
});
}
void _loadInterstitialAd() {
InterstitialAd.load(
adUnitId: GoogleAdId.friendProfileScreenInterstitialAdId,
request: const AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (ad) {
friendProfileInterstitialAd.value = ad;
if (!interstitialAdShown) {
_showInterstitialAd();
}
interstitialAdShown = true;
},
onAdFailedToLoad: (LoadAdError error) =>
friendProfileInterstitialAd.value = null));
}
// void _loadBannerAd() async {
// friendProfileScreenBannerAd.value = await AdMobServices
// .getBannerAdByGivingAdId(GoogleAdId.friendProfileScreenBannerAdId)
// ..load();
// }
@override
void dispose() {
// friendProfileScreenBannerAd.value?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
List<String> hobbies =
widget.friendInfo.hobbies!.map((e) => e.toString()).toList();
return Scaffold(
// floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
// floatingActionButton: ValueListenableBuilder(
// valueListenable: friendProfileScreenBannerAd,
// builder: (context, value, child) {
// return CommonWidgets.buildBannerAd(value);
// },
// ),
body: ListView(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Stack(
clipBehavior: Clip.none,
alignment: Alignment.bottomRight,
children: [
Material(
elevation: 1,
child: Container(
width: double.infinity,
height: MediaQuery.of(context).size.height * 0.6,
decoration: BoxDecoration(),
child: ClipRRect(
child: CachedImageWidget(
imageUrl:
widget.friendInfo.displayPictureUrl ?? "")),
),
),
Positioned(
right: 15,
bottom: -25,
child: InkWell(
onTap: () => Navigator.of(context).pop(),
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Theme.of(context).primaryColor),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Icon(
CupertinoIcons.down_arrow,
size: 30,
color: Theme.of(context).colorScheme.background,
),
)),
),
)
],
),
SizedBox(height: 20.h),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20.w),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(
children: [
Row(
children: [
Padding(
padding: EdgeInsets.only(top: 7.h),
child: CircleAvatar(
backgroundColor: ColorConstants.successColor,
radius: 9.r,
),
),
SizedBox(width: 8.w),
Expanded(
child: CustomText(
text:
"${widget.friendInfo.name}, ${widget.friendInfo.age}",
textColor: Theme.of(context).primaryColor,
isBold: true,
size: 30.sp,
),
),
],
),
SizedBox(height: 8.h),
],
),
SizedBox(height: 15.h),
Row(
children: [
Icon(Icons.home, size: 20.sp),
SizedBox(width: 7.w),
CustomText(
text:
"Lives in ${widget.friendInfo.city}, ${widget.friendInfo.country}",
size: 16.sp,
),
],
),
SizedBox(height: 20.h),
CustomText(
text: "Likes",
size: 18.sp,
isBold: true,
textColor: Theme.of(context).primaryColor,
),
SizedBox(height: 10.h),
SimpleTags(
content: hobbies,
wrapSpacing: 8,
wrapRunSpacing: 8,
tagTextStyle: TextStyle(
fontSize: 12.sp,
),
tagContainerPadding: const EdgeInsets.all(8),
tagContainerDecoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: const BorderRadius.all(
Radius.circular(20),
),
),
)
],
),
)
],
),
],
),
);
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation | mirrored_repositories/Kpop-Chat/lib/presentation/screens/auth_checker_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:kpopchat/core/routes/app_routes.dart';
import 'package:kpopchat/business_logic/auth_checker_cubit/auth_checker_cubit.dart';
class AuthCheckerScreen extends StatelessWidget {
const AuthCheckerScreen({super.key});
@override
Widget build(BuildContext context) {
BlocProvider.of<AuthCheckerCubit>(context).checkUserAuth();
return BlocListener<AuthCheckerCubit, AuthStates>(
listener: (context, state) {
if (state == AuthStates.loggedInState) {
Navigator.of(context).pushNamedAndRemoveUntil(
AppRoutes.dashboardScreen, (route) => false);
} else if (state == AuthStates.loggedOutState) {
Navigator.of(context).pushNamedAndRemoveUntil(
AppRoutes.signInScreen, (route) => false);
}
},
child: const Material(
child: Center(child: CircularProgressIndicator()),
));
}
}
| 0 |
mirrored_repositories/Kpop-Chat/lib/presentation | mirrored_repositories/Kpop-Chat/lib/presentation/screens/menu_screen.dart | import 'package:avatar_glow/avatar_glow.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:kpopchat/business_logic/auth_checker_cubit/auth_checker_cubit.dart';
import 'package:kpopchat/business_logic/theme_cubit.dart';
import 'package:kpopchat/core/constants/analytics_constants.dart';
import 'package:kpopchat/core/constants/asset_path_constants.dart';
import 'package:kpopchat/core/constants/color_constants.dart';
import 'package:kpopchat/core/constants/google_ads_id.dart';
import 'package:kpopchat/core/constants/network_constants.dart';
import 'package:kpopchat/core/constants/text_constants.dart';
import 'package:kpopchat/core/themes/dark_theme.dart';
import 'package:kpopchat/core/utils/admob_services.dart';
import 'package:kpopchat/core/utils/analytics.dart';
import 'package:kpopchat/core/utils/shared_preferences_helper.dart';
import 'package:kpopchat/data/models/user_model.dart';
import 'package:kpopchat/main.dart';
import 'package:kpopchat/presentation/common_widgets/bool_bottom_sheet.dart';
import 'package:kpopchat/presentation/common_widgets/common_widgets.dart';
import 'package:kpopchat/presentation/common_widgets/custom_text.dart';
import 'package:kpopchat/presentation/widgets/menu_screen_widgets/menu_app_bar.dart';
import 'package:kpopchat/presentation/widgets/menu_screen_widgets/menu_list_tile.dart';
import 'package:url_launcher/url_launcher.dart';
class MenuScreen extends StatefulWidget {
const MenuScreen({super.key});
@override
State<MenuScreen> createState() => _MenuScreenState();
}
class _MenuScreenState extends State<MenuScreen> {
// ValueNotifier<BannerAd?> menuScreenBannerAd = ValueNotifier<BannerAd?>(null);
ValueNotifier<InterstitialAd?> switchThemeInterstitialAd =
ValueNotifier<InterstitialAd?>(null);
@override
void didChangeDependencies() {
super.didChangeDependencies();
// _loadBannerAd();
_loadInterstitialAd();
}
void _loadInterstitialAd() {
InterstitialAd.load(
adUnitId: GoogleAdId.switchThemeInterstitialAdId,
request: const AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (ad) => switchThemeInterstitialAd.value = ad,
onAdFailedToLoad: (LoadAdError error) =>
switchThemeInterstitialAd.value = null));
}
// void _loadBannerAd() async {
// menuScreenBannerAd.value = await AdMobServices.getBannerAdByGivingAdId(
// GoogleAdId.menuScreenBannerAdId)
// ..load();
// }
@override
void dispose() {
// menuScreenBannerAd.value?.dispose();
switchThemeInterstitialAd.value?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
UserModel? loggedInUserData = SharedPrefsHelper.getUserProfile();
return Scaffold(
appBar: CommonWidgets.customAppBar(
context, buildAppBarForMenuScreen(context)),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
// floatingActionButton: ValueListenableBuilder(
// valueListenable: menuScreenBannerAd,
// builder: (context, value, child) {
// return CommonWidgets.buildBannerAd(value);
// },
// ),
body: Padding(
padding: EdgeInsets.symmetric(horizontal: 5.w),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 10),
_buildUserDPNameEmailWidget(loggedInUserData, context),
const Divider(),
_buildScoreWidget(loggedInUserData, context),
const Divider(),
ListTile(
leading: const Icon(Icons.color_lens_outlined),
title: CustomText(
text: "Dark Mode",
isBold: true,
textColor: Theme.of(context).primaryColor,
),
trailing: BlocBuilder<ThemeCubit, ThemeData>(
builder: (context, currentTheme) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 10.h),
child: CupertinoSwitch(
activeColor: ColorConstants.primaryColor,
value: currentTheme == darkTheme,
onChanged: (bool val) async {
await AdMobServices.showInterstitialAd(
switchThemeInterstitialAd,
() => _loadInterstitialAd());
BlocProvider.of<ThemeCubit>(
navigatorKey.currentContext!)
.changeTheme();
}));
},
),
),
const Divider(),
CustomListTile(
title: "TOS & Privacy Policy",
leadingIcon: CupertinoIcons.book,
titleColor: Theme.of(context).primaryColor,
onTap: () async {
if (!await launchUrl(Uri.parse(NetworkConstants.policyUrl))) {
throw 'Could not launch TOS & policy url';
}
},
),
const Divider(),
CustomListTile(
title: "Sign out",
leadingIcon: Icons.logout,
titleColor: Theme.of(context).primaryColor,
onTap: () async {
await logoutUser(context);
},
),
const Divider(),
],
),
),
);
}
Row _buildUserDPNameEmailWidget(
UserModel? loggedInUserData, BuildContext context) {
return Row(
children: [
AvatarGlow(
shape: BoxShape.rectangle,
glowColor: ColorConstants.primaryColor,
endRadius: 50,
child: Material(
elevation: 3,
child: Container(
decoration: BoxDecoration(
border: Border.all(width: 5, color: Colors.grey[300]!)),
width: 80,
height: 80,
child: CachedNetworkImage(imageUrl: loggedInUserData!.photoURL!),
),
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CustomText(
text: "${loggedInUserData.displayName}",
isBold: true,
size: 18,
textColor: Theme.of(context).primaryColor,
),
SizedBox(height: 10),
CustomText(
text: "${loggedInUserData.email}",
textColor: Colors.grey,
),
],
)
],
);
}
Row _buildScoreWidget(UserModel? loggedInUserData, BuildContext context) {
return Row(
children: [
AvatarGlow(
shape: BoxShape.rectangle,
glowColor: ColorConstants.primaryColor,
endRadius: 50,
child: Material(
elevation: 3,
child: Container(
decoration: BoxDecoration(
border: Border.all(width: 5, color: Colors.grey[300]!)),
width: 80,
height: 80,
child: Image.asset(AssetPathConstants.kMedalPNG),
),
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CustomText(
text: "My Kpop Score",
isBold: true,
size: 18,
textColor: Theme.of(context).primaryColor,
),
SizedBox(height: 10),
CustomText(
text: "${loggedInUserData?.kpopScore ?? 0}",
textColor: Colors.grey,
),
],
)
],
);
}
Future<void> logoutUser(BuildContext context) async {
bool shouldLogout = await booleanBottomSheet(
context: context,
titleText: TextConstants.logoutTitle,
boolTrueText: TextConstants.logoutText) ??
false;
if (shouldLogout) {
logEventInAnalytics(AnalyticsConstants.kEventSignOut);
BlocProvider.of<AuthCheckerCubit>(navigatorKey.currentContext!)
.signOutUser();
}
}
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.