repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/Stay-safe-from-Corono-Virus
mirrored_repositories/Stay-safe-from-Corono-Virus/lib/home.dart
import 'package:covd_19/Http/allResultJson.dart'; import 'package:covd_19/Http/allCountry.dart'; import 'package:covd_19/Http/http.dart'; import 'package:flutter/material.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'Constant/styles.dart'; import 'package:intl/intl.dart'; import 'package:expandable/expandable.dart'; class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { Future<AllResult> _allResult; Future<List<AllCountry>> _allCountryDart; Future<List> data; String searchingFilter; DateFormat dateFormat = DateFormat("yyyy-MM-ddTHH:mm:ss"); TextEditingController _searchingCountriesController = new TextEditingController(); @override void initState() { super.initState(); _allResult = HTTP().allResult(); data = HTTP().allCountry(); _allCountryDart = HTTP().allCountry(); } @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Container( height: double.infinity, child: FutureBuilder<AllResult>( future: _allResult, builder: (context,snapshot){ if(snapshot.hasData){ var date = new DateTime.fromMillisecondsSinceEpoch(snapshot.data.updated * 1000); // DateTime date = dateFormat.parse(convert.toUtc().toIso8601String()); print(date); return SingleChildScrollView( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: Card( elevation: 5, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)), child: Container( width: MediaQuery.of(context).size.width, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), gradient: Styles.linearGradient, ), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: TextFormField( controller: _searchingCountriesController, cursorColor: Colors.white, decoration: InputDecoration( labelText: "Search country", hintStyle: new TextStyle( color: Colors.white ), labelStyle: new TextStyle( color: Colors.white ), icon: Icon( Icons.search, color: Colors.white ), border: InputBorder.none ), style: TextStyle(color: Colors.white), onTap: (){ setState(() { _searchingCountriesController.addListener((){ setState(() { searchingFilter = _searchingCountriesController.text; }); }); }); }, ), ), ), ), ), Text("All over the world",style: TextStyle(fontSize:20,color: Colors.black54,fontWeight: FontWeight.bold),), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ cardView("Active Cases",snapshot.data.cases.toString()), cardView("Deaths",snapshot.data.deaths.toString()), ], ), cardView("Recovered",snapshot.data.recovered.toString()), Padding( padding: const EdgeInsets.all(8.0), child: Text("Affected Countries",style: TextStyle(fontSize:20,color: Colors.black54,fontWeight: FontWeight.bold),), ), Container( height: MediaQuery.of(context).size.height/2, child: FutureBuilder<List<AllCountry>>( future: _allCountryDart, builder: (context,snapshot){ if(snapshot.hasData){ return ListView.builder( itemCount: snapshot.data.length, itemBuilder: (context,index){ return searchingFilter == null || searchingFilter == "" ? ExpandablePanel( header: Padding( padding: const EdgeInsets.only(left: 25.0,top: 10.0), child: Text(snapshot.data[index].country ,style: TextStyle(fontSize:20,color: Colors.black54,fontWeight: FontWeight.bold), overflow: TextOverflow.ellipsis,), ), tapHeaderToExpand: true, tapBodyToCollapse:true, hasIcon: true, iconColor: Colors.grey, expanded: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Padding( padding: const EdgeInsets.only(top: 5.0,left: 25.0,bottom: 5.0), child: Align( alignment: Alignment.centerLeft, child: Container( width: MediaQuery.of(context).size.width/2, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new Text('Cases:',style:TextStyle(color: Colors.grey)), new Text('Today Cases:',style:TextStyle(color: Colors.grey)), new Text('Deaths:',style:TextStyle(color: Colors.grey)), new Text('Recovered:',style:TextStyle(color: Colors.grey)), new Text('Active:',style:TextStyle(color: Colors.grey)), new Text('Case per One Million: ',style:TextStyle(color: Colors.grey)), new Text('Deaths per One Million: ',style:TextStyle(color: Colors.grey)), ], ), ), ), ), Padding( padding: const EdgeInsets.only(top: 5.0,bottom: 5.0,right: 15), child: Align( alignment: Alignment.center, child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new Text(snapshot.data[index].cases.toString(),style:TextStyle(color: Colors.grey)), new Text(snapshot.data[index].todayCases.toString(),style:TextStyle(color: Colors.grey)), new Text(snapshot.data[index].deaths.toString(),style:TextStyle(color: Colors.grey)), new Text(snapshot.data[index].recovered.toString(),style:TextStyle(color: Colors.grey)), new Text(snapshot.data[index].active.toString(),style:TextStyle(color: Colors.grey)), new Text(snapshot.data[index].casesPerOneMillion.toString(),style:TextStyle(color: Colors.grey)), new Text(snapshot.data[index].deathsPerOneMillion.toString(),style:TextStyle(color: Colors.grey)), ], ), ), ), ), ], ), ) :snapshot.data[index].country.toLowerCase().contains(searchingFilter.toLowerCase())? ExpandablePanel( header:Padding( padding: const EdgeInsets.only(left: 25.0,top: 10.0), child: Text(snapshot.data[index].country ,style: TextStyle(fontSize:20,color: Colors.black54,fontWeight: FontWeight.bold), overflow: TextOverflow.ellipsis,), ), tapHeaderToExpand: true, hasIcon: true, iconColor: Colors.grey, expanded: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Padding( padding: const EdgeInsets.only(top: 5.0,left: 25.0,bottom: 5.0), child: Align( alignment: Alignment.centerLeft, child: Container( width: MediaQuery.of(context).size.width/2, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new Text('Cases:',style:TextStyle(color: Colors.grey)), new Text('Today Cases:',style:TextStyle(color: Colors.grey)), new Text('Deaths:',style:TextStyle(color: Colors.grey)), new Text('Recovered:',style:TextStyle(color: Colors.grey)), new Text('Active:',style:TextStyle(color: Colors.grey)), new Text('Case per One Million: ',style:TextStyle(color: Colors.grey)), new Text('Deaths per One Million: ',style:TextStyle(color: Colors.grey)), ], ), ), ), ), Padding( padding: const EdgeInsets.only(top: 5.0,bottom: 5.0,right: 15), child: Align( alignment: Alignment.center, child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new Text(snapshot.data[index].cases.toString(),style:TextStyle(color: Colors.grey)), new Text(snapshot.data[index].todayCases.toString(),style:TextStyle(color: Colors.grey)), new Text(snapshot.data[index].deaths.toString(),style:TextStyle(color: Colors.grey)), new Text(snapshot.data[index].recovered.toString(),style:TextStyle(color: Colors.grey)), new Text(snapshot.data[index].active.toString(),style:TextStyle(color: Colors.grey)), new Text(snapshot.data[index].casesPerOneMillion.toString(),style:TextStyle(color: Colors.grey)), new Text(snapshot.data[index].deathsPerOneMillion.toString(),style:TextStyle(color: Colors.grey)), ], ), ), ), ), ], ), ) : Container(); }); }else{ return Center( child: SpinKitSquareCircle( color: Colors.red, size: 20.0, ), ); } }), ), ], ), ), ); }else{ return Center( child: SpinKitSquareCircle( color: Colors.red, size: 50.0, ) ); } }, ), ), ), ); } Widget cardView(String title,String content){ return Card( elevation: 5, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)), child: Container( width: MediaQuery.of(context).size.width/2.5, decoration: new BoxDecoration( border: new Border( bottom: new BorderSide(color: Colors.red,width: 2.0, style: BorderStyle.solid), ), ), child: Padding( padding: const EdgeInsets.all(8.0), child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.center, children:<Widget>[ Text(title,style: TextStyle(fontSize:15,color: Colors.black54,fontWeight: FontWeight.bold),), Padding( padding: const EdgeInsets.all(15.0), child: Text(content,style: TextStyle(fontSize:15,color: Colors.black54,fontWeight: FontWeight.bold),), ), ] ), ), ), ); } }
0
mirrored_repositories/Stay-safe-from-Corono-Virus/lib
mirrored_repositories/Stay-safe-from-Corono-Virus/lib/Constant/routes.dart
class Routes{ static String home = "Home"; }
0
mirrored_repositories/Stay-safe-from-Corono-Virus/lib
mirrored_repositories/Stay-safe-from-Corono-Virus/lib/Constant/styles.dart
import 'package:flutter/material.dart'; class Styles{ static const linearGradient = LinearGradient( colors: [ const Color(0xFFc90300), const Color(0xFFf50000), ], begin: const FractionalOffset(0.0, 0.0), end: const FractionalOffset(1.0, 0.1), stops: [0.0, 1.0], tileMode: TileMode.clamp); }
0
mirrored_repositories/Stay-safe-from-Corono-Virus/lib
mirrored_repositories/Stay-safe-from-Corono-Virus/lib/Constant/httpConstant.dart
class HTTPCONSTANT{ static String base = "https://corona.lmao.ninja/"; static String all = "all"; static String country = "countries"; }
0
mirrored_repositories/Stay-safe-from-Corono-Virus/lib
mirrored_repositories/Stay-safe-from-Corono-Virus/lib/Http/allCountry.dart
// To parse this JSON data, do // // final allCountry = allCountryFromJson(jsonString); import 'dart:convert'; List<AllCountry> allCountryFromJson(String str) => List<AllCountry>.from(json.decode(str).map((x) => AllCountry.fromJson(x))); String allCountryToJson(List<AllCountry> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson()))); class AllCountry { String country; CountryInfo countryInfo; int cases; int todayCases; int deaths; int todayDeaths; int recovered; int active; int critical; double casesPerOneMillion; double deathsPerOneMillion; AllCountry({ this.country, this.countryInfo, this.cases, this.todayCases, this.deaths, this.todayDeaths, this.recovered, this.active, this.critical, this.casesPerOneMillion, this.deathsPerOneMillion, }); factory AllCountry.fromJson(Map<String, dynamic> json) => AllCountry( country: json["country"] == null ? null : json["country"], countryInfo: json["countryInfo"] == null ? null : CountryInfo.fromJson(json["countryInfo"]), cases: json["cases"] == null ? null : json["cases"], todayCases: json["todayCases"] == null ? null : json["todayCases"], deaths: json["deaths"] == null ? null : json["deaths"], todayDeaths: json["todayDeaths"] == null ? null : json["todayDeaths"], recovered: json["recovered"] == null ? null : json["recovered"], active: json["active"] == null ? null : json["active"], critical: json["critical"] == null ? null : json["critical"], casesPerOneMillion: json["casesPerOneMillion"] == null ? null : json["casesPerOneMillion"].toDouble(), deathsPerOneMillion: json["deathsPerOneMillion"] == null ? null : json["deathsPerOneMillion"].toDouble(), ); Map<String, dynamic> toJson() => { "country": country == null ? null : country, "countryInfo": countryInfo == null ? null : countryInfo.toJson(), "cases": cases == null ? null : cases, "todayCases": todayCases == null ? null : todayCases, "deaths": deaths == null ? null : deaths, "todayDeaths": todayDeaths == null ? null : todayDeaths, "recovered": recovered == null ? null : recovered, "active": active == null ? null : active, "critical": critical == null ? null : critical, "casesPerOneMillion": casesPerOneMillion == null ? null : casesPerOneMillion, "deathsPerOneMillion": deathsPerOneMillion == null ? null : deathsPerOneMillion, }; } class CountryInfo { int id; double lat; double long; String flag; String iso3; String iso2; CountryInfo({ this.id, this.lat, this.long, this.flag, this.iso3, this.iso2, }); factory CountryInfo.fromJson(Map<String, dynamic> json) => CountryInfo( id: json["_id"] == null ? null : json["_id"], lat: json["lat"] == null ? null : json["lat"].toDouble(), long: json["long"] == null ? null : json["long"].toDouble(), flag: json["flag"] == null ? null : json["flag"], iso3: json["iso3"] == null ? null : json["iso3"], iso2: json["iso2"] == null ? null : json["iso2"], ); Map<String, dynamic> toJson() => { "_id": id == null ? null : id, "lat": lat == null ? null : lat, "long": long == null ? null : long, "flag": flag == null ? null : flag, "iso3": iso3 == null ? null : iso3, "iso2": iso2 == null ? null : iso2, }; }
0
mirrored_repositories/Stay-safe-from-Corono-Virus/lib
mirrored_repositories/Stay-safe-from-Corono-Virus/lib/Http/http.dart
import 'dart:convert'; import 'package:covd_19/Http/allResultJson.dart'; import 'package:covd_19/Http/allCountry.dart'; import 'package:http/http.dart' as http; import 'package:covd_19/Constant/httpConstant.dart'; class HTTP{ Future<AllResult> allResult()async{ String url = HTTPCONSTANT.base+HTTPCONSTANT.all; AllResult _allResult; var filterData; try{ final response = await http.get(url); filterData = await json.decode(response.body); if(response.statusCode == 200){ if(filterData != null){ _allResult = AllResult.fromJson(filterData); } } } on Exception catch (ex){ print (ex); } return _allResult; } Future<List<AllCountry>> allCountry()async{ String url = HTTPCONSTANT.base+HTTPCONSTANT.country; List<AllCountry> _allCountry = new List<AllCountry>(); AllCountry object = new AllCountry(); List filterData; try{ final response = await http.get(url); filterData = await json.decode(response.body); if(response.statusCode == 200){ if(filterData != null){ filterData.forEach((value)=>{ object = AllCountry.fromJson(value), _allCountry.add(object) }); } } } on Exception catch (ex){ print (ex); } return _allCountry; } }
0
mirrored_repositories/Stay-safe-from-Corono-Virus/lib
mirrored_repositories/Stay-safe-from-Corono-Virus/lib/Http/allResultJson.dart
import 'dart:convert'; AllResult allResultFromJson(String str) => AllResult.fromJson(json.decode(str)); String allResultToJson(AllResult data) => json.encode(data.toJson()); class AllResult { int cases; int deaths; int recovered; int updated; AllResult({ this.cases, this.deaths, this.recovered, this.updated, }); factory AllResult.fromJson(Map<String, dynamic> json) => AllResult( cases: json["cases"] == null ? null : json["cases"], deaths: json["deaths"] == null ? null : json["deaths"], recovered: json["recovered"] == null ? null : json["recovered"], updated: json["updated"] == null ? null : json["updated"], ); Map<String, dynamic> toJson() => { "cases": cases == null ? null : cases, "deaths": deaths == null ? null : deaths, "recovered": recovered == null ? null : recovered, "updated": updated == null ? null : updated, }; }
0
mirrored_repositories/Stay-safe-from-Corono-Virus
mirrored_repositories/Stay-safe-from-Corono-Virus/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:covd_19/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/x
mirrored_repositories/x/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:x/common/common.dart'; import 'package:x/core/service_locator.dart'; import 'package:x/features/auth/controller/auth_controller.dart'; import 'package:x/features/home/view/home_view.dart'; import 'package:x/theme/theme.dart'; import 'features/auth/view/login_view.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await setUpDependencies(); runApp(const ProviderScope(child: MyApp())); } class MyApp extends ConsumerWidget { const MyApp({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { return MaterialApp( title: 'Twitter Clone', theme: AppTheme.theme, home: ref.watch(currentUserAccountProvider).when( data: (user) { if (user != null) { return const HomeView(); }else{ return const LoginView(); } }, error: (error, st) => ErrorPage( error: error.toString(), ), loading: () => const LoadingPage(), ), ); } }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/constants/appwrite_constants.dart
class AppwriteConstants { static const String databaseId = '650ac043b551ac054144'; static const String projectId = '650aa6c4a35400770ff0'; static const String endPointMobile = 'http://172.29.112.1:885/v1'; // static const String endPointMobile = 'http://10.0.2.2:885/v1'; static const String endPointWeb = 'http://127.0.0.1:885/v1'; static const String usersCollection = '65104dcb048d2a294630'; static const String tweetsCollection = '651bc52fb19dec766d06'; static const String notificationsCollection = '651bcb59cad204abe2ad'; static const String imagesBucket = '651bcd0da2a1ab69d846'; static String imageUrl(String imageId, String endpoint) => '$endpoint/storage/buckets/$imagesBucket/files/$imageId/view?project=$projectId&mode=admin'; }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/constants/constants.dart
export './appwrite_constants.dart'; export './assets_constants.dart'; export './ui_constants.dart';
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/constants/ui_constants.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:x/features/explore/fragment/explore_fragment.dart'; import 'package:x/features/notification/fragment/notification_view.dart'; import 'package:x/features/tweet/fragment/tweet_list_fragment.dart'; import 'package:x/theme/pallete.dart'; import 'constants.dart'; class UIConstants { static AppBar appBar() { return AppBar( title: SvgPicture.asset( AssetsConstants.twitterLogo, colorFilter: const ColorFilter.mode(Pallete.blueColor, BlendMode.srcIn), height: 30, ), centerTitle: true, ); } static const List<Widget> bottomTabBarPages = [ TweetListFragment(), ExploreFragment(), NotificationFragment(), ]; }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/constants/assets_constants.dart
class AssetsConstants { static const String _svgsPath = 'assets/svgs'; static const String twitterLogo = '$_svgsPath/twitter_logo.svg'; static const String homeFilledIcon = '$_svgsPath/home_filled.svg'; static const String homeOutlinedIcon = '$_svgsPath/home_outlined.svg'; static const String notifFilledIcon = '$_svgsPath/notif_filled.svg'; static const String notifOutlinedIcon = '$_svgsPath/notif_outlined.svg'; static const String searchIcon = '$_svgsPath/search.svg'; static const String gifIcon = '$_svgsPath/gif.svg'; static const String emojiIcon = '$_svgsPath/emoji.svg'; static const String galleryIcon = '$_svgsPath/gallery.svg'; static const String commentIcon = '$_svgsPath/comment.svg'; static const String retweetIcon = '$_svgsPath/retweet.svg'; static const String likeOutlinedIcon = '$_svgsPath/like_outlined.svg'; static const String likeFilledIcon = '$_svgsPath/like_filled.svg'; static const String viewsIcon = '$_svgsPath/views.svg'; static const String verifiedIcon = '$_svgsPath/verified.svg'; static const String blankImage = 'https://upload.wikimedia.org/wikipedia/commons/a/a7/Blank_image.jpg?20180514195324'; }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/repository/notification_api.dart
import 'package:appwrite/appwrite.dart'; import 'package:appwrite/models.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:fpdart/fpdart.dart'; import 'package:x/constants/appwrite_constants.dart'; import 'package:x/model/notification.dart'; import '../core/core.dart'; final notificationAPIProvider = Provider((ref) { return NotificationAPI( db: ref.watch(appwriteDatabaseProvider), realtime: ref.watch(appwriteRealtimeProvider3), ); }); abstract class NotificationAPIInterface { FutureEitherVoid createNotification(Notification notification); Future<List<Document>> getNotifications(String uid); Stream<RealtimeMessage> getLatestNotification(); } class NotificationAPI implements NotificationAPIInterface { final Databases _db; final Realtime _realtime; NotificationAPI({required Databases db, required Realtime realtime}) : _db = db, _realtime = realtime; @override FutureEitherVoid createNotification(Notification notification) async { try { await _db.createDocument( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.notificationsCollection, documentId: ID.unique(), data: notification.toMap(), ); return right(null); } on AppwriteException catch (e, st) { return left( Failure( message: e.message ?? 'Some unexpected error occurred', stackTrace: st, ), ); } catch (e, st) { return left(Failure(message: e.toString(), stackTrace: st)); } } @override Stream<RealtimeMessage> getLatestNotification() { return _realtime.subscribe([ 'databases.${AppwriteConstants.databaseId}.collections.${AppwriteConstants.notificationsCollection}.documents' ]).stream; } @override Future<List<Document>> getNotifications(String uid) async { final documents = await _db.listDocuments( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.notificationsCollection, queries: [ Query.equal('uid', uid), ], ); return documents.documents; } }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/repository/user_api.dart
import 'package:appwrite/appwrite.dart'; import 'package:appwrite/models.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:fpdart/fpdart.dart'; import 'package:x/constants/appwrite_constants.dart'; import 'package:x/core/core.dart'; import 'package:x/model/user.dart'; final userAPIProvider = Provider((ref) { return UserAPI( db: ref.watch(appwriteDatabaseProvider), realtime: ref.watch(appwriteRealtimeProvider2), ); }); abstract class IUserAPI { FutureEitherVoid saveUserData(UserModel userModel); Future<Document> getUserData(String uid); Future<List<Document>> searchUserByName(String name); FutureEitherVoid updateUserData(UserModel userModel); Stream<RealtimeMessage> getLatestUserProfileData(); FutureEitherVoid followUser(UserModel user); FutureEitherVoid addToFollowing(UserModel user); } class UserAPI implements IUserAPI { final Databases _db; final Realtime _realtime; UserAPI({ required Databases db, required Realtime realtime, }) : _realtime = realtime, _db = db; @override FutureEitherVoid saveUserData(UserModel userModel) async { try { await _db.createDocument( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.usersCollection, documentId: userModel.uid, data: userModel.toMap(), ); return right(null); } on AppwriteException catch (e, st) { return left( Failure( message: e.message ?? 'Some unexpected error occurred', stackTrace: st, ), ); } catch (e, st) { return left(Failure(message: e.toString(), stackTrace: st)); } } @override Future<Document> getUserData(String uid) { return _db.getDocument( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.usersCollection, documentId: uid, ); } @override Future<List<Document>> searchUserByName(String name) async { final documents = await _db.listDocuments( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.usersCollection, queries: [ Query.search('name', name), ], ); return documents.documents; } @override FutureEitherVoid updateUserData(UserModel userModel) async { try { await _db.updateDocument( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.usersCollection, documentId: userModel.uid, data: userModel.toMap(), ); return right(null); } on AppwriteException catch (e, st) { return left( Failure( message: e.message ?? 'Some unexpected error occurred', stackTrace: st, ), ); } catch (e, st) { return left(Failure(message: e.toString(), stackTrace: st)); } } @override Stream<RealtimeMessage> getLatestUserProfileData() { return _realtime.subscribe([ 'databases.${AppwriteConstants.databaseId}.collections.${AppwriteConstants.usersCollection}.documents' ]).stream; } @override FutureEitherVoid followUser(UserModel user) async { try { await _db.updateDocument( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.usersCollection, documentId: user.uid, data: { 'followers': user.followers, }, ); return right(null); } on AppwriteException catch (e, st) { return left( Failure( message: e.message ?? 'Some unexpected error occurred', stackTrace: st, ), ); } catch (e, st) { return left(Failure(message: e.toString(), stackTrace: st)); } } @override FutureEitherVoid addToFollowing(UserModel user) async { try { await _db.updateDocument( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.usersCollection, documentId: user.uid, data: { 'following': user.following, }, ); return right(null); } on AppwriteException catch (e, st) { return left( Failure( message: e.message ?? 'Some unexpected error occurred', stackTrace: st, ), ); } catch (e, st) { return left(Failure(message: e.toString(), stackTrace: st)); } } }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/repository/auth_api.dart
import 'package:appwrite/appwrite.dart'; import 'package:appwrite/appwrite.dart'; import 'package:appwrite/models.dart'; import 'package:appwrite/models.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:fpdart/fpdart.dart'; import 'package:x/core/core.dart'; import 'package:x/core/service_locator.dart'; // read only value final authAPIProvider = Provider((ref) { final account = ref.watch(appWriteAccountProvider); return AuthAPI(account: account); }); abstract class IAuthAPI { FutureEither<User> signUp({ required String email, required String password, }); FutureEither<Session> login({ required String email, required String password, }); Future<User?> currentUserAccount(); FutureEitherVoid logout(); } class AuthAPI implements IAuthAPI { final Account _account; AuthAPI({required Account account}) : _account = account; @override Future<User?> currentUserAccount() async { try { return await _account.get(); } on AppwriteException { return null; } catch (e) { return null; } } @override FutureEither<User> signUp({ required String email, required String password, }) async { try { final account = await _account.create( userId: ID.unique(), email: email, password: password, ); return right(account); } on AppwriteException catch (e, stackTrace) { return left( Failure(message: e.message ?? 'Some unexpected error occurred', stackTrace: stackTrace), ); } catch (e, stackTrace) { return left( Failure(message: e.toString(), stackTrace: stackTrace), ); } } @override FutureEither<Session> login({ required String email, required String password, }) async { try { final session = await _account.createEmailSession( email: email, password: password, ); return right(session); } on AppwriteException catch (e, stackTrace) { return left( Failure(message: e.message ?? 'Some unexpected error occurred', stackTrace: stackTrace), ); } catch (e, stackTrace) { return left( Failure(message: e.toString(), stackTrace: stackTrace), ); } } @override FutureEitherVoid logout() async { try { await _account.deleteSession( sessionId: 'current', ); return right(null); } on AppwriteException catch (e, stackTrace) { return left( Failure(message: e.message ?? 'Some unexpected error occurred', stackTrace: stackTrace), ); } catch (e, stackTrace) { return left( Failure(message: e.toString(), stackTrace: stackTrace), ); } } }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/repository/tweet_api.dart
import 'package:appwrite/appwrite.dart'; import 'package:appwrite/models.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:fpdart/fpdart.dart'; import 'package:x/constants/appwrite_constants.dart'; import 'package:x/core/core.dart'; import 'package:x/model/tweet.dart'; final tweetAPIProvider = Provider((ref) { return TweetAPI(db: ref.watch(appwriteDatabaseProvider), realtime: ref.watch(appwriteRealtimeProvider)); }); abstract class TweetAPIInterface { FutureEither<Document> shareTweet(Tweet tweet); Future<List<Document>> getTweets(); Stream<RealtimeMessage> getLatestTweet(); FutureEither<Document> likeTweet(Tweet tweet); FutureEither<Document> updateReShareCount(Tweet tweet); Future<List<Document>> getRepliesToTweet(Tweet tweet); Future<Document> getTweetById(String id); Future<List<Document>> getUserTweets(String uid); Future<List<Document>> getTweetsByHashtag(String hashtag); } class TweetAPI implements TweetAPIInterface { final Databases _db; final Realtime _realtime; TweetAPI({required Databases db, required Realtime realtime}) : _db = db, _realtime = realtime; @override Stream<RealtimeMessage> getLatestTweet() { return _realtime.subscribe([ 'databases.${AppwriteConstants.databaseId}.collections.${AppwriteConstants.tweetsCollection}.documents' ]).stream; } @override Future<List<Document>> getRepliesToTweet(Tweet tweet) async { final document = await _db.listDocuments( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.tweetsCollection, queries: [ Query.equal('repliedTo', tweet.id), ], ); return document.documents; } @override Future<Document> getTweetById(String id) async { return await _db.getDocument( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.tweetsCollection, documentId: id, ); } @override Future<List<Document>> getTweets() async { final documents = await _db.listDocuments( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.tweetsCollection, queries: [ Query.orderDesc('tweetedAt'), ], ); return documents.documents; } @override Future<List<Document>> getTweetsByHashtag(String hashtag) async { final documents = await _db.listDocuments( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.tweetsCollection, queries: [ Query.search('hashtags', hashtag), ], ); return documents.documents; } @override Future<List<Document>> getUserTweets(String uid) async { final documents = await _db.listDocuments( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.tweetsCollection, queries: [ Query.equal('uid', uid), ], ); return documents.documents; } @override FutureEither<Document> likeTweet(Tweet tweet) async{ try { final document = await _db.updateDocument( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.tweetsCollection, documentId: tweet.id, data: { 'likes': tweet.likes, }, ); return right(document); } on AppwriteException catch (e, st) { print("likes error ${e} ${st}"); return left( Failure( message: e.message ?? 'Some unexpected error occurred', stackTrace: st, ), ); } catch (e, st) { return left(Failure(message: e.toString(), stackTrace: st)); } } @override FutureEither<Document> shareTweet(Tweet tweet) async { try { final document = await _db.createDocument( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.tweetsCollection, documentId: ID.unique(), data: tweet.toMap(), ); return right(document); } on AppwriteException catch (e, st) { return left( Failure( message: "shareTweet in tweetApi error ${e.message}", stackTrace: st, ), ); } catch (e, st) { return left(Failure(message: "shareTweet in tweetApi $e", stackTrace: st)); } } @override FutureEither<Document> updateReShareCount(Tweet tweet) async { try { final document = await _db.updateDocument( databaseId: AppwriteConstants.databaseId, collectionId: AppwriteConstants.tweetsCollection, documentId: tweet.id, data: { 'reshareCount': tweet.reshareCount, }, ); return right(document); } on AppwriteException catch (e, st) { return left( Failure( message: e.message ?? 'Some unexpected error occurred', stackTrace: st, ), ); } catch (e, st) { return left(Failure(message: e.toString(), stackTrace: st)); } } }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/repository/storage_api.dart
import 'dart:io'; import 'dart:typed_data'; import 'package:appwrite/appwrite.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:image_picker/image_picker.dart'; import 'package:x/constants/constants.dart'; import 'package:x/core/service_locator.dart'; final storageAPIProvider = Provider((ref) { return StorageAPI( storage: ref.watch(appwriteStorageProvider), ); }); abstract class StorageAPIInterface { Future<List<String>> uploadImage(List<File> files); } class StorageAPI implements StorageAPIInterface { final Storage _storage; StorageAPI({required Storage storage}) : _storage = storage; @override Future<List<String>> uploadImage(List<File> files) async { List<String> imageLinks = []; var endpoint = AppwriteConstants.endPointMobile; if(kIsWeb){ print('UploadImage using web'); endpoint = AppwriteConstants.endPointWeb; for (final fileWeb in files) { XFile file = XFile(fileWeb.path); List<int> fileBytes = await file.readAsBytes(); // Parse the URL and extract the path Uri uri = Uri.parse(file.path.replaceFirst("blob:", "")); String filename = uri.pathSegments.last; final uploadedImage = await _storage.createFile( bucketId: AppwriteConstants.imagesBucket, fileId: ID.unique(), file: InputFile.fromBytes( bytes: fileBytes, filename: filename, ), ); imageLinks.add( AppwriteConstants.imageUrl(uploadedImage.$id, endpoint), ); } return imageLinks; } for (final file in files) { final uploadedImage = await _storage.createFile( bucketId: AppwriteConstants.imagesBucket, fileId: ID.unique(), file: InputFile.fromPath(path: file.path), ); imageLinks.add( AppwriteConstants.imageUrl(uploadedImage.$id, endpoint), ); } return imageLinks; } }
0
mirrored_repositories/x/lib/features/notification
mirrored_repositories/x/lib/features/notification/fragment/notification_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:x/common/widgets/loading_widget.dart'; import 'package:x/constants/constants.dart'; import 'package:x/features/auth/controller/auth_controller.dart'; import 'package:x/features/notification/controller/notification_controller.dart'; import 'package:x/features/notification/widget/notification_tile.dart'; import 'package:x/model/notification.dart' as model; import '../../../common/widgets/error_page.dart'; class NotificationFragment extends ConsumerWidget { const NotificationFragment({ Key? key, }) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { final currentUser = ref.watch(currentUserDetailsProvider).value; return Scaffold( appBar: AppBar( title: const Text('Notifications'), ), body: currentUser == null ? const LoadingWidget() : ref.watch(getNotificationsProvider(currentUser.uid)).when( data: (notifications) { return ref.watch(getLatestNotificationProvider).when( data: (data) { if (data.events.contains( 'databases.*.collections.${AppwriteConstants.notificationsCollection}.documents.*.create', )) { final latestNotif = model.Notification.fromMap(data.payload); if (latestNotif.uid == currentUser.uid) { notifications.insert(0, latestNotif); } } return ListView.builder( itemCount: notifications.length, itemBuilder: (BuildContext context, int index) { final notification = notifications[index]; return NotificationTile( notification: notification, ); }, ); }, error: (error, stackTrace) { print("getNotificationsProvider error $stackTrace"); return ErrorText( error: error.toString(), ); }, loading: () { return ListView.builder( itemCount: notifications.length, itemBuilder: (BuildContext context, int index) { final notification = notifications[index]; return NotificationTile( notification: notification, ); }, ); }, ); }, error: (error, stackTrace) { print("Notification view error $stackTrace"); return ErrorText( error: error.toString(), );}, loading: () { return const LoadingWidget(); }, ), ); } }
0
mirrored_repositories/x/lib/features/notification
mirrored_repositories/x/lib/features/notification/widget/notification_tile.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:x/constants/assets_constants.dart'; import 'package:x/core/enum/notification_type_enum.dart'; import 'package:x/model/notification.dart' as model; import 'package:x/theme/pallete.dart'; class NotificationTile extends StatelessWidget { final model.Notification notification; const NotificationTile({ super.key, required this.notification, }); @override Widget build(BuildContext context) { return ListTile( leading: notification.notificationType == NotificationType.follow ? const Icon( Icons.person, color: Pallete.blueColor, ) : notification.notificationType == NotificationType.like ? SvgPicture.asset( AssetsConstants.likeFilledIcon, colorFilter: const ColorFilter.mode(Pallete.redColor, BlendMode.srcIn), height: 20, ) : notification.notificationType == NotificationType.retweet ? SvgPicture.asset( AssetsConstants.retweetIcon, colorFilter: const ColorFilter.mode(Pallete.whiteColor, BlendMode.srcIn), height: 20, ) : null, title: Text(notification.text), ); } }
0
mirrored_repositories/x/lib/features/notification
mirrored_repositories/x/lib/features/notification/controller/notification_controller.dart
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:x/core/enum/notification_type_enum.dart'; import 'package:x/model/notification.dart' as model; import 'package:x/repository/notification_api.dart'; final notificationControllerProvider = StateNotifierProvider<NotificationController, bool>((ref) { return NotificationController( ref.watch(notificationAPIProvider), ); }); final getLatestNotificationProvider = StreamProvider((ref) { final notificationAPI = ref.watch(notificationAPIProvider); return notificationAPI.getLatestNotification(); }); final getNotificationsProvider = FutureProvider.family((ref, String uid) async { final notificationController = ref.watch(notificationControllerProvider.notifier); return notificationController.getNotifications(uid); }); class NotificationController extends StateNotifier<bool> { final NotificationAPI _notificationAPI; NotificationController(this._notificationAPI): super(false); Future createNotification({ required String text, required String postId, required NotificationType notificationType, required String uid, }) async { final notification = model.Notification( text: text, postId: postId, id: '', uid: uid, notificationType: notificationType, ); final res = await _notificationAPI.createNotification(notification); res.fold((l) { print("error create notification ${l.message} ${l.stackTrace}"); }, (r) => null); } Future<List<model.Notification>> getNotifications(String uid) async { final notifications = await _notificationAPI.getNotifications(uid); return notifications .map((e) => model.Notification.fromMap(e.data)) .toList(); } }
0
mirrored_repositories/x/lib/features/explore
mirrored_repositories/x/lib/features/explore/widgets/search_tile.dart
import 'package:flutter/material.dart'; import 'package:x/features/profile/view/user_profile_view.dart'; import 'package:x/model/user.dart'; import 'package:x/theme/pallete.dart'; class SearchTile extends StatelessWidget { final UserModel userModel; const SearchTile(this.userModel, {super.key}); @override Widget build(BuildContext context) { return ListTile( onTap: () { Navigator.push( context, UserProfileView.route(userModel), ); }, leading: CircleAvatar( backgroundImage: NetworkImage(userModel.profilePic), radius: 30, ), title: Text( userModel.name, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.w600, ), ), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '@${userModel.name}', style: const TextStyle( fontSize: 16, ), ), Text( userModel.bio, style: const TextStyle( color: Pallete.whiteColor, ), ), ], ), ); } }
0
mirrored_repositories/x/lib/features/explore
mirrored_repositories/x/lib/features/explore/fragment/explore_fragment.dart
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:x/common/common.dart'; import 'package:x/features/explore/controller/explore_controller.dart'; import 'package:x/features/explore/widgets/search_tile.dart'; import 'package:x/model/user.dart'; import 'package:x/theme/pallete.dart'; class ExploreFragment extends ConsumerStatefulWidget { const ExploreFragment({super.key}); @override ConsumerState<ConsumerStatefulWidget> createState() => _ExploreFragmentState(); } class _ExploreFragmentState extends ConsumerState<ExploreFragment> { final searchController = TextEditingController(); bool isShowUsers = false; @override void dispose() { super.dispose(); searchController.dispose(); } @override Widget build(BuildContext context) { final appBarTextFieldBorder = OutlineInputBorder( borderRadius: BorderRadius.circular(50), borderSide: const BorderSide( color: Pallete.searchBarColor, ), ); return Scaffold( appBar: AppBar( title: SizedBox( height: 50, child: TextField( controller: searchController, onSubmitted: (value) { setState(() { isShowUsers = true; }); }, decoration: InputDecoration( contentPadding: const EdgeInsets.all(10).copyWith( left: 20, ), fillColor: Pallete.searchBarColor, filled: true, enabledBorder: appBarTextFieldBorder, focusedBorder: appBarTextFieldBorder, hintText: 'Search Twitter', ), ), ), ), body: isShowUsers ? ref.watch(searchUserProvider(searchController.text)).when( data: (users) { return ListView.builder( itemCount: users.length, itemBuilder: (BuildContext context, int index) { final user = users[index]; return SearchTile(user); }, ); }, error: (error, st) => ErrorText( error: error.toString(), ), loading: () => const LoadingWidget(), ) : const SizedBox(), ); } }
0
mirrored_repositories/x/lib/features/explore
mirrored_repositories/x/lib/features/explore/controller/explore_controller.dart
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:x/model/user.dart'; import 'package:x/repository/user_api.dart'; final exploreControllerProvider = StateNotifierProvider((ref) { return ExploreController(userAPI: ref.watch(userAPIProvider)); }); final searchUserProvider = FutureProvider.family((ref, String name) { final exploreController = ref.watch(exploreControllerProvider.notifier); return exploreController.searchUser(name); }); class ExploreController extends StateNotifier<bool> { final UserAPI _userAPI; ExploreController({required UserAPI userAPI}) : _userAPI = userAPI, super(false); Future<List<UserModel>> searchUser(String name) async { final getUsers = await _userAPI.searchUserByName(name); return getUsers.map((e) => UserModel.fromMap(e.data)).toList(); } }
0
mirrored_repositories/x/lib/features/tweet
mirrored_repositories/x/lib/features/tweet/view/create_tweet_view.dart
import 'dart:io'; import 'package:carousel_slider/carousel_slider.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:x/common/common.dart'; import 'package:x/constants/constants.dart'; import 'package:x/features/auth/controller/auth_controller.dart'; import 'package:x/features/tweet/controller/tweet_controller.dart'; import 'package:x/model/user.dart'; import 'package:x/theme/pallete.dart'; class CreateTweetView extends ConsumerStatefulWidget { static route() => MaterialPageRoute( builder: (context) => CreateTweetView(), ); const CreateTweetView({ Key? key, }) : super(key: key); @override ConsumerState<ConsumerStatefulWidget> createState() => _CreateTweetViewState(); } class _CreateTweetViewState extends ConsumerState<CreateTweetView> { final tweetTextController = TextEditingController(); List<File> images = []; void onPickImages() async { images = await pickImages(); setState(() {}); } @override void dispose() { super.dispose(); tweetTextController.dispose(); } void shareTweet() { ref.read(tweetControllerProvider.notifier).shareTweet( images: images, text: tweetTextController.text, context: context, repliedTo: '', repliedToUserId: '', ); Navigator.pop(context); } @override Widget build(BuildContext context) { UserModel? currentUser = ref.watch(currentUserDetailsProvider).value; bool isLoading = ref.watch(tweetControllerProvider); Widget showAttachmentOption( {VoidCallback? onTap, required String assetName}) { double paddingSize = MediaQuery.of(context).size.width * .04; return Padding( padding: EdgeInsets.all(paddingSize).copyWith( left: 15, right: 15, ), child: GestureDetector( onTap: onTap ?? () {}, child: SvgPicture.asset( assetName, width: paddingSize * 1.2, height: paddingSize * 1.2, ), ), ); } return Scaffold( appBar: AppBar( leading: IconButton( onPressed: () { Navigator.pop(context); }, icon: const Icon(Icons.close, size: 30), ), actions: [ RoundedSmallButton( onTap: shareTweet, label: 'Tweet', backgroundColor: Pallete.blueColor, textColor: Pallete.whiteColor, ), ], ), body: currentUser == null || isLoading ? const LoadingWidget() : SafeArea( child: SingleChildScrollView( scrollDirection: Axis.vertical, child: Column( children: [ Row( children: [ CircleAvatar( backgroundImage: NetworkImage(currentUser.profilePic), radius: 30, ), const SizedBox(width: 15), Expanded( child: TextField( controller: tweetTextController, style: const TextStyle( fontSize: 22, ), decoration: const InputDecoration( hintText: "What's happening?", hintStyle: TextStyle( color: Pallete.greyColor, fontSize: 12, fontWeight: FontWeight.w600), border: InputBorder.none, ), maxLines: null, )) ], ), if (images.isNotEmpty) if (kIsWeb) CarouselSlider( items: images.map((e) { print('using web access ${e.path}'); return Container( width: MediaQuery.of(context).size.width, margin: MarginConstant.marginHorizontal5, child: Image.network( e.path, fit: BoxFit.scaleDown, ), ); }).toList(), options: CarouselOptions( enlargeCenterPage: true, height: 400, enableInfiniteScroll: false)) else CarouselSlider( items: images.map((e) { return Container( width: MediaQuery.of(context).size.width, margin: MarginConstant.marginHorizontal5, child: Image.file( e, fit: BoxFit.cover, ), ); }).toList(), options: CarouselOptions( enlargeCenterPage: true, height: 400, enableInfiniteScroll: false)) ], ), )), bottomNavigationBar: Container( padding: PaddingConstant.paddingHorizontal25, decoration: const BoxDecoration( border: Border(top: BorderSide(color: Pallete.greyColor, width: 0.3))), child: Row( children: [ showAttachmentOption( assetName: AssetsConstants.galleryIcon, onTap: onPickImages), showAttachmentOption(assetName: AssetsConstants.gifIcon), showAttachmentOption(assetName: AssetsConstants.emojiIcon), ], ), ), ); } }
0
mirrored_repositories/x/lib/features/tweet
mirrored_repositories/x/lib/features/tweet/view/twitter_reply_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:x/common/common.dart'; import 'package:x/constants/appwrite_constants.dart'; import 'package:x/features/tweet/controller/tweet_controller.dart'; import 'package:x/features/tweet/widget/tweet_card.dart'; import 'package:x/model/tweet.dart'; class TwitterReplyScreen extends ConsumerWidget { static route(Tweet tweet) => MaterialPageRoute( builder: (context) => TwitterReplyScreen( tweet: tweet, ), ); final Tweet tweet; const TwitterReplyScreen({ super.key, required this.tweet, }); @override Widget build(BuildContext context, WidgetRef ref) { return Scaffold( appBar: AppBar( title: const Text('Tweet'), ), body: Column( children: [ TweetCard(tweet: tweet), ref.watch(getRepliesToTweetsProvider(tweet)).when( data: (tweets) { return ref.watch(getLatestTweetProvider).when( data: (data) { final latestTweet = Tweet.fromMap(data.payload); bool isTweetAlreadyPresent = false; for (final tweetModel in tweets) { if (tweetModel.id == latestTweet.id) { isTweetAlreadyPresent = true; break; } } if (!isTweetAlreadyPresent && latestTweet.repliedTo == tweet.id) { if (data.events.contains( 'databases.*.collections.${AppwriteConstants.tweetsCollection}.documents.*.create', )) { tweets.insert(0, Tweet.fromMap(data.payload)); } else if (data.events.contains( 'databases.*.collections.${AppwriteConstants.tweetsCollection}.documents.*.update', )) { // get id of original tweet final startingPoint = data.events[0].lastIndexOf('documents.'); final endPoint = data.events[0].lastIndexOf('.update'); final tweetId = data.events[0] .substring(startingPoint + 10, endPoint); var tweet = tweets .where((element) => element.id == tweetId) .first; final tweetIndex = tweets.indexOf(tweet); tweets.removeWhere( (element) => element.id == tweetId); tweet = Tweet.fromMap(data.payload); tweets.insert(tweetIndex, tweet); } } return Expanded( child: ListView.builder( itemCount: tweets.length, itemBuilder: (BuildContext context, int index) { final tweet = tweets[index]; return TweetCard(tweet: tweet); }, ), ); }, error: (error, stackTrace) => ErrorText( error: error.toString(), ), loading: () { return Expanded( child: ListView.builder( itemCount: tweets.length, itemBuilder: (BuildContext context, int index) { final tweet = tweets[index]; return TweetCard(tweet: tweet); }, ), ); }, ); }, error: (error, stackTrace) => ErrorText( error: error.toString(), ), loading: () => const LoadingWidget(), ), ], ), bottomNavigationBar: Container( margin: const EdgeInsets.all(16), child: TextField( onSubmitted: (value) { ref.read(tweetControllerProvider.notifier).shareTweet( images: [], text: value, context: context, repliedTo: tweet.id, repliedToUserId: tweet.uid, ); }, decoration: const InputDecoration( hintText: 'Tweet your reply', ), ), ), ); } }
0
mirrored_repositories/x/lib/features/tweet
mirrored_repositories/x/lib/features/tweet/view/hashtag_view.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:x/common/common.dart'; import 'package:x/constants/appwrite_constants.dart'; import 'package:x/features/tweet/controller/tweet_controller.dart'; import 'package:x/features/tweet/widget/tweet_card.dart'; import 'package:x/model/tweet.dart'; class HashtagView extends ConsumerWidget { static route(String hashtag) => MaterialPageRoute( builder: (context) { return HashtagView( hashTag: hashtag, ); }, ); final String hashTag; const HashtagView({Key? key, required this.hashTag}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { return Scaffold( appBar: AppBar( title: Text(hashTag), ), body: ref.watch(getTweetsByHashtagProvider(hashTag)).when( data: (tweets) { return ref.watch(getLatestTweetProvider).when( data: (data) { if (data.events.contains( 'databases.*.collections.${AppwriteConstants.tweetsCollection}.documents.*.create', )) { tweets.insert(0, Tweet.fromMap(data.payload)); } else if (data.events.contains( 'databases.*.collections.${AppwriteConstants.tweetsCollection}.documents.*.update', )) { if (kDebugMode) { print("data events: ${data.events[0]}"); } final startingPoint = data.events[0].lastIndexOf('documents.'); final endPoint = data.events[0].lastIndexOf('.update'); if (kDebugMode) { print("starting point $startingPoint endpoint $endPoint"); } final tweetId = data.events[0].substring(startingPoint + 10, endPoint); if (kDebugMode) { print('get tweet id $tweetId'); } var tweet = tweets.where((element) => element.id == tweetId).first; final tweetIndex = tweets.indexOf(tweet); tweets.removeWhere((element) => element.id == tweetId); tweet = Tweet.fromMap(data.payload); tweets.insert(tweetIndex, tweet); } else { if (kDebugMode) { print('dataevents1'); } if (kDebugMode) { print("data events: ${data.events[0]}"); } final startingPoint = data.events[0].lastIndexOf('documents.'); final endPoint = data.events[0].lastIndexOf('.update'); if (kDebugMode) { print("starting point $startingPoint endpoint $endPoint"); } } // print("View tweets view data2}"); return ListView.builder( itemCount: tweets.length, itemBuilder: (BuildContext context, int index) { final tweet = tweets[index]; return TweetCard(tweet: tweet); }, ); }, error: (error, stackTrace) => ErrorText( error: "$error $stackTrace", ), loading: () { return ListView.builder( itemCount: tweets.length, itemBuilder: (BuildContext context, int index) { final tweet = tweets[index]; return TweetCard(tweet: tweet); }, ); }); }, error: (error, stackTrace) => ErrorText( error: error.toString(), ), loading: () => const LoadingWidget(), ), ); } }
0
mirrored_repositories/x/lib/features/tweet
mirrored_repositories/x/lib/features/tweet/fragment/tweet_list_fragment.dart
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:x/common/common.dart'; import 'package:x/constants/constants.dart'; import 'package:x/features/auth/controller/auth_controller.dart'; import 'package:x/features/tweet/controller/tweet_controller.dart'; import 'package:x/features/tweet/widget/tweet_card.dart'; import 'package:x/model/tweet.dart'; class TweetListFragment extends ConsumerWidget { const TweetListFragment({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { // UserModel? userData = ref.watch(currentUserDetailsProvider).value; //currentUserAccountProvider return ref.watch(getTweetsProvider).when( data: (tweets) { // print("View tweets view data1 $tweets"); return ref.watch(getLatestTweetProvider).when( data: (data) { if (data.events.contains( 'databases.*.collections.${AppwriteConstants.tweetsCollection}.documents.*.create', )) { tweets.insert(0, Tweet.fromMap(data.payload)); } else if (data.events.contains( 'databases.*.collections.${AppwriteConstants.tweetsCollection}.documents.*.update', )) { print("data events: " + data.events[0]); final startingPoint = data.events[0].lastIndexOf('documents.'); final endPoint = data.events[0].lastIndexOf('.update'); print("starting point $startingPoint endpoint $endPoint"); final tweetId = data.events[0].substring(startingPoint + 10, endPoint); print('get tweet id $tweetId'); var tweet = tweets.where((element) => element.id == tweetId).first; final tweetIndex = tweets.indexOf(tweet); tweets.removeWhere((element) => element.id == tweetId); tweet = Tweet.fromMap(data.payload); tweets.insert(tweetIndex, tweet); } else { print('dataevents1'); print("data events: " + data.events[0]); final startingPoint = data.events[0].lastIndexOf('documents.'); final endPoint = data.events[0].lastIndexOf('.update'); print("starting point $startingPoint endpoint $endPoint"); } // print("View tweets view data2}"); return ListView.builder( itemCount: tweets.length, itemBuilder: (BuildContext context, int index) { // print("View tweets view data3"); final tweet = tweets[index]; return TweetCard(tweet: tweet); }, ); }, error: (error, stackTrace) => ErrorText( error: "$error $stackTrace", ), loading: () { return ListView.builder( itemCount: tweets.length, itemBuilder: (BuildContext context, int index) { final tweet = tweets[index]; return TweetCard(tweet: tweet); }, ); }); }, error: (error, stackTrace) => ErrorText(error: error.toString()), loading: () { return const LoadingWidget(); }); } }
0
mirrored_repositories/x/lib/features/tweet
mirrored_repositories/x/lib/features/tweet/widget/tweet_icon_button.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:x/theme/theme.dart'; class TweetIconButton extends StatelessWidget { final String pathName; final String text; final VoidCallback onTap; const TweetIconButton({ Key? key, required this.pathName, required this.text, required this.onTap, }) : super(key: key); @override Widget build(BuildContext context) { return GestureDetector( onTap: onTap, child: Row( children: [ SvgPicture.asset( pathName, colorFilter: const ColorFilter.mode(Pallete.greyColor, BlendMode.srcIn), ), Container( margin: const EdgeInsets.all(6), child: Text( text, style: const TextStyle( fontSize: 16, ), ), ), ], ), ); } }
0
mirrored_repositories/x/lib/features/tweet
mirrored_repositories/x/lib/features/tweet/widget/tweet_card.dart
import 'package:any_link_preview/any_link_preview.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; import 'package:like_button/like_button.dart'; import 'package:x/common/common.dart'; import 'package:x/constants/constants.dart'; import 'package:x/core/core.dart'; import 'package:x/core/enum/string_enum.dart'; import 'package:x/features/auth/controller/auth_controller.dart'; import 'package:x/features/profile/view/user_profile_view.dart'; import 'package:x/features/tweet/controller/tweet_controller.dart'; import 'package:x/features/tweet/view/twitter_reply_view.dart'; import 'package:x/features/tweet/widget/tweet_icon_button.dart'; import 'package:x/model/tweet.dart'; import 'package:x/theme/pallete.dart'; import 'package:timeago/timeago.dart' as timeago; import 'carousel_image.dart'; import 'hashtag_text.dart'; class TweetCard extends ConsumerWidget { final Tweet tweet; const TweetCard({ Key? key, required this.tweet, }) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { final currentUser = ref.watch(currentUserDetailsProvider).value; return currentUser == null ? const SizedBox() : ref.watch(userDetailsProvider(tweet.uid)).when( data: (user) { return InkWell( onTap: () { Navigator.push( context, TwitterReplyScreen.route(tweet), ); }, child: Container( color: Colors.indigoAccent.withOpacity(.2), child: Column( children: [ Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ GestureDetector( child: Container( margin: MarginConstant.marginAll8, child: InkWell( onTap: () { Navigator.push(context, UserProfileView.route(user)); }, child: CircleAvatar( backgroundImage: NetworkImage(kIsWeb ? user.profilePic: user.profilePic.replaceHostIP()), radius: 35, ), ), ), ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ if (tweet.retweetedBy.isNotEmpty) Row( children: [ SvgPicture.asset( AssetsConstants.retweetIcon, colorFilter: const ColorFilter.mode(Pallete.greyColor, BlendMode.srcIn), height: 20, ), const SizedBox(width: 2), Text( '${tweet.retweetedBy} retweeted', style: const TextStyle( color: Pallete.greyColor, fontSize: 16, fontWeight: FontWeight.w500, ), ), ], ), Row( children: [ Container( margin: EdgeInsets.only( right: user.isTwitterBlue ? 1 : 5, ), child: Text( user.name, style: const TextStyle( fontWeight: FontWeight.bold, fontSize: 19, ), ), ), if (user.isTwitterBlue) Padding( padding: const EdgeInsets.only(right: 5.0), child: SvgPicture.asset( AssetsConstants.verifiedIcon, ), ), Text( '@${user.name} · ${timeago.format( tweet.tweetedAt, locale: 'en_short', )}', style: const TextStyle( color: Pallete.greyColor, fontSize: 17, ), ), ], ), if (tweet.repliedTo.isNotEmpty) ref .watch( getTweetByIdProvider(tweet.repliedTo)) .when( data: (repliedToTweet) { final replyingToUser = ref .watch( userDetailsProvider( repliedToTweet.uid, ), ) .value; return RichText( text: TextSpan( text: 'Replying to', style: const TextStyle( color: Pallete.greyColor, fontSize: 16, ), children: [ TextSpan( text: ' @${replyingToUser?.name}', style: const TextStyle( color: Pallete.blueColor, fontSize: 16, ), ), ], ), ); }, error: (error, st) => ErrorText( error: error.toString(), ), loading: () => const SizedBox(), ), HashtagText(text: tweet.text), if (tweet.tweetType == TweetType.image) CarouselImage(imageLinks: tweet.imageLinks), if (tweet.link.isNotEmpty) ...[ const SizedBox(height: 4), AnyLinkPreview( displayDirection: UIDirection.uiDirectionHorizontal, link: tweet.link, ), ], Container( margin: const EdgeInsets.only( top: 10, right: 20, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ TweetIconButton( pathName: AssetsConstants.viewsIcon, text: (tweet.commentIds.length + tweet.reshareCount + tweet.likes.length) .toString(), onTap: () {}, ), TweetIconButton( pathName: AssetsConstants.commentIcon, text: tweet.commentIds.length.toString(), onTap: () {}, ), TweetIconButton( pathName: AssetsConstants.retweetIcon, text: tweet.reshareCount.toString(), onTap: () { ref .read(tweetControllerProvider .notifier) .reshareTweet( tweet, currentUser, context); }, ), LikeButton( size: 25, onTap: (isLiked) async { ref .read(tweetControllerProvider .notifier) .likeTweet( tweet, currentUser, ); return !isLiked; }, isLiked: tweet.likes.contains(currentUser.uid), likeBuilder: (isLiked) { return isLiked ? SvgPicture.asset( AssetsConstants.likeFilledIcon, colorFilter: const ColorFilter.mode(Pallete.redColor, BlendMode.srcIn), ) : SvgPicture.asset( AssetsConstants .likeOutlinedIcon, colorFilter: const ColorFilter.mode(Pallete.greyColor, BlendMode.srcIn), ); }, likeCount: tweet.likes.length, countBuilder: (likeCount, isLiked, text) { return Padding( padding: const EdgeInsets.only(left: 2.0), child: Text( text, style: TextStyle( color: isLiked ? Pallete.redColor : Pallete.whiteColor, fontSize: 16, ), ), ); }, ), IconButton( onPressed: () {}, icon: const Icon( Icons.share_outlined, size: 25, color: Pallete.greyColor, ), ), ], ), ), const SizedBox(height: 1), // @TODO: Create LIKE SHARE RETWEET const Divider(color: Pallete.greyColor), ])) ], ) ], ), ), ); }, error: (error, stackTrace) => ErrorText( error: error.toString(), ), loading: () => const LoadingWidget()); } }
0
mirrored_repositories/x/lib/features/tweet
mirrored_repositories/x/lib/features/tweet/widget/carousel_image.dart
import 'package:carousel_slider/carousel_slider.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:x/constants/appwrite_constants.dart'; class CarouselImage extends StatefulWidget { final List<String> imageLinks; const CarouselImage({ super.key, required this.imageLinks, }); @override State<CarouselImage> createState() => _CarouselImageState(); } class _CarouselImageState extends State<CarouselImage> { int _current = 0; @override Widget build(BuildContext context) { return Stack( alignment: Alignment.center, children: [ CarouselSlider( items: widget.imageLinks .map((link) => Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(25), ), margin: const EdgeInsets.all(10), child: Image.network( kIsWeb ? link : link.replaceAll('http://127.0.0.1', 'http://172.29.112.1'), fit: BoxFit.contain, ), )) .toList(), options: CarouselOptions( // viewportFraction: .75, aspectRatio: 2, enableInfiniteScroll: false, onPageChanged: (index, reason) { setState(() { _current = index; }); }, ), ), Positioned( bottom: 0, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: widget.imageLinks.asMap().entries.map((e) { return Container( width: 12, height: 12, margin: const EdgeInsets.symmetric( horizontal: 4, ), decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.white.withOpacity( _current == e.key ? 0.9 : 0.4, ), ), ); }).toList(), ), ), ], ); } }
0
mirrored_repositories/x/lib/features/tweet
mirrored_repositories/x/lib/features/tweet/widget/hashtag_text.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:x/features/tweet/view/hashtag_view.dart'; import 'package:x/theme/theme.dart'; class HashtagText extends StatelessWidget { final String text; const HashtagText({ super.key, required this.text, }); @override Widget build(BuildContext context) { List<TextSpan> textspans = []; text.split(' ').forEach((element) { if (element.startsWith('#')) { textspans.add( TextSpan( text: '$element ', style: const TextStyle( color: Pallete.blueColor, fontSize: 18, fontWeight: FontWeight.bold, ), recognizer: TapGestureRecognizer() ..onTap = () { Navigator.push( context, HashtagView.route(element), ); }, ), ); } else if (element.startsWith('www.') || element.startsWith('https://')) { textspans.add( TextSpan( text: '$element ', style: const TextStyle( color: Pallete.blueColor, fontSize: 18, ), ), ); } else { textspans.add( TextSpan( text: '$element ', style: const TextStyle( fontSize: 18, color: Pallete.whiteColor ), ), ); } }); return RichText( text: TextSpan( children: textspans, ), ); } }
0
mirrored_repositories/x/lib/features/tweet
mirrored_repositories/x/lib/features/tweet/controller/tweet_controller.dart
import 'dart:io'; import 'package:appwrite/appwrite.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:x/core/core.dart'; import 'package:x/core/enum/notification_type_enum.dart'; import 'package:x/features/auth/controller/auth_controller.dart'; import 'package:x/features/notification/controller/notification_controller.dart'; import 'package:x/model/tweet.dart'; import 'package:x/model/user.dart'; import 'package:x/repository/storage_api.dart'; import 'package:x/repository/tweet_api.dart'; import '../../../common/common.dart'; final tweetControllerProvider = StateNotifierProvider<TweetController, bool>( (ref) { return TweetController( ref: ref, tweetAPI: ref.watch(tweetAPIProvider), storageAPI: ref.watch(storageAPIProvider), notificationController: ref.watch(notificationControllerProvider.notifier), ); }, ); final getTweetsProvider = FutureProvider((ref) { final tweetController = ref.watch(tweetControllerProvider.notifier); return tweetController.getTweets(); }); final getRepliesToTweetsProvider = FutureProvider.family((ref, Tweet tweet) { final tweetController = ref.watch(tweetControllerProvider.notifier); return tweetController.getRepliesToTweet(tweet); }); final getTweetByIdProvider = FutureProvider.family((ref, String id) async { final tweetController = ref.watch(tweetControllerProvider.notifier); return tweetController.getTweetById(id); }); final getTweetsByHashtagProvider = FutureProvider.family((ref, String hashtag) { final tweetController = ref.watch(tweetControllerProvider.notifier); return tweetController.getTweetsByHashtag(hashtag); }); //family has data type immutable final getLatestTweetProvider = StreamProvider((ref) { final tweetAPI = ref.watch(tweetAPIProvider); if (kDebugMode) { print("getLatestTweetProvider ${tweetAPI.getLatestTweet().toList()}"); } return tweetAPI.getLatestTweet(); }); class TweetController extends StateNotifier<bool> { final TweetAPI _tweetAPI; final StorageAPI _storageAPI; final NotificationController _notificationController; final Ref _ref; TweetController({ required Ref ref, required TweetAPI tweetAPI, required StorageAPI storageAPI, required NotificationController notificationController, }) : _ref = ref, _tweetAPI = tweetAPI, _storageAPI = storageAPI, _notificationController = notificationController, super(false); Future<List<Tweet>> getTweets() async { try { final tweetList = await _tweetAPI.getTweets(); return tweetList.map((tweet) => Tweet.fromMap(tweet.data)).toList(); } catch (e) { if (kDebugMode) { print("Stack get tweets error $e"); } rethrow; } } Future<Tweet> getTweetById(String id) async { final tweet = await _tweetAPI.getTweetById(id); return Tweet.fromMap(tweet.data); } void shareTweet({ required List<File> images, required String text, required BuildContext context, required String repliedTo, required String repliedToUserId, }) { if (text.isEmpty) { showSnackBar(context, 'Please enter text'); return; } if (images.isNotEmpty) { _shareImageTweet( images: images, text: text, context: context, repliedTo: repliedTo, repliedToUserId: repliedToUserId, ); } else { _shareTextTweet( text: text, context: context, repliedTo: repliedTo, repliedToUserId: repliedToUserId, ); } } void _shareImageTweet( {required List<File> images, required String text, required BuildContext context, required String repliedTo, required String repliedToUserId}) async { state = true; final hashtags = _getHashtagsFromText(text); String link = _getLinkFromText(text); final user = _ref.read(currentUserDetailsProvider).value!; final imageLinks = await _storageAPI.uploadImage(images); Tweet tweet = Tweet( text: text, hashtags: hashtags, link: link, imageLinks: imageLinks, uid: user.uid, tweetType: TweetType.image, tweetedAt: DateTime.now(), likes: const [], commentIds: const [], id: '', reshareCount: 0, retweetedBy: '', repliedTo: repliedTo, ); final res = await _tweetAPI.shareTweet(tweet); res.fold((l) { print("Error _shareImageTweet ${l.stackTrace}"); return showSnackBar(context, l.message); }, (r) async { print("RepliedToUserID ${repliedToUserId.isNotEmpty}"); if (repliedToUserId.isNotEmpty) { await _notificationController.createNotification( text: '${user.name} replied to your tweet!', postId: r.$id, notificationType: NotificationType.reply, uid: repliedToUserId, ); } }); state = false; } void _shareTextTweet({ required String text, required BuildContext context, required String repliedTo, required String repliedToUserId, }) async { state = true; final hashtags = _getHashtagsFromText(text); String link = _getLinkFromText(text); final user = _ref.read(currentUserDetailsProvider).value!; Tweet tweet = Tweet( text: text, hashtags: hashtags, link: link, imageLinks: const [], uid: user.uid, tweetType: TweetType.text, tweetedAt: DateTime.now(), likes: const [], commentIds: const [], id: '', reshareCount: 0, retweetedBy: '', repliedTo: repliedTo, ); final res = await _tweetAPI.shareTweet(tweet); res.fold((l) { print("Error _shareTextTweet ${l.stackTrace}"); return showSnackBar(context, l.message); }, (r) async { print("RepliedToUserID ${repliedToUserId.isNotEmpty}"); if (repliedToUserId.isNotEmpty) { await _notificationController.createNotification( text: '${user.name} replied to your tweet!', postId: r.$id, notificationType: NotificationType.reply, uid: repliedToUserId, ); } }); state = false; } Future<List<Tweet>> getTweetsByHashtag(String hashtag) async { final documents = await _tweetAPI.getTweetsByHashtag(hashtag); return documents.map((tweet) => Tweet.fromMap(tweet.data)).toList(); } List<String> _getHashtagsFromText(String text) { return text.split(' ').where((word) => word.startsWith('#')).toList(); } String _getLinkFromText(String text) { return text.split(' ').firstWhere( (word) => word.startsWith('https://') || word.startsWith('www.'), orElse: () => '', ); } Future likeTweet(Tweet tweet, UserModel user) async { List<String> likes = tweet.likes; var textLike = "${user.name} "; if (tweet.likes.contains(user.uid)) { likes.remove(user.uid); textLike += "Unlike your tweet"; } else { likes.add(user.uid); textLike += "Like your tweet"; } tweet = tweet.copyWith(likes: likes); final res = await _tweetAPI.likeTweet(tweet); res.fold((l) => null, (r) { _notificationController.createNotification( text: textLike, postId: tweet.id, notificationType: NotificationType.like, uid: tweet.uid, ); }); } Future<List<Tweet>> getRepliesToTweet(Tweet tweet) async { final documents = await _tweetAPI.getRepliesToTweet(tweet); return documents.map((tweet) => Tweet.fromMap(tweet.data)).toList(); } void reshareTweet( Tweet tweet, UserModel currentUser, BuildContext context, ) async { tweet = tweet.copyWith( retweetedBy: currentUser.name, likes: [], commentIds: [], reshareCount: tweet.reshareCount + 1, ); final res = await _tweetAPI.updateReShareCount(tweet); res.fold( (l) => showSnackBar(context, l.message), (r) async { tweet = tweet.copyWith( id: ID.unique(), reshareCount: 0, tweetedAt: DateTime.now(), ); final res2 = await _tweetAPI.shareTweet(tweet); res2.fold( (l) { print("Error reshareTweet ${l.stackTrace}"); return showSnackBar(context, l.message); }, (r) { _notificationController.createNotification( text: '${currentUser.name} reshared your tweet!', postId: tweet.id, notificationType: NotificationType.retweet, uid: tweet.uid, ); showSnackBar(context, 'Retweeted!'); }, ); }, ); } }
0
mirrored_repositories/x/lib/features/profile
mirrored_repositories/x/lib/features/profile/view/edit_user_profile.dart
import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:x/common/common.dart'; import 'package:x/features/auth/controller/auth_controller.dart'; import 'package:x/features/profile/controller/profile_controller.dart'; import 'package:x/model/user.dart'; import 'package:x/theme/theme.dart'; class EditProfileView extends ConsumerStatefulWidget { const EditProfileView({ Key? key, }) : super(key: key); static route() => MaterialPageRoute( builder: (context) => const EditProfileView(), ); @override ConsumerState createState() => _EditProfileViewState(); } class _EditProfileViewState extends ConsumerState<EditProfileView> { late TextEditingController nameController; late TextEditingController bioController; File? bannerFile; File? profileFile; @override void initState() { super.initState(); nameController = TextEditingController( text: ref.read(currentUserDetailsProvider).value?.name ?? '', ); bioController = TextEditingController( text: ref.read(currentUserDetailsProvider).value?.bio ?? '', ); } @override void dispose() { super.dispose(); nameController.dispose(); bioController.dispose(); } void selectBannerImage() async { final banner = await pickImage(); if (banner != null) { setState(() { bannerFile = banner; }); } } void selectProfileImage() async { final profileImage = await pickImage(); if (profileImage != null) { setState(() { profileFile = profileImage; }); } } @override Widget build(BuildContext context) { final user = ref.watch(currentUserDetailsProvider).value; final isLoading = ref.watch(userProfileControllerProvider); Widget getBannerWidget(UserModel user) { if (kIsWeb) { if (user.bannerPic.isNotEmpty) { return Image.network( user.bannerPic, fit: BoxFit.fitWidth, ); } if (bannerFile != null) { return Image.network( bannerFile!.path, fit: BoxFit.fitWidth, ); } else { return Container( color: Pallete.blueColor, ); } } else { if (bannerFile != null) { return Image.file( bannerFile!, fit: BoxFit.fitWidth, ); } else { return Container( color: Pallete.blueColor, ); } } } Widget getProfileImageWidget(UserModel user) { if (kIsWeb) { return CircleAvatar( backgroundImage: NetworkImage(profileFile?.path ?? user.profilePic), radius: 40, ); } else { if (profileFile != null) { return CircleAvatar( backgroundImage: FileImage(profileFile!), radius: 40, ); } else { return CircleAvatar( backgroundImage: NetworkImage(user.profilePic), radius: 40, ); } } } return Scaffold( appBar: AppBar( title: const Text('Edit Profile'), centerTitle: false, actions: [ TextButton( onPressed: () async { ref .read(userProfileControllerProvider.notifier) .updateUserProfile( userModel: user!.copyWith( bio: bioController.text, name: nameController.text, ), context: context, bannerFile: bannerFile, profileFile: profileFile, ); }, child: const Text('Save')) ], ), body: isLoading || user == null ? const LoadingWidget() : Column( children: [ SizedBox( height: MediaQuery.of(context).size.width * .15, child: Stack( children: [ GestureDetector( onTap: selectBannerImage, child: Container( width: double.infinity, height: MediaQuery.of(context).size.width * .1, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), ), child: getBannerWidget(user), )), Positioned( bottom: MediaQuery.of(context).size.width * .05 - 30, left: 20, child: GestureDetector( onTap: selectProfileImage, child: getProfileImageWidget(user))), ], ), ), TextField( controller: nameController, decoration: const InputDecoration( hintText: 'Name', contentPadding: EdgeInsets.all(18), ), ), const SizedBox(height: 20), TextField( controller: bioController, decoration: const InputDecoration( hintText: 'Bio', contentPadding: EdgeInsets.all(18), ), maxLines: 4, ), ], ), ); } }
0
mirrored_repositories/x/lib/features/profile
mirrored_repositories/x/lib/features/profile/view/user_profile_view.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:x/common/widgets/error_page.dart'; import 'package:x/constants/appwrite_constants.dart'; import 'package:x/features/profile/controller/profile_controller.dart'; import 'package:x/features/profile/widget/user_profile_widget.dart'; import 'package:x/model/user.dart'; class UserProfileView extends ConsumerWidget { static route(UserModel userModel) => MaterialPageRoute( builder: (context) => UserProfileView( userModel: userModel, ), ); final UserModel userModel; const UserProfileView({ super.key, required this.userModel, }); @override Widget build(BuildContext context, WidgetRef ref) { UserModel copyOfUser = userModel; return Scaffold( body: ref.watch(getLatestUserProfileDataProvider).when( data: (data) { if (data.events.contains( 'databases.${AppwriteConstants.databaseId}.collections.${AppwriteConstants.usersCollection}.documents.${copyOfUser.uid}.update', ) || data.events.contains( 'databases.${AppwriteConstants.databaseId}.collections.${AppwriteConstants.usersCollection}.documents.${copyOfUser.uid}.create', ) ) { copyOfUser = UserModel.fromMap(data.payload); } return UserProfileWidget(user: copyOfUser); }, error: (error, st) => ErrorText( error: error.toString(), ), loading: () { return UserProfileWidget(user: copyOfUser); }, ), ); } }
0
mirrored_repositories/x/lib/features/profile
mirrored_repositories/x/lib/features/profile/widget/user_profile_widget.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; import 'package:x/common/common.dart'; import 'package:x/constants/constants.dart'; import 'package:x/core/enum/string_enum.dart'; import 'package:x/features/auth/controller/auth_controller.dart'; import 'package:x/features/profile/controller/profile_controller.dart'; import 'package:x/features/profile/view/edit_user_profile.dart'; import 'package:x/features/tweet/controller/tweet_controller.dart'; import 'package:x/features/tweet/widget/tweet_card.dart'; import 'package:x/model/tweet.dart'; import 'package:x/model/user.dart'; import 'package:x/theme/pallete.dart'; import 'follow_count.dart'; class UserProfileWidget extends ConsumerWidget { final UserModel user; const UserProfileWidget({Key? key, required this.user}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { final currentUser = ref.watch(currentUserDetailsProvider).value; return currentUser == null ? const LoadingPage() : NestedScrollView( headerSliverBuilder: (context, innerBoxIsScrolled) { return [ SliverAppBar( expandedHeight: 150, floating: true, snap: true, flexibleSpace: Stack( children: [ Positioned.fill( child: user.bannerPic.isEmpty ? Container( color: Pallete.blueColor, ) : Image.network( kIsWeb ? user.bannerPic : user.bannerPic.replaceHostIP(), fit: BoxFit.fitWidth, ), ), Positioned( bottom: 0, child: CircleAvatar( backgroundImage: NetworkImage(kIsWeb ? user.profilePic: user.profilePic.replaceAll('http://127.0.0.1', 'http://172.29.112.1')), radius: 45, ), ), Container( alignment: Alignment.bottomRight, margin: const EdgeInsets.all(20), child: OutlinedButton( onPressed: () { if (currentUser.uid == user.uid) { // edit profile Navigator.push(context, EditProfileView.route()); } else { ref .read(userProfileControllerProvider.notifier) .followUser( user: user, context: context, currentUser: currentUser, ); } }, style: ElevatedButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), side: const BorderSide( color: Pallete.whiteColor, ), ), padding: const EdgeInsets.symmetric(horizontal: 25), ), child: Text( currentUser.uid == user.uid ? 'Edit Profile' : currentUser.following.contains(user.uid) ? 'Unfollow' : 'Follow', style: const TextStyle( color: Pallete.whiteColor, ), ), ), ), ], ), ), SliverPadding( padding: const EdgeInsets.all(8), sliver: SliverList( delegate: SliverChildListDelegate( [ Row( children: [ Text( user.name, style: const TextStyle( fontSize: 25, fontWeight: FontWeight.bold, ), ), if (user.isTwitterBlue) Padding( padding: const EdgeInsets.only(left: 3.0), child: SvgPicture.asset( AssetsConstants.verifiedIcon, ), ), ], ), Text( '@${user.name}', style: const TextStyle( fontSize: 17, color: Pallete.greyColor, ), ), Text( user.bio, style: const TextStyle( fontSize: 17, ), ), const SizedBox(height: 10), Row( children: [ FollowCount( count: user.following.length, text: 'Following', ), const SizedBox(width: 15), FollowCount( count: user.followers.length, text: 'Followers', ), ], ), const SizedBox(height: 2), const Divider(color: Pallete.whiteColor), ], ), ), ), ]; }, body: ref.watch(getUserTweetsProvider(user.uid)).when( data: (tweets) { // can make it realtime by copying code // from twitter_reply_view return ref.watch(getLatestTweetProvider).when( data: (data) { if (data.events.contains( 'databases.*.collections.${AppwriteConstants.tweetsCollection}.documents.*.create', )) { tweets.insert(0, Tweet.fromMap(data.payload)); } else if (data.events.contains( 'databases.*.collections.${AppwriteConstants.tweetsCollection}.documents.*.update', )) { if (kDebugMode) { print("data events: ${data.events[0]}"); } final startingPoint = data.events[0].lastIndexOf('documents.'); final endPoint = data.events[0].lastIndexOf('.update'); if (kDebugMode) { print("starting point $startingPoint endpoint $endPoint"); } final tweetId = data.events[0].substring(startingPoint + 10, endPoint); if (kDebugMode) { print('get tweet id $tweetId'); } var tweet = tweets.where((element) => element.id == tweetId).first; final tweetIndex = tweets.indexOf(tweet); tweets.removeWhere((element) => element.id == tweetId); tweet = Tweet.fromMap(data.payload); tweets.insert(tweetIndex, tweet); } else { if (kDebugMode) { print('dataevents1'); } if (kDebugMode) { print("data events: ${data.events[0]}"); } final startingPoint = data.events[0].lastIndexOf('documents.'); final endPoint = data.events[0].lastIndexOf('.update'); if (kDebugMode) { print("starting point $startingPoint endpoint $endPoint"); } } // print("View tweets view data2}"); return ListView.builder( itemCount: tweets.length, itemBuilder: (BuildContext context, int index) { final tweet = tweets[index]; return TweetCard(tweet: tweet); }, ); }, error: (error, stackTrace) => ErrorText( error: "$error $stackTrace", ), loading: () { return ListView.builder( itemCount: tweets.length, itemBuilder: (BuildContext context, int index) { final tweet = tweets[index]; return TweetCard(tweet: tweet); }, ); }); }, error: (error, st) => ErrorText( error: error.toString(), ), loading: () => const LoadingPage(), ), ); } }
0
mirrored_repositories/x/lib/features/profile
mirrored_repositories/x/lib/features/profile/widget/follow_count.dart
import 'package:flutter/material.dart'; import 'package:x/theme/pallete.dart'; class FollowCount extends StatelessWidget { final int count; final String text; const FollowCount({ Key? key, required this.count, required this.text, }) : super(key: key); @override Widget build(BuildContext context) { double fontSize = 18; return Row( children: [ Text( '$count', style: TextStyle( color: Pallete.whiteColor, fontSize: fontSize, fontWeight: FontWeight.bold, ), ), const SizedBox(width: 3), Text( text, style: TextStyle( color: Pallete.greyColor, fontSize: fontSize, ), ), ], ); } }
0
mirrored_repositories/x/lib/features/profile
mirrored_repositories/x/lib/features/profile/controller/profile_controller.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:x/common/common.dart'; import 'package:x/core/enum/notification_type_enum.dart'; import 'package:x/features/notification/controller/notification_controller.dart'; import 'package:x/model/tweet.dart'; import 'package:x/model/user.dart'; import 'package:x/repository/storage_api.dart'; import 'package:x/repository/tweet_api.dart'; import 'package:x/repository/user_api.dart'; final userProfileControllerProvider = StateNotifierProvider<UserProfileController, bool>((ref) { return UserProfileController( tweetAPI: ref.watch(tweetAPIProvider), storageAPI: ref.watch(storageAPIProvider), userAPI: ref.watch(userAPIProvider), notificationController: ref.watch(notificationControllerProvider.notifier), ); }); final getUserTweetsProvider = FutureProvider.family((ref, String uid) async { final userProfileController = ref.watch(userProfileControllerProvider.notifier); return userProfileController.getUserTweets(uid); }); final getLatestUserProfileDataProvider = StreamProvider((ref) { final userAPI = ref.watch(userAPIProvider); print("getLatestUserProfileDataProvider" + userAPI.getLatestUserProfileData().toList().toString()); return userAPI.getLatestUserProfileData(); }); class UserProfileController extends StateNotifier<bool> { final TweetAPI _tweetAPI; final StorageAPI _storageAPI; final UserAPI _userAPI; final NotificationController _notificationController; UserProfileController({ required TweetAPI tweetAPI, required StorageAPI storageAPI, required UserAPI userAPI, required NotificationController notificationController, }) : _tweetAPI = tweetAPI, _storageAPI = storageAPI, _userAPI = userAPI, _notificationController = notificationController, super(false); Future<List<Tweet>> getUserTweets(String uid) async { final tweets = await _tweetAPI.getUserTweets(uid); return tweets.map((e) => Tweet.fromMap(e.data)).toList(); } void updateUserProfile({ required UserModel userModel, required BuildContext context, required File? bannerFile, required File? profileFile, }) async { state = true; if (bannerFile != null) { final bannerUrl = await _storageAPI.uploadImage([bannerFile]); userModel = userModel.copyWith( bannerPic: bannerUrl[0], ); } if (profileFile != null) { final profileUrl = await _storageAPI.uploadImage([profileFile]); userModel = userModel.copyWith( profilePic: profileUrl[0], ); } final res = await _userAPI.updateUserData(userModel); state = false; res.fold( (l) => showSnackBar(context, l.message), (r) => Navigator.pop(context), ); } void followUser({ required UserModel user, required BuildContext context, required UserModel currentUser, }) async { bool isFollowing = false; // already following if (currentUser.following.contains(user.uid)) { user.followers.remove(currentUser.uid); currentUser.following.remove(user.uid); isFollowing = false; } else { user.followers.add(currentUser.uid); currentUser.following.add(user.uid); isFollowing = true; } user = user.copyWith(followers: user.followers); currentUser = currentUser.copyWith( following: currentUser.following, ); final res = await _userAPI.followUser(user); res.fold((l){ print("Error followUser _userAPI.followUser ${l.stackTrace}"); showSnackBar(context, l.message); }, (r) async { final res2 = await _userAPI.addToFollowing(currentUser); res2.fold((l) {showSnackBar(context, l.message);}, (r) async { var textFollow = "${currentUser.name} "; isFollowing ? textFollow += "Following you" : textFollow += "Unfollow you"; await _notificationController.createNotification( text: textFollow, postId: '', notificationType: NotificationType.follow, uid: user.uid, ); }); }); } }
0
mirrored_repositories/x/lib/features/auth
mirrored_repositories/x/lib/features/auth/view/login_view.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:x/common/common.dart'; import 'package:x/features/auth/widgets/auth_field.dart'; import 'package:x/constants/constants.dart'; import 'package:x/features/auth/controller/auth_controller.dart'; import 'package:x/features/auth/view/signup_view.dart'; import 'package:x/theme/pallete.dart'; class LoginView extends ConsumerStatefulWidget { static route() => MaterialPageRoute( builder: (context) => const LoginView(), ); const LoginView({Key? key}) : super(key: key); @override ConsumerState<LoginView> createState() => _LoginViewState(); } class _LoginViewState extends ConsumerState<LoginView> { final appBar = UIConstants.appBar(); final emailController = TextEditingController(); final passwordController = TextEditingController(); @override void dispose() { emailController.dispose(); passwordController.dispose(); super.dispose(); } Future onLogin() async { ref.read(authControllerProvider.notifier).login( email: emailController.text, password: passwordController.text, context: context); // ref.read(authControllerProvider.notifier).currentUser(); } @override Widget build(BuildContext context) { final isLoading = ref.watch(authControllerProvider); return Scaffold( appBar: appBar, body: isLoading ? const LoadingWidget() : Center( child: SingleChildScrollView( child: Padding( padding: PaddingConstant.paddingHorizontal25, child: Column( children: [ AuthField( controller: emailController, hintText: 'Email', ), const SizedBox(height: 25), AuthField( controller: passwordController, hintText: 'Password', ), const SizedBox(height: 40), Align( alignment: Alignment.topRight, child: RoundedSmallButton( onTap: onLogin, label: 'Done', ), ), const SizedBox(height: 40), RichText( text: TextSpan( text: "Don't have an account?", style: const TextStyle( fontSize: 16, ), children: [ TextSpan( text: ' Sign up', style: const TextStyle( color: Pallete.blueColor, fontSize: 16, ), recognizer: TapGestureRecognizer() ..onTap = () { Navigator.push(context, SignUpView.route()); }, ), ], ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/x/lib/features/auth
mirrored_repositories/x/lib/features/auth/view/signup_view.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:x/common/common.dart'; import 'package:x/features/auth/widgets/auth_field.dart'; import 'package:x/constants/constants.dart'; import 'package:x/features/auth/controller/auth_controller.dart'; import 'package:x/theme/pallete.dart'; import 'login_view.dart'; class SignUpView extends ConsumerStatefulWidget { static route() => MaterialPageRoute( builder: (context) => const SignUpView(), ); const SignUpView({super.key}); @override ConsumerState<SignUpView> createState() => _SignUpViewState(); } class _SignUpViewState extends ConsumerState<SignUpView> { final appbar = UIConstants.appBar(); final emailController = TextEditingController(); final passwordController = TextEditingController(); @override void dispose() { super.dispose(); emailController.dispose(); passwordController.dispose(); } void onSignUp() { // notifier used for access method ref.read(authControllerProvider.notifier).signUp( email: emailController.text, password: passwordController.text, context: context); } @override Widget build(BuildContext context) { final isLoading = ref.watch(authControllerProvider); return Scaffold( appBar: appbar, body: isLoading ? const LoadingWidget() :Center( child: SingleChildScrollView( child: Padding( padding: PaddingConstant.paddingHorizontal25, child: Column( children: [ AuthField( controller: emailController, hintText: 'Email', ), const SizedBox(height: 25), AuthField( controller: passwordController, hintText: 'Password', ), const SizedBox(height: 40), Align( alignment: Alignment.topRight, child: RoundedSmallButton( onTap: onSignUp, label: 'Done', ), ), const SizedBox(height: 40), RichText( text: TextSpan( text: "Already have an account?", style: const TextStyle( fontSize: 16, ), children: [ TextSpan( text: ' Login', style: const TextStyle( color: Pallete.blueColor, fontSize: 16, ), recognizer: TapGestureRecognizer() ..onTap = () { Navigator.push( context, LoginView.route(), ); }, ), ], ), ), ], ), ), ), )); } }
0
mirrored_repositories/x/lib/features/auth
mirrored_repositories/x/lib/features/auth/widgets/auth_field.dart
import 'package:flutter/material.dart'; import 'package:x/common/size/ruler.dart'; import 'package:x/theme/pallete.dart'; class AuthField extends StatelessWidget { final TextEditingController controller; final String hintText; const AuthField({Key? key, required this.controller, required this.hintText}) : super(key: key); @override Widget build(BuildContext context) { return TextFormField( controller: controller, decoration: InputDecoration( focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(5), borderSide: const BorderSide( color: Pallete.blueColor, width: 3, ), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(5), borderSide: const BorderSide( color: Pallete.greyColor, ), ), contentPadding: PaddingConstant.paddingAll25, hintText: hintText, hintStyle: const TextStyle( fontSize: 18, ), ), ); } }
0
mirrored_repositories/x/lib/features/auth
mirrored_repositories/x/lib/features/auth/controller/auth_controller.dart
import 'package:appwrite/models.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:x/common/widgets/utils_widget.dart'; import 'package:x/features/auth/view/login_view.dart'; import 'package:x/features/auth/view/signup_view.dart'; import 'package:x/features/home/view/home_view.dart'; import 'package:x/model/user.dart'; import 'package:x/repository/auth_api.dart'; import 'package:x/repository/user_api.dart'; final authControllerProvider = StateNotifierProvider<AuthController, bool>((ref) { return AuthController( authAPI: ref.watch(authAPIProvider), userAPI: ref.watch(userAPIProvider), ); }); // final currentUserAccountProvider = FutureProvider((ref) { // final authController = ref.watch(authControllerProvider.notifier); // print("currentUserAccountProvider: ### Gettt ${authController} it is"); // // // print("currentUserProvider: ${authController.currentUser().email} id: ${authController.currentUser().$id}"); // // // UserModel user = ref.watch(currentUserDetailsProvider); // return authController.currentUser(); // }); final currentUserDetailsProvider = FutureProvider((ref) { final userFirstFetch = ref.watch(authControllerProvider.notifier).usermodel; String? currentUserId; if(userFirstFetch != null){ currentUserId = userFirstFetch.$id; ref.watch(currentUserAccountProvider).value; }else{ currentUserId = ref.watch(currentUserAccountProvider).value!.$id; } final userDetails = ref.watch(userDetailsProvider(currentUserId)); return userDetails.value; }); final userDetailsProvider = FutureProvider.family((ref, String uid) { final authController = ref.watch(authControllerProvider.notifier); return authController.getUserData(uid); }); final currentUserAccountProvider = FutureProvider((ref) { final authController = ref.watch(authControllerProvider.notifier); return authController.currentUser(); }); class AuthController extends StateNotifier<bool> { final AuthAPI _authAPI; final UserAPI _userAPI; User? usermodel; AuthController({ required AuthAPI authAPI, required UserAPI userAPI, }) : _authAPI = authAPI, _userAPI = userAPI, super(false); // state = isLoading void signUp({ required String email, required String password, required BuildContext context, }) async { state = true; final res = await _authAPI.signUp( email: email, password: password, ); state = false; res.fold( (l) => showSnackBar(context, l.message), (r) async { UserModel userModel = UserModel( email: email, name: getNameFromEmail(email), followers: const [], following: const [], profilePic: '', bannerPic: '', uid: r.$id, bio: '', isTwitterBlue: false, ); final res2 = await _userAPI.saveUserData(userModel); res2.fold((l) => showSnackBar(context, l.message), (r) { showSnackBar(context, 'Accounted created! Please login.'); Navigator.push(context, LoginView.route()); }); }, ); } void login( {required String email, required String password, required BuildContext context}) async { state = true; final res = await _authAPI.login(email: email, password: password); state = false; res.fold((l) => showSnackBar(context, l.message), (r) async { usermodel = await currentUser(); if (!context.mounted) return; if(usermodel != null){ showSnackBar(context, 'Successfully Login'); Navigator.push(context, HomeView.route()); }else{ showSnackBar(context, 'Failed Login'); } }); } Future<User?> currentUser() async { return await _authAPI.currentUserAccount(); } void logout(BuildContext context) async { final res = await _authAPI.logout(); res.fold((l) => null, (r) { Navigator.pushAndRemoveUntil( context, SignUpView.route(), (route) => false, ); }); } Future<UserModel> getUserData(String uid) async { final document = await _userAPI.getUserData(uid); print("get user data from auth controller \n ${document.data}"); final updatedUser = UserModel.fromMap(document.data); return updatedUser; } }
0
mirrored_repositories/x/lib/features/home
mirrored_repositories/x/lib/features/home/view/home_view.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:x/constants/constants.dart'; import 'package:x/features/home/widgets/side_drawer.dart'; import 'package:x/features/tweet/view/create_tweet_view.dart'; import 'package:x/theme/theme.dart'; class HomeView extends StatefulWidget { static route() => MaterialPageRoute(builder: (context) => const HomeView()); const HomeView({super.key}); @override State<HomeView> createState() => _HomeViewState(); } class _HomeViewState extends State<HomeView> { final _appBar = UIConstants.appBar(); int _page = 0; void onPageChange(int index) { setState(() { _page = index; }); } onCreateTweet(){ Navigator.push(context, CreateTweetView.route()); } BottomNavigationBarItem bottomNavigationBarItem(bool isSelected, {required String filledIcon, required String outlineIcon}) { return BottomNavigationBarItem( icon: SvgPicture.asset( isSelected ? filledIcon : outlineIcon, colorFilter: const ColorFilter.mode(Pallete.whiteColor, BlendMode.srcIn), )); } @override Widget build(BuildContext context) { return Scaffold( appBar: _page == 0 ? _appBar : null, drawer: const SideDrawer(), body: IndexedStack( index: _page, children: UIConstants.bottomTabBarPages, ), floatingActionButton: FloatingActionButton( onPressed: onCreateTweet, child: const Icon( Icons.add, color: Pallete.whiteColor, size: 28, ), ), bottomNavigationBar: CupertinoTabBar( height: MediaQuery.of(context).size.height * 0.05, onTap: onPageChange, currentIndex: _page, backgroundColor: Pallete.backgroundColor, items: [ bottomNavigationBarItem(_page == 0, filledIcon: AssetsConstants.homeFilledIcon, outlineIcon: AssetsConstants.homeOutlinedIcon), bottomNavigationBarItem(false, filledIcon: AssetsConstants.searchIcon, outlineIcon: AssetsConstants.searchIcon,), bottomNavigationBarItem(_page == 2, filledIcon: AssetsConstants.notifFilledIcon, outlineIcon: AssetsConstants.notifOutlinedIcon,), ], ), ); } }
0
mirrored_repositories/x/lib/features/home
mirrored_repositories/x/lib/features/home/widgets/side_drawer.dart
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:x/common/common.dart'; import 'package:x/constants/constants.dart'; import 'package:x/features/auth/controller/auth_controller.dart'; import 'package:x/features/profile/controller/profile_controller.dart'; import 'package:x/features/profile/view/user_profile_view.dart'; import 'package:x/theme/pallete.dart'; class SideDrawer extends ConsumerWidget { const SideDrawer({ Key? key, }) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { final currentUser = ref.watch(currentUserDetailsProvider).value; if (currentUser == null) { return const LoadingWidget(); } return SafeArea( child: Drawer( backgroundColor: Pallete.backgroundColor, child: Column( children: [ const SizedBox(height: 50), ListTile( leading: const Icon( Icons.person, size: 30, ), title: const Text( 'My Profile', style: TextStyle( fontSize: 22, ), ), onTap: () { Navigator.push( context, UserProfileView.route(currentUser), ); }, ), ListTile( leading: SvgPicture.asset( AssetsConstants.twitterLogo, height: 30, colorFilter: const ColorFilter.mode(Pallete.whiteColor, BlendMode.srcIn), ), title: const Text( 'Twitter Blue', style: TextStyle( fontSize: 22, ), ), onTap: () { ref .read(userProfileControllerProvider.notifier) .updateUserProfile( userModel: currentUser.copyWith(isTwitterBlue: true), context: context, bannerFile: null, profileFile: null, ); }, ), ListTile( leading: const Icon( Icons.logout, size: 30, ), title: const Text( 'Log Out', style: TextStyle( fontSize: 22, ), ), onTap: () { ref.read(authControllerProvider.notifier).logout(context); }, ), ], ), ), ); } }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/model/tweet.dart
import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:x/core/core.dart'; class Tweet { final String text; final List<String> hashtags; final String link; final List<String> imageLinks; final String uid; final TweetType tweetType; final DateTime tweetedAt; final List<String> likes; final List<String> commentIds; final String id; final int reshareCount; final String retweetedBy; final String repliedTo; Tweet({ required this.text, required this.hashtags, required this.link, required this.imageLinks, required this.uid, required this.tweetType, required this.tweetedAt, required this.likes, required this.commentIds, required this.id, required this.reshareCount, required this.retweetedBy, required this.repliedTo, }); Tweet copyWith({ String? text, List<String>? hashtags, String? link, List<String>? imageLinks, String? uid, TweetType? tweetType, DateTime? tweetedAt, List<String>? likes, List<String>? commentIds, String? id, int? reshareCount, String? retweetedBy, String? repliedTo, }) { return Tweet( text: text ?? this.text, hashtags: hashtags ?? this.hashtags, link: link ?? this.link, imageLinks: imageLinks ?? this.imageLinks, uid: uid ?? this.uid, tweetType: tweetType ?? this.tweetType, tweetedAt: tweetedAt ?? this.tweetedAt, likes: likes ?? this.likes, commentIds: commentIds ?? this.commentIds, id: id ?? this.id, reshareCount: reshareCount ?? this.reshareCount, retweetedBy: retweetedBy ?? this.retweetedBy, repliedTo: repliedTo ?? this.repliedTo, ); } Map<String, dynamic> toMap() { return { 'text': text, 'hashtags': hashtags, 'link': link, 'imageLinks': imageLinks, 'uid': uid, 'tweetType': tweetType.type, 'tweetedAt': tweetedAt.millisecondsSinceEpoch, 'likes': likes, 'commentIds': commentIds, 'id': id, 'reshareCount': reshareCount, 'retweetedBy': retweetedBy, 'repliedTo': repliedTo, }; } factory Tweet.fromMap(Map<String, dynamic> map) { return Tweet( text: map['text'] ?? '', hashtags: List<String>.from(map['hashtags']), link: map['link'] ?? '', imageLinks: List<String>.from(map['imageLinks']), uid: map['uid'] ?? '', tweetType: (map['tweetType'] as String).toTweetTypeEnum(), tweetedAt: DateTime.fromMillisecondsSinceEpoch(map['tweetedAt']), likes: List<String>.from(map['likes']), commentIds: List<String>.from(map['commentIds']), id: map['\$id'] ?? '', reshareCount: map['reshareCount']?.toInt() ?? 0, retweetedBy: map['retweetedBy'] ?? '', repliedTo: map['repliedTo'] ?? '', ); } String toJson() => json.encode(toMap()); factory Tweet.fromJson(String source) => Tweet.fromMap(json.decode(source)); @override String toString() { return 'Tweet(text: $text, hashtags: $hashtags, link: $link, imageLinks: $imageLinks, uid: $uid, tweetType: $tweetType, tweetedAt: $tweetedAt, likes: $likes, commentIds: $commentIds, id: $id, reshareCount: $reshareCount, retweetedBy: $retweetedBy, repliedTo: $repliedTo)'; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is Tweet && other.text == text && listEquals(other.hashtags, hashtags) && other.link == link && listEquals(other.imageLinks, imageLinks) && other.uid == uid && other.tweetType == tweetType && other.tweetedAt == tweetedAt && listEquals(other.likes, likes) && listEquals(other.commentIds, commentIds) && other.id == id && other.reshareCount == reshareCount && other.retweetedBy == retweetedBy && other.repliedTo == repliedTo; } @override int get hashCode { return text.hashCode ^ hashtags.hashCode ^ link.hashCode ^ imageLinks.hashCode ^ uid.hashCode ^ tweetType.hashCode ^ tweetedAt.hashCode ^ likes.hashCode ^ commentIds.hashCode ^ id.hashCode ^ reshareCount.hashCode ^ retweetedBy.hashCode ^ repliedTo.hashCode; } }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/model/notification.dart
import 'dart:convert'; import 'package:x/core/enum/notification_type_enum.dart'; class Notification { final String text; final String postId; final String id; final String uid; final NotificationType notificationType; Notification({ required this.text, required this.postId, required this.id, required this.uid, required this.notificationType, }); Notification copyWith({ String? text, String? postId, String? id, String? uid, NotificationType? notificationType, }) { return Notification( text: text ?? this.text, postId: postId ?? this.postId, id: id ?? this.id, uid: uid ?? this.uid, notificationType: notificationType ?? this.notificationType, ); } Map<String, dynamic> toMap() { return { 'text': text, 'postId': postId, 'id': id, 'uid': uid, 'notificationType': notificationType.type, }; } factory Notification.fromMap(Map<String, dynamic> map) { return Notification( text: map['text'] ?? '', postId: map['postId'] ?? '', id: map['id'] ?? '', uid: map['uid'] ?? '', notificationType: (map['notificationType'] as String).toNotificationTypeEnum(), ); } String toJson() => json.encode(toMap()); factory Notification.fromJson(String source) => Notification.fromMap(json.decode(source)); @override String toString() { return 'Notification(text: $text, postId: $postId, id: $id, uid: $uid, notificationType: $notificationType)'; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is Notification && other.text == text && other.postId == postId && other.id == id && other.uid == uid && other.notificationType == notificationType; } @override int get hashCode { return text.hashCode ^ postId.hashCode ^ id.hashCode ^ uid.hashCode ^ notificationType.hashCode; } }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/model/user.dart
import 'dart:convert'; import 'package:flutter/foundation.dart'; class UserModel { final String email; final String name; final List<String> followers; final List<String> following; final String profilePic; final String bannerPic; String uid; final String bio; final bool isTwitterBlue; UserModel({ required this.email, required this.name, required this.followers, required this.following, required this.profilePic, required this.bannerPic, required this.uid, required this.bio, required this.isTwitterBlue, }); UserModel copyWith({ String? email, String? name, List<String>? followers, List<String>? following, String? profilePic, String? bannerPic, String? uid, String? bio, bool? isTwitterBlue, }) { return UserModel( email: email ?? this.email, name: name ?? this.name, followers: followers ?? this.followers, following: following ?? this.following, profilePic: profilePic ?? this.profilePic, bannerPic: bannerPic ?? this.bannerPic, uid: uid ?? this.uid, bio: bio ?? this.bio, isTwitterBlue: isTwitterBlue ?? this.isTwitterBlue, ); } Map<String, dynamic> toMap() { final map = { 'email': email, 'name': name, 'followers': followers, 'following': following, 'profilePic': profilePic, 'bannerPic': bannerPic, 'bio': bio, 'isTwitterBlue': isTwitterBlue, }; // if (uid != null) { // map['uid'] = uid!; // } return map; } factory UserModel.fromMap(Map<String, dynamic> map) { return UserModel( email: map['email'] ?? '', name: map['name'] ?? '', followers: List<String>.from(map['followers']), following: List<String>.from(map['following']), profilePic: map['profilePic'] ?? '', bannerPic: map['bannerPic'] ?? '', uid: map['\$id'], bio: map['bio'] ?? '', isTwitterBlue: map['isTwitterBlue'] ?? false, ); } String toJson() => json.encode(toMap()); factory UserModel.fromJson(String source) => UserModel.fromMap(json.decode(source)); @override String toString() { return 'UserModel(email: $email, name: $name, followers: $followers, following: $following, profilePic: $profilePic, bannerPic: $bannerPic, uid: $uid, bio: $bio, isTwitterBlue: $isTwitterBlue)'; } }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/core/core.dart
export './failure.dart'; export './type_defs.dart'; export './enum/tweet_enum.dart'; export './service_locator.dart';
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/core/failure.dart
class Failure { final String message; final StackTrace stackTrace; Failure({required this.message, required this.stackTrace}); }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/core/type_defs.dart
import 'package:fpdart/fpdart.dart'; import 'package:x/core/failure.dart'; typedef FutureEither<T> = Future<Either<Failure, T>>; typedef FutureEitherVoid = FutureEither<void>;
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/core/service_locator.dart
import 'package:appwrite/appwrite.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:get_it/get_it.dart'; import 'package:x/constants/appwrite_constants.dart'; import 'package:x/contracts/appwrite_contract.dart'; GetIt injector = GetIt.instance; Future setUpDependencies() async { injector .registerLazySingleton<AppwriteServiceContract>(() => AppWriteService()); } final appWriteService = injector.get<AppwriteServiceContract>(); final appWriteClientProvider = Provider((ref){ String used = ''; String endpoint; if(kIsWeb){ endpoint = AppwriteConstants.endPointWeb; used = "Connect via web"; }else{ endpoint = AppwriteConstants.endPointMobile; used = "Connect via mobile"; } print("Trying to $used"); return Client() .setEndpoint(endpoint) .setProject(AppwriteConstants.projectId) .setSelfSigned(status: true); }); // watch is continiously, read is for once final appWriteAccountProvider = Provider((ref) => Account(ref.watch(appWriteClientProvider))); final appwriteDatabaseProvider = Provider((ref) { final client = ref.watch(appWriteClientProvider); return Databases(client); }); final appwriteStorageProvider = Provider((ref) { final client = ref.watch(appWriteClientProvider); return Storage(client); }); final appwriteRealtimeProvider = Provider((ref) { final client = ref.watch(appWriteClientProvider); return Realtime(client); }); final appwriteRealtimeProvider2 = Provider((ref) { final client = ref.watch(appWriteClientProvider); return Realtime(client); }); final appwriteRealtimeProvider3 = Provider((ref) { final client = ref.watch(appWriteClientProvider); return Realtime(client); });
0
mirrored_repositories/x/lib/core
mirrored_repositories/x/lib/core/enum/tweet_enum.dart
enum TweetType { text('text'), image('image'); final String type; const TweetType(this.type); } extension ConvertTweet on String { TweetType toTweetTypeEnum() { switch (this) { case 'text': return TweetType.text; case 'image': return TweetType.image; default: return TweetType.text; } } }
0
mirrored_repositories/x/lib/core
mirrored_repositories/x/lib/core/enum/string_enum.dart
extension ReplaceHost on String { String replaceHostIP() { return replaceAll('http://127.0.0.1', 'http://172.29.112.1'); } }
0
mirrored_repositories/x/lib/core
mirrored_repositories/x/lib/core/enum/notification_type_enum.dart
enum NotificationType { like('like'), reply('reply'), follow('follow'), retweet('retweet'); final String type; const NotificationType(this.type); } extension ConvertTweet on String { NotificationType toNotificationTypeEnum() { switch (this) { case 'retweet': return NotificationType.retweet; case 'follow': return NotificationType.follow; case 'reply': return NotificationType.reply; default: return NotificationType.like; } } }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/theme/app_theme.dart
import 'package:flutter/material.dart'; import 'theme.dart'; class AppTheme { static ThemeData theme = ThemeData.dark().copyWith( scaffoldBackgroundColor: Pallete.backgroundColor, appBarTheme: const AppBarTheme( backgroundColor: Pallete.backgroundColor, elevation: 0, ), floatingActionButtonTheme: const FloatingActionButtonThemeData( backgroundColor: Pallete.blueColor, ), ); }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/theme/pallete.dart
import 'package:flutter/material.dart'; class Pallete { static const Color backgroundColor = Colors.black; static const Color searchBarColor = Color.fromRGBO(32, 35, 39, 1); static const Color blueColor = Color.fromRGBO(29, 155, 240, 1); static const Color whiteColor = Colors.white; static const Color greyColor = Colors.grey; static const Color redColor = Color.fromRGBO(249, 25, 127, 1); }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/theme/theme.dart
export './app_theme.dart'; export './pallete.dart';
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/common/common.dart
export 'package:x/common/size/ruler.dart'; export 'package:x/common/widgets/acommon_widget.dart';
0
mirrored_repositories/x/lib/common
mirrored_repositories/x/lib/common/widgets/rounded_small_button.dart
import 'package:flutter/material.dart'; import 'package:x/theme/pallete.dart'; class RoundedSmallButton extends StatelessWidget { final VoidCallback onTap; final String label; final Color backgroundColor; final Color textColor; const RoundedSmallButton({ super.key, required this.onTap, required this.label, this.backgroundColor = Pallete.whiteColor, this.textColor = Pallete.backgroundColor, }); @override Widget build(BuildContext context) { return InkWell( onTap: onTap, child: Chip( label: Text( label, style: TextStyle( color: textColor, fontSize: 16, ), ), backgroundColor: backgroundColor, labelPadding: const EdgeInsets.symmetric( horizontal: 20, vertical: 5, ), ), ); } }
0
mirrored_repositories/x/lib/common
mirrored_repositories/x/lib/common/widgets/acommon_widget.dart
export './rounded_small_button.dart'; export './loading_widget.dart'; export './utils_widget.dart'; export './error_page.dart';
0
mirrored_repositories/x/lib/common
mirrored_repositories/x/lib/common/widgets/loading_widget.dart
import 'package:flutter/material.dart'; class LoadingWidget extends StatelessWidget { const LoadingWidget({super.key}); @override Widget build(BuildContext context) { return const Center( child: CircularProgressIndicator(), ); } } class LoadingPage extends StatelessWidget { const LoadingPage({super.key}); @override Widget build(BuildContext context) { return const Scaffold( body: LoadingWidget(), ); } }
0
mirrored_repositories/x/lib/common
mirrored_repositories/x/lib/common/widgets/error_page.dart
import 'package:flutter/material.dart'; class ErrorText extends StatelessWidget { final String error; const ErrorText({super.key, required this.error}); @override Widget build(BuildContext context) { return Center( child: Text(error), ); } } class ErrorPage extends StatelessWidget { final String error; const ErrorPage({super.key, required this.error}); @override Widget build(BuildContext context) { return Scaffold( body: ErrorText(error: error), ); } }
0
mirrored_repositories/x/lib/common
mirrored_repositories/x/lib/common/widgets/utils_widget.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; void showSnackBar(BuildContext context, String content) { ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(content))); } String getNameFromEmail(String email) { // tes@gmail // list = [tes, gmail] // list[0] = tes return email.split('@')[0]; } Future<List<File>> pickImages() async { List<File> images = []; final ImagePicker picker = ImagePicker(); final imageFiles = await picker.pickMultiImage(); if (imageFiles.isNotEmpty) { for (final image in imageFiles) { images.add(File(image.path)); } } return images; } Future<File?> pickImage() async { final ImagePicker picker = ImagePicker(); final imageFile = await picker.pickImage(source: ImageSource.gallery); if (imageFile != null) { return File(imageFile.path); } return null; }
0
mirrored_repositories/x/lib/common
mirrored_repositories/x/lib/common/size/ruler.dart
import 'package:flutter/material.dart'; class PaddingConstant { static const paddingHorizontal25 = EdgeInsets.symmetric(horizontal: 25); static const paddingAll25 = EdgeInsets.all(25); static const paddingAll16 = EdgeInsets.all(16); static const paddingBottom10 = EdgeInsets.only(bottom: 10); } class MarginConstant { static const marginHorizontal5 = EdgeInsets.symmetric( horizontal: 5, ); static const marginAll8 = EdgeInsets.all( 8 ); }
0
mirrored_repositories/x/lib
mirrored_repositories/x/lib/contracts/appwrite_contract.dart
import 'package:appwrite/appwrite.dart'; abstract class AppwriteServiceContract { Client init(); } class AppWriteService implements AppwriteServiceContract { late Client client; AppWriteService() { client = Client() .setEndpoint('http://127.0.0.1:885/v1') .setProject('650aa6c4a35400770ff0'); } @override Client init() { return client; } }
0
mirrored_repositories/x
mirrored_repositories/x/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility in the flutter_test package. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:x/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Flutter-Folding-Cell-Sample
mirrored_repositories/Flutter-Folding-Cell-Sample/lib/soccer_player_details.dart
class SoccerPlayerDetails{ String playerImg; String playerName; String playingPosition; String clubName; String countryName; SoccerPlayerDetails(this.playerImg, this.playerName, this.playingPosition, this.clubName, this.countryName); }
0
mirrored_repositories/Flutter-Folding-Cell-Sample
mirrored_repositories/Flutter-Folding-Cell-Sample/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutterfoldingcellsample/my_folding_cell_screen.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: MyFoldingCellScreen(), ); } }
0
mirrored_repositories/Flutter-Folding-Cell-Sample
mirrored_repositories/Flutter-Folding-Cell-Sample/lib/my_folding_cell_screen.dart
import 'package:flutter/material.dart'; import 'package:flutterfoldingcellsample/soccer_player_details.dart'; import 'package:folding_cell/folding_cell.dart'; class MyFoldingCellScreen extends StatefulWidget { @override _MyFoldingCellScreenState createState() => _MyFoldingCellScreenState(); } class _MyFoldingCellScreenState extends State<MyFoldingCellScreen> { List<SoccerPlayerDetails> listSoccerPlayerDetails; @override void initState() { super.initState(); listSoccerPlayerDetails = [ SoccerPlayerDetails( "https://resources.premierleague.com/premierleague/photos/players/40×40/p14937.png", "Cristiano Ronaldo", "Forward", "Manchester United", "Portugal"), SoccerPlayerDetails( "https://resources.premierleague.com/premierleague/photos/players/40×40/p78830.png", "Harry Kane", "Forward", "Tottenham Hotspur", "England"), SoccerPlayerDetails( "https://resources.premierleague.com/premierleague/photos/players/40×40/p61366.png", "Kevin De Bruyne", "Midfielder", "Manchester City", "Belgium"), SoccerPlayerDetails( "https://resources.premierleague.com/premierleague/photos/players/40×40/p101668.png", "Jamie Vardy", "Forward", "Leicester City", "England"), SoccerPlayerDetails( "https://resources.premierleague.com/premierleague/photos/players/40×40/p97032.png", "Virgil van Dijk", "Defender", "Liverpool", "Netherlands"), ]; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Flutter Folding Cell Sample')), body: Container( child: ListView.builder( itemCount: listSoccerPlayerDetails.length, itemBuilder: (context, index) { return SimpleFoldingCell.create( padding: EdgeInsets.all(12), borderRadius: 12, frontWidget: buildListWidget(index), innerWidget: buildDetailsWidget(index), cellSize: Size(MediaQuery.of(context).size.width, 125), animationDuration: Duration(milliseconds: 200), onOpen: () {}, onClose: () {}, ); }, ), ), ); } Widget buildListWidget(int index) { var getSoccerPlayerDetails = listSoccerPlayerDetails[index]; return Builder( builder: (BuildContext context) { return Container( color: Colors.orangeAccent, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( getSoccerPlayerDetails.playerName, style: TextStyle( fontSize: 25, fontWeight: FontWeight.bold, color: Colors.white ), ), SizedBox(height: 15), ElevatedButton( child: Text("Expand", style: TextStyle(color: Colors.orangeAccent, fontSize: 22)), style: ElevatedButton.styleFrom( primary: Colors.white, ), onPressed: () { final foldingCellState = context.findAncestorStateOfType<SimpleFoldingCellState>(); foldingCellState?.toggleFold(); }, ), ], ), ); }, ); } Widget buildDetailsWidget(int index) { var getSoccerPlayerDetails = listSoccerPlayerDetails[index]; return Builder( builder: (context) { return Container( color: Colors.pinkAccent, padding: EdgeInsets.all(12), child: Column( children: [ SizedBox(height: 15), Align( alignment: Alignment.center, child: Text( getSoccerPlayerDetails.playingPosition, style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 25, ), ), ), SizedBox(height: 15), Align( alignment: Alignment.center, child: Text( getSoccerPlayerDetails.clubName, style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 25, ), ), ), SizedBox(height: 15), Align( alignment: Alignment.center, child: Text( getSoccerPlayerDetails.countryName, style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 25, ), ), ), SizedBox(height: 25), ElevatedButton( child: Text("Shrink", style: TextStyle(color: Colors.pinkAccent, fontSize: 22)), style: ElevatedButton.styleFrom( primary: Colors.white, ), onPressed: () { final foldingCellState = context.findAncestorStateOfType<SimpleFoldingCellState>(); foldingCellState?.toggleFold(); }, ), ], ) ); }, ); } }
0
mirrored_repositories/Flutter-Folding-Cell-Sample
mirrored_repositories/Flutter-Folding-Cell-Sample/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutterfoldingcellsample/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/Flutter-Timer-with-GetX/flutter_simple_timer
mirrored_repositories/Flutter-Timer-with-GetX/flutter_simple_timer/lib/bindings.dart
import 'package:get/get.dart'; import '../controller/theme_controller.dart'; import '../controller/timer_controller.dart'; class MyBindings implements Bindings { @override void dependencies() { Get.lazyPut(() => TimerController()); Get.lazyPut(() => ThemeController()); } }
0
mirrored_repositories/Flutter-Timer-with-GetX/flutter_simple_timer
mirrored_repositories/Flutter-Timer-with-GetX/flutter_simple_timer/lib/main.dart
//CodeWithFlexz on Instagram //AmirBayat0 on Github //Programming with Flexz on Youtube import 'package:flutter/material.dart'; import 'package:get/get_navigation/src/root/get_material_app.dart'; // import '../bindings.dart'; import '../utils/themes.dart'; import 'view/final_view.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return GetMaterialApp( initialBinding: MyBindings(), debugShowCheckedModeBanner: false, title: 'Flutter Simple Timer', darkTheme: MyThemes.darkTheme, themeMode: ThemeMode.light, theme: MyThemes.lightTheme, home: const FinalView(), ); } }
0
mirrored_repositories/Flutter-Timer-with-GetX/flutter_simple_timer/lib
mirrored_repositories/Flutter-Timer-with-GetX/flutter_simple_timer/lib/view/final_view.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; // import '../components/buttons.dart'; import '../controller/theme_controller.dart'; import '../controller/timer_controller.dart'; class FinalView extends StatelessWidget { const FinalView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { var timerController = Get.find<TimerController>(); var themeController = Get.find<ThemeController>(); // var textTheme = Theme.of(context).textTheme; // var iconTheme = Theme.of(context).iconTheme; return Scaffold( appBar: const MyAppBar(), body: Container( margin: const EdgeInsets.all(10), width: Get.width, height: Get.height, child: GetBuilder<TimerController>( init: TimerController(), builder: (context) { return Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ /// Center Circle GetBuilder<ThemeController>( id: 1, builder: (context) { return Container( decoration: BoxDecoration( color: themeController.isDarkMode ? const Color.fromARGB(255, 21, 21, 21) : Colors.white, shape: BoxShape.circle, boxShadow: [ BoxShadow( blurRadius: 10.0, offset: const Offset(5, 5), color: themeController.isDarkMode ? Colors.black : const Color.fromARGB( 109, 144, 144, 144)), BoxShadow( blurRadius: 10.0, offset: const Offset(-5, -5), color: themeController.isDarkMode ? const Color.fromARGB(255, 27, 27, 27) : const Color.fromARGB( 255, 243, 243, 243)) ], ), width: 300, height: 300, child: Stack( fit: StackFit.expand, children: [ Padding( padding: const EdgeInsets.all(20), child: CircularProgressIndicator( strokeWidth: 12, valueColor: AlwaysStoppedAnimation( timerController.seconds == 60 ? Colors.green : Colors.red), backgroundColor: themeController.isDarkMode ? const Color.fromARGB(255, 34, 34, 34) : const Color.fromARGB( 255, 237, 237, 237), value: timerController.seconds / TimerController.maxSeconds, ), ), Center( child: Text( timerController.seconds.toString(), style: TextStyle( fontSize: 100, fontWeight: FontWeight.bold, color: timerController.isCompleted() ? const Color.fromARGB(255, 8, 123, 12) : const Color.fromARGB(255, 178, 14, 2), ), ), ), ], ), ); }), const SizedBox( height: 50, ), /// Buttons timerController.isTimerRuning() || !timerController.isCompleted() ? Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ ButtonWidget( onTap: () { timerController.isTimerRuning() ? timerController.stopTimer(rest: false) : timerController.startTimer(rest: false); }, text: timerController.isTimerRuning() ? "Pause" : "Resume", color: timerController.isTimerRuning() ? Colors.red : Colors.green, fontWeight: FontWeight.w400), ButtonWidget( onTap: () { timerController.stopTimer(rest: true); }, text: "Cancel", color: Colors.red, fontWeight: FontWeight.w600) ], ) : GetBuilder<ThemeController>( init: ThemeController(), id: 1, initState: (_) {}, builder: (_) { return ButtonWidget( onTap: () { timerController.startTimer(); }, text: "Start", color: themeController.isDarkMode ? Colors.white : Colors.black, fontWeight: FontWeight.w400, ); }, ), ], ); }), ), ); } } /// MyApp Bar class MyAppBar extends StatelessWidget with PreferredSizeWidget { const MyAppBar({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { var themeController = Get.find<ThemeController>(); var textTheme = Theme.of(context).textTheme; var iconTheme = Theme.of(context).iconTheme; return AppBar( title: Text("Timer", style: textTheme.headline1), backgroundColor: Colors.transparent, elevation: 0, actions: [ GetBuilder<ThemeController>( init: ThemeController(), id: 1, initState: (_) {}, builder: (_) { return IconButton( onPressed: () { themeController.changeThemeOfButtons(); themeController.isDarkMode ? Get.changeThemeMode(ThemeMode.dark) : Get.changeThemeMode(ThemeMode.light); }, icon: Icon( themeController.isDarkMode ? Icons.light_mode : Icons.dark_mode, color: iconTheme.color, size: iconTheme.size, )); }, ) ], ); } @override Size get preferredSize => const Size.fromHeight(65); }
0
mirrored_repositories/Flutter-Timer-with-GetX/flutter_simple_timer/lib
mirrored_repositories/Flutter-Timer-with-GetX/flutter_simple_timer/lib/components/buttons.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../controller/theme_controller.dart'; class ButtonWidget extends StatelessWidget { const ButtonWidget({ Key? key, required this.text, required this.onTap, required this.color, required this.fontWeight, }) : super(key: key); final String text; final Color color; final VoidCallback onTap; final FontWeight fontWeight; @override Widget build(BuildContext context) { var themeController = Get.find<ThemeController>(); return GestureDetector( onTap: onTap, child: GetBuilder<ThemeController>( id: 1, builder: (context) { return Container( width: Get.width / 5, height: Get.height / 14, decoration: BoxDecoration( color: themeController.isDarkMode ? const Color.fromARGB(255, 21, 21, 21) : Colors.white, boxShadow: [ BoxShadow( blurRadius: 10.0, offset: const Offset(5, 5), color: themeController.isDarkMode ? Colors.black : const Color.fromARGB(109, 144, 144, 144)), BoxShadow( blurRadius: 10.0, offset: const Offset(-5, -5), color: themeController.isDarkMode ? const Color.fromARGB(255, 27, 27, 27) : const Color.fromARGB(255, 243, 243, 243)) ], borderRadius: BorderRadius.circular(20)), child: Center( child: Text( text, style: TextStyle( color: color, fontSize: 19, fontWeight: fontWeight, ), ), ), ); }), ); } }
0
mirrored_repositories/Flutter-Timer-with-GetX/flutter_simple_timer/lib
mirrored_repositories/Flutter-Timer-with-GetX/flutter_simple_timer/lib/controller/timer_controller.dart
import 'dart:async'; import 'package:get/get.dart'; class TimerController extends GetxController { static const maxSeconds = 60; var seconds = maxSeconds; Timer? timer; /// Start Timer void startTimer({bool rest = true}) { if (rest) { resetTimer(); update(); } timer = Timer.periodic(const Duration(seconds: 1), (timer) { if (seconds > 0) { seconds--; update(); } else { stopTimer(rest: false); resetTimer(); } }); } /// Stop Timer void stopTimer({bool rest = true}) { if (rest) { resetTimer(); update(); } timer?.cancel(); update(); } /// Reset Timer void resetTimer() { seconds = maxSeconds; update(); } /// is Timer Active? bool isTimerRuning() { return timer == null ? false : timer!.isActive; } /// is Timer Completed? bool isCompleted() { return seconds == maxSeconds || seconds == 0; } }
0
mirrored_repositories/Flutter-Timer-with-GetX/flutter_simple_timer/lib
mirrored_repositories/Flutter-Timer-with-GetX/flutter_simple_timer/lib/controller/theme_controller.dart
import 'package:get/get.dart'; class ThemeController extends GetxController { bool isDarkMode = Get.isDarkMode; void changeThemeOfButtons() { isDarkMode = !isDarkMode; update([1]); } }
0
mirrored_repositories/Flutter-Timer-with-GetX/flutter_simple_timer/lib
mirrored_repositories/Flutter-Timer-with-GetX/flutter_simple_timer/lib/utils/themes.dart
import 'package:flutter/material.dart'; class MyThemes { static final lightTheme = ThemeData( scaffoldBackgroundColor: Colors.white, textTheme: const TextTheme( headline1: TextStyle( color: Colors.black, fontSize: 26, fontWeight: FontWeight.w400, ), headline2: TextStyle( color: Colors.black, fontSize: 15, fontWeight: FontWeight.w300, ), ), iconTheme: const IconThemeData(color: Colors.black, size: 35)); /// static final darkTheme = ThemeData( scaffoldBackgroundColor: const Color.fromARGB(255, 21, 21, 21), textTheme: const TextTheme( headline1: TextStyle( color: Colors.white, fontSize: 26, fontWeight: FontWeight.w400, ), headline2: TextStyle( color: Colors.white, fontSize: 15, fontWeight: FontWeight.w300, ), ), iconTheme: const IconThemeData(color: Colors.white, size: 35)); }
0
mirrored_repositories/DiceRoller
mirrored_repositories/DiceRoller/lib/main.dart
import 'dart:math'; import 'package:flutter/material.dart'; void main() { return runApp( MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( backgroundColor: Colors.red, appBar: AppBar( title: Text('Dicee'), backgroundColor: Colors.red, ), body: SafeArea( child: DicePage(), ), ), ), ); } class DicePage extends StatefulWidget { @override _DicePageState createState() => _DicePageState(); } class _DicePageState extends State<DicePage> { int leftDiceNumber = 1; int rightDiceNumber = 1; void rowDices() { setState(() { leftDiceNumber = Random().nextInt(6) + 1; rightDiceNumber = Random().nextInt(6) + 1; }); } @override Widget build(BuildContext context) { return Center( child: Row( children: <Widget>[ Expanded( child: FlatButton( padding: EdgeInsets.only(left: 16.0, right: 8.0), child: Image.asset('images/dice$leftDiceNumber.png'), onPressed: () { rowDices(); }, ), ), Expanded( child: FlatButton( padding: EdgeInsets.only(left: 8.0, right: 16.0), child: Image.asset('images/dice$rightDiceNumber.png'), onPressed: () { rowDices(); }, ), ), ], ), ); } }
0
mirrored_repositories/fec-thesis-publish
mirrored_repositories/fec-thesis-publish/lib/main.dart
import 'package:fecthesispublish/constants/supabase_urls.dart'; import 'package:fecthesispublish/screens/splashs/spalsh_screen.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; void main(List<String> args) async { // await Supabase.initialize( // url: SupabaseCredentials.supabaseUrl, // anonKey: SupabaseCredentials.supabaseAnonKey, // debug: true, // // authFlowType: AuthFlowType.implicit, // ); WidgetsFlutterBinding.ensureInitialized(); await Supabase.initialize( url: supabaseUrl, anonKey: supabaseAnonKey, authFlowType: AuthFlowType.pkce); // Get.put<SupabaseClient>(supabaseClient); // Get.put<GetStorage>(GetStorage()); runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { // @override // void initState() { // super.initState(); // } @override Widget build(BuildContext context) { return const GetMaterialApp( debugShowCheckedModeBanner: false, home: SplashScreen(), ); } }
0
mirrored_repositories/fec-thesis-publish/lib
mirrored_repositories/fec-thesis-publish/lib/constants/supabase_urls.dart
import 'package:supabase_flutter/supabase_flutter.dart'; const supabaseUrl = "https://vxrnxqqdeeymkucsobeq.supabase.co"; const String supabaseAnonKey = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZ4cm54cXFkZWV5bWt1Y3NvYmVxIiwicm9sZSI6ImFub24iLCJpYXQiOjE2OTE3NjY3ODcsImV4cCI6MjAwNzM0Mjc4N30.6mwp8YN1JBuIpBjhi42CqTYSp7wiHUHa3yXdRoyo-ks"; const String emailRedirect = "io.supabase.flutterquickstart://login-callback/"; final supabaseClient = SupabaseClient(supabaseUrl, supabaseAnonKey); final supabase = Supabase.instance.client;
0
mirrored_repositories/fec-thesis-publish/lib
mirrored_repositories/fec-thesis-publish/lib/constants/app_colors.dart
import 'package:flutter/material.dart'; const Color blue = Color(0xff0E4C92); const Color steelBlue = Color(0xff4682B4); const Color primaryColor = Color(0xff6C63FF); const Color black = Colors.black; const Color grey = Colors.grey;
0
mirrored_repositories/fec-thesis-publish/lib
mirrored_repositories/fec-thesis-publish/lib/constants/app_fonts.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; final TextStyle ubuntu = GoogleFonts.ubuntu(); final TextStyle popins = GoogleFonts.poppins();
0
mirrored_repositories/fec-thesis-publish/lib
mirrored_repositories/fec-thesis-publish/lib/components/appbar.dart
import 'package:flutter/material.dart'; class MyAppBar extends StatelessWidget { const MyAppBar({super.key}); @override Widget build(BuildContext context) { return AppBar(); } // @override // // TODO: implement preferredSize // Size get preferredSize => throw UnimplementedError(); }
0
mirrored_repositories/fec-thesis-publish/lib
mirrored_repositories/fec-thesis-publish/lib/components/upload_file.dart
import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:get/get.dart'; import 'package:google_fonts/google_fonts.dart'; class UploadFileWidget extends StatelessWidget { final String title; const UploadFileWidget({ super.key, required this.title, }); @override Widget build(BuildContext context) { return Container( constraints: const BoxConstraints(maxWidth: 200), decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), color: Colors.amber, ), child: MaterialButton( onPressed: () { pickFile(); }, child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ const Icon(Icons.file_upload_outlined), Text(title, style: GoogleFonts.ubuntu()) ], ), ), ); } void pickFile() async { FilePickerResult? pickerResult = await FilePicker.platform.pickFiles(type: FileType.media); if (pickerResult == null) { Get.snackbar(title, "Upload Unsuccessful", backgroundColor: Colors.redAccent, icon: const Padding( padding: EdgeInsets.all(15.0), child: FaIcon( FontAwesomeIcons.xmark, color: Colors.black, ), )); } else { Get.snackbar(title, "Upload Successful", backgroundColor: Colors.greenAccent, icon: const Padding( padding: EdgeInsets.all(15.0), child: FaIcon( FontAwesomeIcons.check, color: Colors.black, ), )); } } }
0
mirrored_repositories/fec-thesis-publish/lib
mirrored_repositories/fec-thesis-publish/lib/components/color.dart
import 'package:flutter/material.dart'; class CustomColor { static Color BLUEGREY = Colors.blueGrey.shade800; static Color WHITE = Colors.white; }
0
mirrored_repositories/fec-thesis-publish/lib
mirrored_repositories/fec-thesis-publish/lib/components/form_wid.dart
import 'package:fecthesispublish/constants/app_colors.dart'; import 'package:fecthesispublish/constants/app_fonts.dart'; import 'package:flutter/material.dart'; class FormWidget extends StatelessWidget { final String text; final TextEditingController controller; final bool? obsecuretext; final TextInputType textInputType; final Widget? widget; final FormFieldValidator? fieldValidator; const FormWidget({ super.key, required this.text, required this.controller, this.obsecuretext, required this.textInputType, this.widget, this.fieldValidator, }); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: TextFormField( validator: fieldValidator, keyboardType: textInputType, obscureText: obsecuretext ?? false, controller: controller, cursorColor: grey, style: ubuntu.copyWith( color: black.withOpacity(.7), ), decoration: InputDecoration( focusedBorder: const UnderlineInputBorder( borderSide: BorderSide(color: primaryColor)), suffixIcon: widget, hintText: text, hintStyle: popins.copyWith( fontSize: 15, color: grey.withOpacity(.8), ), ), ), ); } }
0
mirrored_repositories/fec-thesis-publish/lib
mirrored_repositories/fec-thesis-publish/lib/components/my_drawer.dart
import 'package:fecthesispublish/components/color.dart'; import 'package:fecthesispublish/constants/supabase_urls.dart'; import 'package:fecthesispublish/screens/auths/sign_in_screen.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:get/get.dart'; import 'package:google_fonts/google_fonts.dart'; class MyDrawer extends StatelessWidget { const MyDrawer({super.key}); @override Widget build(BuildContext context) { double resWIDTH = MediaQuery.of(context).size.width; return SafeArea( child: Drawer( width: resWIDTH * 0.6, backgroundColor: CustomColor.BLUEGREY, child: Padding( padding: const EdgeInsets.all(10.0), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ // fec logo Column( children: [ Image.asset('assets/images/fec_logo.png'), // contact ListTile( leading: FaIcon( FontAwesomeIcons.addressCard, color: CustomColor.WHITE, ), title: Text( 'Contact', style: GoogleFonts.ubuntu(color: CustomColor.WHITE), ), ), // Settings ListTile( leading: FaIcon(FontAwesomeIcons.gear, color: CustomColor.WHITE), title: Text( 'Settings', style: GoogleFonts.ubuntu(color: CustomColor.WHITE), ), ), // Our website ListTile( leading: FaIcon(FontAwesomeIcons.earthAsia, color: CustomColor.WHITE), title: Text( 'Our Website', style: GoogleFonts.ubuntu(color: CustomColor.WHITE), ), ), ], ), GestureDetector( onTap: () async { await supabaseClient.auth.signOut(); Get.to(() => const SignInScreen()); }, child: ListTile( leading: FaIcon(FontAwesomeIcons.rightFromBracket, color: CustomColor.WHITE), title: Text( 'Log-Out', style: GoogleFonts.ubuntu(color: CustomColor.WHITE), ), ), ), ], ), ), ), ); } }
0
mirrored_repositories/fec-thesis-publish/lib
mirrored_repositories/fec-thesis-publish/lib/services/auth_services.dart
import 'package:fecthesispublish/constants/supabase_urls.dart'; class AuthServices { // Signup static Future<void> signUP( {required String email, required String password, required String firstname, required String lastname, required int regno}) async { await supabase.auth.signUp( email: email, password: password, emailRedirectTo: emailRedirect, data: {'firstName': firstname, 'lastName': lastname, 'regNo': regno}); } // SignIn static Future<void> signIN( {required String email, required String password}) async { await supabase.auth.signInWithPassword(email: email, password: password); } // SignOut // otp } /* // signIn method static Future<void> signInWithEmail({ required String email, required String password, }) async { try { final response = await Supabase.instance.client.auth.signInWithPassword( email: email, password: password, ); } catch (e) { print('error $e'); } } // signUp method static Future<void> signUp({ required String email, required String password, }) async { try { final response = await Supabase.instance.client.auth.signUp( email: email, password: password, ); } catch (e) { print('error $e'); } // final Session? session = res.session; // final User? user = res.user; } // signOut method static Future<void> signOut() async { try { final response = await Supabase.instance.client.auth.signOut(); } catch (e) { print("Error signing out"); } } */
0
mirrored_repositories/fec-thesis-publish/lib
mirrored_repositories/fec-thesis-publish/lib/screens/papers_screen.dart
import 'package:fecthesispublish/screens/submission_screen.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:google_fonts/google_fonts.dart'; import '../components/color.dart'; class PapersScreen extends StatefulWidget { const PapersScreen({super.key}); @override State<PapersScreen> createState() => _PapersScreenState(); } class _PapersScreenState extends State<PapersScreen> { final TextEditingController searchController = TextEditingController(); late String searchText = ""; List<String> batchDropDownItem = <String>[ 'All', 'Batch-01', 'Batch-02', 'Batch-03', 'Batch-04', 'Batch-05', 'Batch-06', 'Batch-07', 'Batch-08', 'Batch-09', 'Batch-10', ]; // String batchDropDownValue = 'All'; String batchDropDownValue = "All"; List<String> deptDropDownItem = <String>[ 'All', 'CSE', 'EEE', 'CE', ]; String deptDropDownValue = 'All'; @override Widget build(BuildContext context) { double resWIDTH = MediaQuery.of(context).size.width; return Scaffold( // floatingActionButton floatingActionButton: FloatingActionButton( backgroundColor: CustomColor.BLUEGREY, onPressed: () { Get.to(const SubmissionScreen()); }, child: const Icon(Icons.add), ), body: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(24.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ // department filter SizedBox( width: resWIDTH * 0.7, child: TextFormField( controller: searchController, // onChanged: (value) => show = searchText.toString(), decoration: InputDecoration( // prefixIcon: const Icon(Icons.search), // prefixIconColor: CustomColor.BLUEGREY, hintText: 'search.....', hintStyle: GoogleFonts.ubuntu(), border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), ), ), ), const Spacer(), OutlinedButton( onPressed: () { setState(() { searchText = searchController.text; searchController.clear(); }); }, child: SizedBox( height: 60, child: Icon( Icons.search, color: CustomColor.BLUEGREY, ), ), ), ], ), const SizedBox(height: 20), // Text(show), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ // batch filter SizedBox( width: resWIDTH * 0.3, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Department", style: GoogleFonts.ubuntu(fontSize: 18), ), const SizedBox(height: 10), // department select DropdownButtonFormField<String>( hint: const Text('Select Department'), dropdownColor: Colors.blueGrey.shade200, isExpanded: true, decoration: InputDecoration( border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), ), items: deptDropDownItem.map((String value) { return DropdownMenuItem<String>( value: value, child: Text(value, style: GoogleFonts.ubuntu()), ); }).toList(), onChanged: (String? newValue) { setState(() { deptDropDownValue = newValue!; }); }, value: deptDropDownValue, ), ], ), ), SizedBox( width: resWIDTH * 0.5, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Batch", style: GoogleFonts.ubuntu(fontSize: 18), ), const SizedBox(height: 10), // batch select DropdownButtonFormField<String>( hint: const Text('Select Batch'), dropdownColor: Colors.blueGrey.shade200, isExpanded: true, decoration: InputDecoration( border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), ), items: batchDropDownItem.map((String value) { return DropdownMenuItem<String>( value: value, child: Text(value, style: GoogleFonts.ubuntu()), ); }).toList(), onChanged: (String? newValue) { setState(() { batchDropDownValue = newValue!; }); }, value: batchDropDownValue, ), ], ), ), ], ), ], ), ), ), ); } }
0
mirrored_repositories/fec-thesis-publish/lib
mirrored_repositories/fec-thesis-publish/lib/screens/blog_screen.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class BlogScreen extends StatefulWidget { const BlogScreen({super.key}); @override State<BlogScreen> createState() => _BlogScreenState(); } class _BlogScreenState extends State<BlogScreen> { @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: const EdgeInsets.all(20.0), child: SingleChildScrollView( scrollDirection: Axis.vertical, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // profile Text( "Blogs", style: GoogleFonts.ubuntu(fontSize: 40), ), const Divider( thickness: 3, endIndent: 200, color: Colors.grey, ), const SizedBox(height: 20), ], ), ), ), ); } }
0
mirrored_repositories/fec-thesis-publish/lib
mirrored_repositories/fec-thesis-publish/lib/screens/profile_screen.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class ProfileScreen extends StatefulWidget { const ProfileScreen({super.key}); @override State<ProfileScreen> createState() => _ProfileScreenState(); } class _ProfileScreenState extends State<ProfileScreen> { @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: const EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // profile Text( "Profile", style: GoogleFonts.ubuntu(fontSize: 40), ), const Divider( thickness: 3, endIndent: 200, color: Colors.grey, ), const SizedBox(height: 20), // name Row( children: [ Text( "Name: ", style: GoogleFonts.ubuntu( fontWeight: FontWeight.bold, fontSize: 20), ), Text( "Anamul Nishat", style: GoogleFonts.ubuntu(fontSize: 20), ), ], ), const SizedBox(height: 15), // email Row( children: [ Text( "e-mail: ", style: GoogleFonts.ubuntu( fontWeight: FontWeight.bold, fontSize: 20), ), Text( "[email protected]", style: GoogleFonts.ubuntu(fontSize: 20), ), ], ), const SizedBox(height: 15), // registration Row( children: [ Text( "Reg. No.: ", style: GoogleFonts.ubuntu( fontWeight: FontWeight.bold, fontSize: 20), ), Text( "1777", style: GoogleFonts.ubuntu(fontSize: 20), ), ], ), const SizedBox(height: 15), ], ), ), ); } }
0
mirrored_repositories/fec-thesis-publish/lib
mirrored_repositories/fec-thesis-publish/lib/screens/submission_screen.dart
import 'package:fecthesispublish/screens/main_navbar_screen.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:google_fonts/google_fonts.dart'; import '../components/upload_file.dart'; class SubmissionScreen extends StatefulWidget { const SubmissionScreen({super.key}); @override State<SubmissionScreen> createState() => _SubmissionScreenState(); } class _SubmissionScreenState extends State<SubmissionScreen> { List<String> batchDropDownItem = <String>[ 'Batch-01', 'Batch-02', 'Batch-03', 'Batch-04', 'Batch-05', 'Batch-06', 'Batch-07', 'Batch-08', 'Batch-09', 'Batch-10', ]; String batchDropDownValue = 'Batch-01'; List<String> deptDropDownItem = <String>[ 'CSE', 'EEE', 'CE', ]; String deptDropDownValue = 'CSE'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: Text('Submit Thesis Paper', style: GoogleFonts.ubuntu(color: Colors.black)), leading: IconButton( onPressed: () { Get.back(); }, icon: const Icon(Icons.arrow_back_ios_rounded), color: Colors.black), backgroundColor: Colors.white, elevation: 0, ), body: SafeArea( child: SingleChildScrollView( // scrollDirection: Axis.vertical, child: Padding( padding: const EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // thesis title Text( 'Thesis Name', style: GoogleFonts.ubuntu( fontWeight: FontWeight.bold, fontSize: 20), ), const SizedBox(height: 10), STPTextWidget( name: "enter thesis name", controller: TextEditingController(), ), const SizedBox(height: 10), // batch Text( 'Select Batch', style: GoogleFonts.ubuntu( fontWeight: FontWeight.bold, fontSize: 20), ), const SizedBox(height: 10), // batch select DropdownButtonFormField<String>( hint: const Text('Select Batch'), dropdownColor: Colors.blueGrey.shade200, isExpanded: true, decoration: InputDecoration( border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), ), items: batchDropDownItem.map((String value) { return DropdownMenuItem<String>( value: value, child: Text(value, style: GoogleFonts.ubuntu()), ); }).toList(), onChanged: (String? newValue) { setState(() { batchDropDownValue = newValue!; }); }, value: batchDropDownValue, ), const SizedBox(height: 10), // department Text( 'Select Department', style: GoogleFonts.ubuntu( fontWeight: FontWeight.bold, fontSize: 20), ), const SizedBox(height: 10), // department select DropdownButtonFormField<String>( hint: const Text('Select Department'), dropdownColor: Colors.blueGrey.shade200, isExpanded: true, decoration: InputDecoration( border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), ), items: deptDropDownItem.map((String value) { return DropdownMenuItem<String>( value: value, child: Text(value, style: GoogleFonts.ubuntu()), ); }).toList(), onChanged: (String? newValue) { setState(() { deptDropDownValue = newValue!; }); }, value: deptDropDownValue, ), const SizedBox(height: 10), // team mates name Text( 'Team Mates Name', style: GoogleFonts.ubuntu( fontWeight: FontWeight.bold, fontSize: 20), ), const SizedBox(height: 10), STPTextWidget( name: "first name", controller: TextEditingController(), ), const SizedBox(height: 10), STPTextWidget( name: "second name", controller: TextEditingController(), ), const SizedBox(height: 10), STPTextWidget( name: "third name", controller: TextEditingController(), ), const SizedBox(height: 10), STPTextWidget( name: "fourth name", controller: TextEditingController(), ), const SizedBox(height: 10), // supervisor name Text( 'Supervisor Name', style: GoogleFonts.ubuntu( fontWeight: FontWeight.bold, fontSize: 20), ), const SizedBox(height: 10), STPTextWidget( name: "enter supervisor's name", controller: TextEditingController(), ), const SizedBox(height: 10), // upload Cover Page const UploadFileWidget( title: 'Upload Cover page', ), const SizedBox(height: 10), // upload pdf const UploadFileWidget( title: 'Upload PDF', ), const SizedBox(height: 20), // submit button SizedBox( width: double.infinity, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.blue.shade900, ), onPressed: () { Get.to(const MainNavBarScreen()); }, child: Text('Submit', style: GoogleFonts.ubuntu()), ), ), const SizedBox(height: 20), ], ), ), )), ); } } class STPTextWidget extends StatelessWidget { final String name; final TextEditingController controller; const STPTextWidget({ super.key, required this.name, required this.controller, }); @override Widget build(BuildContext context) { return TextFormField( controller: controller, decoration: InputDecoration( border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)), hintText: name, hintStyle: GoogleFonts.ubuntu()), ); } }
0
mirrored_repositories/fec-thesis-publish/lib
mirrored_repositories/fec-thesis-publish/lib/screens/main_navbar_screen.dart
import 'package:fecthesispublish/components/color.dart'; import 'package:fecthesispublish/components/my_drawer.dart'; import 'package:fecthesispublish/screens/blog_screen.dart'; import 'package:fecthesispublish/screens/papers_screen.dart'; import 'package:fecthesispublish/screens/profile_screen.dart'; import 'package:flutter/material.dart'; class MainNavBarScreen extends StatefulWidget { const MainNavBarScreen({super.key}); @override State<MainNavBarScreen> createState() => _MainNavBarScreenState(); } class _MainNavBarScreenState extends State<MainNavBarScreen> { var _selectIndex = 0; final List<Widget> _list = [ const PapersScreen(), const BlogScreen(), const ProfileScreen(), ]; void _onTaped(int i) { setState(() { _selectIndex = i; }); } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, // appbar appBar: AppBar( backgroundColor: CustomColor.BLUEGREY, ), // drawer drawer: const MyDrawer(), // bottomNavigationBar bottomNavigationBar: BottomNavigationBar( backgroundColor: CustomColor.BLUEGREY, selectedItemColor: Colors.green.shade300, unselectedItemColor: Colors.white, currentIndex: _selectIndex, onTap: _onTaped, items: const [ BottomNavigationBarItem( icon: Icon(Icons.web_rounded), label: 'Thesis', ), BottomNavigationBarItem( icon: Icon(Icons.analytics_rounded), label: 'Blogs', ), BottomNavigationBarItem( icon: Icon(Icons.person_2_rounded), label: 'Profile', ), ], ), // body body: _list[_selectIndex], // floatingActionButton // floatingActionButton: FloatingActionButton( // backgroundColor: CustomColor.BLUEGREY, // onPressed: () { // Get.to(const SubmissionScreen()); // }, // child: const Icon(Icons.add), // ), ); } }
0
mirrored_repositories/fec-thesis-publish/lib/screens
mirrored_repositories/fec-thesis-publish/lib/screens/splashs/welcome_screen1.dart
import 'package:fecthesispublish/screens/splashs/welcome_screen2.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'splash_widget.dart'; class WelcomeScreen1 extends StatelessWidget { const WelcomeScreen1({super.key}); @override Widget build(BuildContext context) { return SpalshWidget( bannerImgpath: 'assets/svgs/knowledge.svg', sloganName: 'Try to gather knowledge from vast world', onTap: () { Get.to(() => const WelcomeScreen2(), transition: Transition.rightToLeft, duration: const Duration(milliseconds: 1500)); }, ); } }
0
mirrored_repositories/fec-thesis-publish/lib/screens
mirrored_repositories/fec-thesis-publish/lib/screens/splashs/welcome_screen3.dart
import 'package:fecthesispublish/screens/splashs/welcome_screen2.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'splash_widget.dart'; class WelcomeScreen3 extends StatelessWidget { const WelcomeScreen3({super.key}); @override Widget build(BuildContext context) { return SpalshWidget( bannerImgpath: 'assets/svgs/articles.svg', sloganName: 'Read more to know topics deeply and accurately', onTap: () { Get.to(() => const WelcomeScreen2(), transition: Transition.rightToLeft, duration: const Duration(milliseconds: 1500)); }, ); } }
0
mirrored_repositories/fec-thesis-publish/lib/screens
mirrored_repositories/fec-thesis-publish/lib/screens/splashs/welcome_screen2.dart
import 'package:fecthesispublish/screens/auths/sign_in_screen.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'splash_widget.dart'; class WelcomeScreen2 extends StatelessWidget { const WelcomeScreen2({super.key}); @override Widget build(BuildContext context) { return SpalshWidget( bannerImgpath: 'assets/svgs/predictive_analytics.svg', sloganName: 'Share your progress knowledge with everyone', onTap: () { Get.offAll( () => const SignInScreen(), ); }, ); } }
0
mirrored_repositories/fec-thesis-publish/lib/screens
mirrored_repositories/fec-thesis-publish/lib/screens/splashs/spalsh_screen.dart
import 'package:fecthesispublish/constants/app_fonts.dart'; import 'package:fecthesispublish/screens/auths/sign_in_screen.dart'; import 'package:fecthesispublish/screens/splashs/welcome_screen1.dart'; import 'package:fecthesispublish/screens/splashs/welcome_screen2.dart'; import 'package:fecthesispublish/screens/splashs/welcome_screen3.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:smooth_page_indicator/smooth_page_indicator.dart'; class SplashScreen extends StatefulWidget { const SplashScreen({super.key}); @override State<SplashScreen> createState() => _SplashScreenState(); } class _SplashScreenState extends State<SplashScreen> { // @override // void initState() { // super.initState(); // Future.delayed(const Duration(seconds: 7)) // .then((value) => Get.off(()=>const WelcomeScreen1())); // } final PageController _controller = PageController(); bool onLastPage = false; // @override // void initState() { // super.initState(); // _redirect(); // } // Future<void> _redirect() async { // await Future.delayed(Duration.zero); // final sessoon = supabase.auth.currentSession; // if (!mounted) return; // if (sessoon != null) { // Get.off(() => const MainNavBarScreen()); // } else { // Get.off(() => const SignInScreen()); // } // } @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Stack( children: [ PageView( controller: _controller, onPageChanged: (value) { setState(() { onLastPage = (value == 2); }); }, children: const [ WelcomeScreen1(), WelcomeScreen2(), WelcomeScreen3() ], ), Container( alignment: const Alignment(0, .65), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ // skip button GestureDetector( onTap: () { _controller.jumpToPage(2); }, child: Text("Skip", style: popins), ), // dot indicator SmoothPageIndicator( controller: _controller, count: 3, ), // onLastPage // next ? done button onLastPage ? GestureDetector( onTap: () { setState(() { Get.offAll(const SignInScreen()); }); }, child: Text("Done", style: popins), ) : GestureDetector( onTap: () { _controller.nextPage( duration: const Duration(milliseconds: 1500), curve: Curves.decelerate); }, child: Text("Next", style: popins), ), ], )), ], ), ), ); } }
0
mirrored_repositories/fec-thesis-publish/lib/screens
mirrored_repositories/fec-thesis-publish/lib/screens/splashs/splash_widget.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import '../../constants/app_fonts.dart'; class SpalshWidget extends StatelessWidget { final String sloganName; final String bannerImgpath; final VoidCallback onTap; const SpalshWidget({ super.key, required this.sloganName, required this.bannerImgpath, required this.onTap, }); @override Widget build(BuildContext context) { double resHeight = MediaQuery.of(context).size.height; return Scaffold( body: SafeArea( child: Padding( padding: const EdgeInsets.all(30), child: Stack(children: [ const Align( alignment: Alignment.topRight, child: Icon(Icons.arrow_forward_ios_outlined), ), Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SvgPicture.asset( bannerImgpath, height: resHeight / 3.5, ), SizedBox( height: resHeight / 35, ), Text( sloganName, style: popins.copyWith(fontSize: resHeight / 25), ), SizedBox( height: resHeight / 35, ), // SizedBox( // width: 250, // height: 50, // child: ElevatedButton( // style: ElevatedButton.styleFrom( // backgroundColor: purple.withOpacity(.8), // shape: RoundedRectangleBorder( // borderRadius: BorderRadius.circular( // 10, // ), // ), // ), // onPressed: onTap, // child: Text("Continue", // style: popins.copyWith( // fontSize: 20, // color: black, // fontWeight: FontWeight.w500)), // ), // ) ], ), ]), ), ), ); } }
0
mirrored_repositories/fec-thesis-publish/lib/screens
mirrored_repositories/fec-thesis-publish/lib/screens/auths/sign_in_screen.dart
import 'package:fecthesispublish/constants/app_fonts.dart'; import 'package:fecthesispublish/screens/auths/sign_up_screen.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; import '../../components/form_wid.dart'; import '../../constants/app_colors.dart'; import '../../services/auth_services.dart'; import '../main_navbar_screen.dart'; import 'elevatedbutton.dart'; class SignInScreen extends StatefulWidget { const SignInScreen({super.key}); @override State<SignInScreen> createState() => _SignInScreenState(); } class _SignInScreenState extends State<SignInScreen> { final GlobalKey<FormState> _formKey = GlobalKey(); late TextEditingController _emailController = TextEditingController(); late TextEditingController _passwordController = TextEditingController(); // late final StreamSubscription<AuthState> _authSubscription; // @override // void initState() { // super.initState(); // _authSubscription = supabase.auth.onAuthStateChange.listen((event) { // final session = event.session; // if (session != null) { // Get.off(() => const MainNavBarScreen()); // } // }); // } @override void initState() { super.initState(); _emailController = TextEditingController(); _passwordController = TextEditingController(); } @override void dispose() { _emailController.dispose(); _passwordController.dispose(); // _authSubscription.cancel(); super.dispose(); } @override Widget build(BuildContext context) { // final double resWidth = MediaQuery.of(context).size.width; // 360 // final double resHeight = MediaQuery.of(context).size.height; // 677.33 return Scaffold( body: SafeArea( child: Padding( // padding: const EdgeInsets.all(25), padding: const EdgeInsets.symmetric(horizontal: 15), child: Center( child: Form( key: _formKey, child: ListView( shrinkWrap: true, children: [ // text Container( decoration: BoxDecoration( border: Border.all( color: black.withOpacity(.4), ), color: Colors.grey.shade200, borderRadius: BorderRadius.circular(15)), child: Padding( padding: const EdgeInsets.symmetric( vertical: 20, horizontal: 10), child: Column( children: [ Text( 'Sign In', style: GoogleFonts.roboto(fontSize: 35), ), const SizedBox(height: 20), // user-name FormWidget( textInputType: TextInputType.text, controller: _emailController, text: 'Email Address', fieldValidator: (value) { if (value == null || value.isEmpty) { return 'Required Email'; } final bool emailValid = RegExp( r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+") .hasMatch(value); if (!emailValid) { return 'Email is not valid'; } return null; }, ), const SizedBox(height: 10), // password FormWidget( obsecuretext: true, textInputType: TextInputType.text, controller: _passwordController, text: 'Password', fieldValidator: (value) { if (value == null || value.isEmpty) { return 'Required Password'; } return null; }, ), const SizedBox(height: 20), // sign-in button ElevatedButtonWidget( buttonName: 'SIGN IN', ontap: () async { try { // final email = _emailController.text.trim(); // final password = _passwordController.text; // await supabase.auth.signInWithOtp( // email: email, // // password: password // emailRedirectTo: // SupabaseCredentials.emailRedirect, // ); await AuthServices.signIN( email: _emailController.text, password: _passwordController.text, ); if (mounted) { Get.showSnackbar(const GetSnackBar( duration: Duration(seconds: 3), message: 'Login Successfull', // message: 'Check Your mail', )); Get.offAll(() => const MainNavBarScreen()); } } on AuthException catch (e) { Get.showSnackbar(GetSnackBar( duration: const Duration(seconds: 2), message: e.message, backgroundColor: Theme.of(context).colorScheme.error, )); } catch (e) { Get.showSnackbar(GetSnackBar( duration: const Duration(seconds: 2), message: 'Unknown Error occurred', backgroundColor: Theme.of(context).colorScheme.error, )); } }, ), // create new account TextButton( onPressed: () { Get.to(() => const SignUpScreen()); }, child: Text( 'Create an account', style: popins.copyWith(color: grey.withOpacity(.8)), ), ), ], ), ), ) ], ), ), ), ), ), ); } }
0
mirrored_repositories/fec-thesis-publish/lib/screens
mirrored_repositories/fec-thesis-publish/lib/screens/auths/elevatedbutton.dart
import 'package:flutter/material.dart'; import '../../constants/app_colors.dart'; import '../../constants/app_fonts.dart'; class ElevatedButtonWidget extends StatelessWidget { final String buttonName; final VoidCallback ontap; const ElevatedButtonWidget({ super.key, required this.buttonName, required this.ontap, }); @override Widget build(BuildContext context) { return SizedBox( width: double.infinity, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: primaryColor, ), onPressed: ontap, child: Text(buttonName, style: popins)), ); } }
0