repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/bloc/getposts_bloc.dart
import 'package:bloc/bloc.dart'; import 'package:nirogi/src/bloc/events.dart'; import 'package:nirogi/src/bloc/states.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/repository/repositories.dart'; class GetPostsBloc extends Bloc<GetPostsEvent, GetPostsState> { @override GetPostsState get initialState => PostsUninitialisedState(); @override Stream<GetPostsState> mapEventToState(GetPostsEvent event) async* { yield PostsFetchingState(); try { List<Post> posts; if (event is GetAllPostsEvent) { posts = await postRepository.getAllPost(sort: event.sort); } else if (event is GetAllMyPostsEvent) { posts = await postRepository.getAllMyPosts(); } else if (event is GetUsersPostsEvent) { posts = await postRepository.getUsersPosts(userId: event.userId); } else if (event is GetCategoryPostsEvent) { posts = await postRepository.viewCategoryPosts( categoryId: event.categoryId); } if (posts.length == 0) { yield PostsEmptyState(); } else { yield PostsFetchedState(posts: posts); } } catch (e) { yield PostsErrorState(); } } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/bloc/login_state.dart
import 'package:equatable/equatable.dart'; import 'package:meta/meta.dart'; abstract class LoginState extends Equatable {} class LoginInitialState extends LoginState { @override String toString() => 'LoginInitial'; @override List<Object> get props => null; } class LoginLoadingState extends LoginState { @override String toString() => 'LoginLoading'; List<Object> get props => null; } class LoginFailureState extends LoginState { final String error; LoginFailureState({@required this.error}); @override String toString() => 'LoginFailure { error: $error }'; List<Object> get props => [error]; }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/bloc/login_event.dart
import 'package:equatable/equatable.dart'; import 'package:meta/meta.dart'; abstract class LoginEvent extends Equatable {} class LoginButtonPressedEvent extends LoginEvent { final String email; final String password; LoginButtonPressedEvent({ @required this.email, @required this.password, }); @override String toString() => 'LoginButtonPressed { email: $email, password: $password }'; @override List<Object> get props => [email, password]; } class LoginInitialEvent extends LoginEvent { @override List<Object> get props => null; }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/themes/glass_painter.dart
import 'package:flutter/material.dart'; class GlassPainter extends CustomPainter { double filledPercent; GlassPainter({this.filledPercent}); @override void paint(Canvas canvas, Size size) { Paint glassPaint = Paint() ..color = Colors.black ..strokeCap = StrokeCap.butt ..strokeWidth = 2 ..style = PaintingStyle.stroke; Paint waterPaint = Paint() ..color = Colors.blue ..strokeCap = StrokeCap.butt ..style = PaintingStyle.fill; Path glassPath = Path(); glassPath.lineTo(size.width * 0.25, size.height); glassPath.lineTo(size.width * 0.75, size.height); glassPath.lineTo(size.width, 0); canvas.drawPath(glassPath, glassPaint); Path waterPath = Path(); double _factorInside = 0.05; double smallHeight = size.height * 0.05 + size.height * (1 - filledPercent); double smallWidth = 0.25 * size.width * smallHeight / size.height; waterPath.moveTo((smallWidth + size.width * _factorInside), smallHeight); waterPath.lineTo((size.width * 0.25 + size.width * _factorInside), (size.height - size.height * _factorInside)); waterPath.lineTo((size.width * 0.75 - size.width * _factorInside), (size.height - size.height * _factorInside)); waterPath.lineTo( size.width - (smallWidth + size.width * _factorInside), smallHeight); canvas.drawPath(waterPath, waterPaint); } @override bool shouldRepaint(CustomPainter oldDelegate) => false; }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/themes/themes.dart
import 'package:flutter/material.dart'; final ThemeData kLightTheme = _buildLightTheme(); ThemeData _buildLightTheme() { final ThemeData base = ThemeData.light(); return base.copyWith( highlightColor: Colors.grey[400].withOpacity(.6), appBarTheme: AppBarTheme( iconTheme: IconThemeData(color: Colors.red[700]), elevation: 0, ), primaryColor: Colors.white, accentColor: Colors.blue, primaryIconTheme: IconThemeData( color: Colors.red[700], ), inputDecorationTheme: InputDecorationTheme( hintStyle: TextStyle( fontSize: 14, color: Colors.black, fontFamily: 'Montserrat', fontWeight: FontWeight.normal, ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Colors.red[700], ), ), ), textTheme: TextTheme( headline: TextStyle( fontFamily: 'Montserrat', fontWeight: FontWeight.normal, color: Colors.black, ), body1: TextStyle( fontSize: 14, color: Colors.black, fontFamily: 'Montserrat', fontWeight: FontWeight.normal, ), body2: TextStyle( fontFamily: 'Karla', fontWeight: FontWeight.normal, color: Colors.black, fontSize: 12), button: TextStyle( fontFamily: 'Montserrat', fontWeight: FontWeight.w600, color: Colors.black, fontSize: 12, letterSpacing: 2, ), ), scaffoldBackgroundColor: Colors.white, buttonColor: Colors.white, buttonTheme: ButtonThemeData( buttonColor: Colors.white, ), ); } final ThemeData kDarkTheme = _buildDarkTheme(); ThemeData _buildDarkTheme() { final ThemeData base = ThemeData.dark(); return base.copyWith( inputDecorationTheme: InputDecorationTheme( hintStyle: TextStyle( fontSize: 14, color: Colors.black, fontFamily: 'Montserrat', fontWeight: FontWeight.normal, ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Colors.red[700], ), ), ), buttonColor: Colors.white, buttonTheme: ButtonThemeData( buttonColor: Colors.white, ), highlightColor: Colors.white24, appBarTheme: AppBarTheme( iconTheme: IconThemeData( color: Colors.red[700], ), elevation: 0.0, ), primaryColor: Color(0xff212121), scaffoldBackgroundColor: Color(0xff212121), canvasColor: Color(0xff303030), accentColor: Colors.blue, primaryIconTheme: IconThemeData(color: Colors.black), textTheme: TextTheme( headline: TextStyle( fontFamily: 'Montserrat', fontWeight: FontWeight.normal, color: Colors.white, fontSize: 24), body1: TextStyle( fontFamily: 'Montserrat', fontWeight: FontWeight.normal, color: Colors.white, fontSize: 14), body2: TextStyle( fontFamily: 'Karla', fontWeight: FontWeight.normal, color: Colors.white, fontSize: 12, ), button: TextStyle( fontFamily: 'Montserrat', fontWeight: FontWeight.w600, color: Colors.white, fontSize: 17, letterSpacing: 2, ), ), ); }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/themes/clippers.dart
import 'package:flutter/material.dart'; class HomePageClipper extends CustomClipper<Path> { @override Path getClip(Size size) { final Path path = new Path(); path.lineTo(0, size.height); path.quadraticBezierTo(size.width * 0.24, size.height * .955, size.width * .4, size.height * .8); path.quadraticBezierTo( size.width * .5, size.height * .73, size.width * .6, size.height * .75); path.quadraticBezierTo( size.width * 0.9, size.height * 0.8, size.width, size.height * 0.6); path.quadraticBezierTo(size.width * 0.9255, size.height * 0.555, size.width * 0.885, size.height * 0.38); path.quadraticBezierTo(size.width * .85, size.height * .12, size.width * .95, size.height * .2); path.quadraticBezierTo( size.width * 0.95, size.height * 0.04, size.width, size.height * 0.09); path.lineTo(size.width, 0); return path; } @override bool shouldReclip(CustomClipper<Path> oldClipper) => true; } class HomePageBorderClipper extends CustomClipper<Path> { @override Path getClip(Size size) { final Path path = new Path(); path.lineTo(0, size.height); path.quadraticBezierTo(size.width * 0.24, size.height * .955, size.width * .4, size.height * .8); path.quadraticBezierTo( size.width * .5, size.height * .73, size.width * .6, size.height * .75); path.quadraticBezierTo( size.width * 0.9, size.height * 0.8, size.width, size.height * 0.6); path.quadraticBezierTo(size.width * 0.93, size.height * 0.5, size.width * 0.899, size.height * 0.375); path.quadraticBezierTo(size.width * .87, size.height * .159, size.width * .96225, size.height * .195); path.quadraticBezierTo( size.width * 0.96, size.height * 0.07, size.width, size.height * 0.09); path.lineTo(size.width, 0); return path; } @override bool shouldReclip(CustomClipper<Path> oldClipper) => true; } class LoginPageClipper extends CustomClipper<Path> { @override Path getClip(Size size) { final Path path = Path(); path.lineTo(0, 0.61 * size.height); path.lineTo(size.width, 0.29 * size.height); path.lineTo(size.width, 0.49 * size.height); path.lineTo(0, 0.81 * size.height); return path; } @override bool shouldReclip(CustomClipper<Path> oldClipper) => true; }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/themes/scrollOverlay.dart
import 'package:flutter/material.dart'; class RemoveEndOfListIndicator extends ScrollBehavior { @override Widget buildViewportChrome( BuildContext context, Widget child, AxisDirection axisDirection) { return child; } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/provincePage.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'dart:math'; import 'package:nirogi/src/screens/screens.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:nirogi/src/widgets/widgets.dart'; List<String> images = [ "assets/images/province/Province700.jpg", "assets/images/province/Province600.jpg", "assets/images/province/Province500.jpg", "assets/images/province/Province400.jpg", "assets/images/province/Province300.jpg", "assets/images/province/Province200.jpg", "assets/images/province/Province100.jpg", ]; class ProvincePage extends StatefulWidget { @override _ProvincePageState createState() => _ProvincePageState(); } class _ProvincePageState extends State<ProvincePage> { var currentPage = images.length - 1.0; @override Widget build(BuildContext context) { PageController controller = PageController(initialPage: images.length - 1); controller.addListener(() { setState(() { currentPage = controller.page; }); }); return Scaffold( drawer: AppDrawer(), appBar: AppBar( centerTitle: true, title: Text( "Geographic Health Information", style: Theme.of(context).textTheme.headline, ), ), body: Column( children: <Widget>[ SizedBox(height: 60), Align( alignment: Alignment.topLeft, child: Padding( padding: const EdgeInsets.only(left: 20.0), child: Text( 'Select a Province', style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, shadows: [ Shadow( color: Colors.grey[500], offset: Offset(1, 2), blurRadius: 4, ) ]), ), ), ), SizedBox(height: 20), GestureDetector( onTap: () { int activeProvince = 8 - (currentPage.round().floor() + 1); Navigator.of(context) .push(MaterialPageRoute(builder: (BuildContext context) { return EachProvincePage( provinceId: activeProvince, title: 'Province $activeProvince', ); })); }, child: Stack( children: <Widget>[ CardScrollWidget(currentPage), Positioned.fill( child: ScrollConfiguration( child: PageView.builder( itemCount: images.length, controller: controller, reverse: true, itemBuilder: (context, index) { return Container(); }, ), behavior: RemoveEndOfListIndicator(), ), ) ], ), ), ], ), ); } } var cardAspectRatio = 12.0 / 16.0; var widgetAspectRatio = cardAspectRatio * 1.2; class CardScrollWidget extends StatelessWidget { final currentPage; final double padding = 20.0; final double verticalInset = 20.0; CardScrollWidget(this.currentPage); @override Widget build(BuildContext context) { return AspectRatio( aspectRatio: widgetAspectRatio, child: LayoutBuilder(builder: (context, contraints) { var width = contraints.maxWidth; var height = contraints.maxHeight; var safeWidth = width - 2 * padding; var safeHeight = height - 2 * padding; var heightOfPrimaryCard = safeHeight; var widthOfPrimaryCard = heightOfPrimaryCard * cardAspectRatio; var primaryCardLeft = safeWidth - widthOfPrimaryCard; var horizontalInset = primaryCardLeft / 2; List<Widget> cardList = List(); for (var i = 0; i < images.length; i++) { var delta = i - currentPage; bool isOnRight = delta > 0; var start = padding + max( primaryCardLeft - horizontalInset * -delta * (isOnRight ? 15 : 1), 0.0); var cardItem = Positioned.directional( top: padding + verticalInset * max(-delta, 0.0), bottom: padding + verticalInset * max(-delta, 0.0), start: start, textDirection: TextDirection.rtl, child: ClipRRect( borderRadius: BorderRadius.circular(16.0), child: Container( decoration: BoxDecoration( color: Colors.white, boxShadow: [ BoxShadow( color: Colors.black12, offset: Offset(3.0, 6.0), blurRadius: 10.0) ], ), child: AspectRatio( aspectRatio: cardAspectRatio, child: Stack( fit: StackFit.expand, children: <Widget>[ Image.asset(images[i], fit: BoxFit.cover), ], ), ), ), ), ); cardList.add(cardItem); } return Stack( children: cardList, ); }), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/symptom_search_page.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:nirogi/src/bloc/blocs.dart'; import 'package:nirogi/src/bloc/events.dart'; import 'package:nirogi/src/bloc/states.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class SymptomSearchPage extends StatefulWidget { @override _SymptomSearchPageState createState() => _SymptomSearchPageState(); } class _SymptomSearchPageState extends State<SymptomSearchPage> { FocusNode focusNode; SearchBloc searchBloc; String searchQuery = ""; GlobalKey<FormFieldState> _key = GlobalKey<FormFieldState>(); @override void initState() { super.initState(); focusNode = FocusNode(); searchBloc = SearchBloc(); } @override void dispose() { super.dispose(); searchBloc.close(); } @override Widget build(BuildContext context) { FocusScope.of(context).requestFocus(focusNode); return Scaffold( appBar: AppBar( title: TextFormField( onFieldSubmitted: (value) { if (_key.currentState.validate()) { _key.currentState.save(); searchBloc.add(SymptomSearchEvent(query: searchQuery)); } }, key: _key, validator: (value) { if (value.isEmpty || value.length < 3) { return "Enter at least 3 characters"; } return null; }, onSaved: (value) { searchQuery = value.trim(); }, focusNode: focusNode, style: TextStyle( fontSize: 16, color: Colors.black, fontFamily: 'Montserrat', fontWeight: FontWeight.normal, ), keyboardType: TextInputType.text, decoration: InputDecoration( contentPadding: EdgeInsets.all(0), border: UnderlineInputBorder( borderSide: BorderSide(color: Colors.red[700]), ), hintText: 'Search for symptom', labelStyle: TextStyle( fontSize: 18, color: Colors.red[700], fontFamily: 'Montserrat', fontWeight: FontWeight.w500, ), suffix: IconButton( padding: EdgeInsets.all(0), icon: Icon(Icons.search), onPressed: () { if (_key.currentState.validate()) { _key.currentState.save(); searchBloc.add(SymptomSearchEvent(query: searchQuery)); } }, ), ), ), ), body: Container( child: BlocBuilder( bloc: searchBloc, builder: (BuildContext context, state) { if (state is SearchUninitialisedState) { return Center( child: Text('Search for the symptom here.'), ); } else if (state is SearchFetchingState) { return Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, )); } else if (state is SearchErrorState) { return Center( child: Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), )); } else if (state is SearchEmptyState) { return Center( child: RichText( textAlign: TextAlign.center, text: TextSpan(children: [ TextSpan( text: "Nothing found for\n\n", style: Theme.of(context).textTheme.body1.copyWith( fontSize: 15, color: Colors.black, )), TextSpan( text: searchQuery, style: Theme.of(context).textTheme.headline.copyWith( fontSize: 17, color: Colors.blue[700], fontWeight: FontWeight.w500), ) ]), ), ); } else if (state is SearchSymptomFetchedState) { return Padding( padding: EdgeInsets.only(right: 10, left: 10), child: Container( child: ListView.separated( shrinkWrap: true, physics: BouncingScrollPhysics(), scrollDirection: Axis.vertical, itemCount: state.symptoms.length, itemBuilder: (BuildContext context, int index) { return SymptomBlock(symptom: state.symptoms[index]); }, separatorBuilder: (BuildContext context, int index) { return SizedBox( height: 15.0, ); }, ), ), ); } }, ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/passwordchange.dart
import 'package:flutter/material.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class ChangePasswordPage extends StatelessWidget { @override Widget build(BuildContext context) { final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return Scaffold( appBar: AppBar( backgroundColor: Color(0xfff2fcfe).withOpacity(0.8), elevation: 0, title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Change Password', style: Theme.of(context).textTheme.headline), SizedBox( width: 0.03 * width, ), Image.asset( 'assets/images/icons/padlock.png', width: 0.07 * width, ), ], ), ), backgroundColor: Theme.of(context).scaffoldBackgroundColor, body: ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: SingleChildScrollView( child: Stack( children: <Widget>[ _LinearGradient(), Column( children: <Widget>[ SizedBox( height: 0.05 * height, ), SizedBox( height: 0.15 * height, ), PasswordChangeForm(), ], ), ], ), ), ), ); } } class _LinearGradient extends StatelessWidget { const _LinearGradient({ Key key, }) : super(key: key); @override Widget build(BuildContext context) { return Column( children: <Widget>[ Container( height: MediaQuery.of(context).size.height * 0.4, decoration: BoxDecoration( gradient: LinearGradient( colors: [ Color(0xfff2fcfe).withOpacity(0.8), Color(0xff1c92d2).withOpacity(0.8), ], begin: Alignment.topCenter, end: Alignment.bottomCenter, ), ), ), Container( height: MediaQuery.of(context).size.height * 0.6, decoration: BoxDecoration( gradient: LinearGradient( colors: [ Color(0xfff2fcfe).withOpacity(0.8), Color(0xff1c92d2).withOpacity(0.8), ], end: Alignment.topCenter, begin: Alignment.bottomCenter, ), ), ) ], ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/aboutPage.dart
import 'package:flutter/material.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class AboutPage extends StatelessWidget { @override Widget build(BuildContext context) { final width = MediaQuery.of(context).size.width; return Stack( children: <Widget>[ _LinearGradient(), Scaffold( backgroundColor: Colors.transparent, appBar: AppBar( backgroundColor: Colors.transparent, elevation: Theme.of(context).appBarTheme.elevation, title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('About Us', style: Theme.of(context) .textTheme .headline .copyWith(color: Colors.black)), SizedBox( width: 0.035 * width, ), Image.asset( 'assets/images/icons/about.png', width: 0.07 * width, ), ], ), ), drawer: AppDrawer(), body: Container( child: AboutPageCard(), ), ), ], ); } } class _LinearGradient extends StatelessWidget { const _LinearGradient({ Key key, }) : super(key: key); @override Widget build(BuildContext context) { return Container( child: Column( children: <Widget>[ Container( height: MediaQuery.of(context).size.height * 0.5, decoration: BoxDecoration( gradient: LinearGradient( colors: [ Color(0xfff2fcfe).withOpacity(0.8), Color(0xff1c92d2).withOpacity(0.8), ], begin: Alignment.topCenter, end: Alignment.bottomCenter, ), ), ), Container( height: MediaQuery.of(context).size.height * 0.5, decoration: BoxDecoration( gradient: LinearGradient( colors: [ Color(0xfff2fcfe).withOpacity(0.8), Color(0xff1c92d2).withOpacity(0.8), ], end: Alignment.topCenter, begin: Alignment.bottomCenter, ), ), ) ], ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/dailyWater.dart
import 'package:flutter/material.dart'; import 'package:flutter_fluid_slider/flutter_fluid_slider.dart'; import 'package:nirogi/src/themes/glass_painter.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; class DailyWater extends StatefulWidget { @override _DailyWaterState createState() => _DailyWaterState(); } class _DailyWaterState extends State<DailyWater> with SingleTickerProviderStateMixin { int bodyWeight = 70; int glassVolume = 240; double litre = 0; double glass = 0; String waterInLitre = '__ Litre'; String waterInGlass = '__ Glasses'; String volume = '240 ml'; int fullGlasses = 0; double lastGlassVolume = 1.0; Animation<double> waterLevelAnimation; AnimationController waterLevelAnimationController; void calculateWater(int weight) { double divider = glassVolume / 1000; litre = weight * 0.031415897987; glass = litre / divider; waterInLitre = litre.toStringAsFixed(3) + ' Litre'; waterInGlass = glass.toStringAsFixed(1) + ' Glasses'; volume = glassVolume.toString() + ' ml'; fullGlasses = glass.floor(); lastGlassVolume = double.parse((glass - fullGlasses).toStringAsFixed(1)); waterLevelAnimationController.reset(); waterLevelAnimationController.forward(); } @override void initState() { super.initState(); waterLevelAnimationController = AnimationController(duration: const Duration(seconds: 5), vsync: this); waterLevelAnimation = Tween<double>(begin: 0, end: 1).animate(waterLevelAnimationController) ..addListener(() { setState(() {}); }); waterLevelAnimationController.forward(); } @override Widget build(BuildContext context) { final List<WaterGlass> waterGlassList = []; for (int i = 0; i < fullGlasses; i++) { waterGlassList.add(WaterGlass( waterLevelAnimation: waterLevelAnimation, finalGlassVolume: 1, )); } if (lastGlassVolume != 0) { waterGlassList.add(WaterGlass( waterLevelAnimation: waterLevelAnimation, finalGlassVolume: lastGlassVolume, )); } return Scaffold( appBar: AppBar( centerTitle: true, title: Row( children: <Widget>[ Text( 'Water Requirement', style: Theme.of(context).textTheme.headline, ), SizedBox( width: 14, ), ], ), ), body: ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.fromLTRB(18, 15, 18, 8), child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.fromLTRB(10, 10, 10, 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Column( children: <Widget>[ Text( 'Your Body', style: TextStyle( fontSize: 18, fontWeight: FontWeight.w500), ), Text( 'Weight:', style: TextStyle( fontSize: 25, fontWeight: FontWeight.w500), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: <Widget>[ Text( bodyWeight.toString(), style: TextStyle( fontSize: 50, ), ), SizedBox( width: 2, ), Text( 'kg', style: TextStyle( fontSize: 17, ), ), ], ), ], ), ), Padding( padding: const EdgeInsets.fromLTRB(8, 20, 8, 18), child: Text( 'Slide the cirlce to select your weight.', style: TextStyle( fontSize: 15, ), ), ), Padding( padding: const EdgeInsets.fromLTRB(8, 8, 8, 8), child: FluidSlider( value: bodyWeight.toDouble(), min: 20, max: 150, onChanged: (double newValue) { setState(() { bodyWeight = newValue.round(); waterInLitre = '__ Litre'; waterInGlass = '__ Glasses'; }); }, sliderColor: Color(0xFF1E8EE7), thumbColor: Colors.white, valueTextStyle: TextStyle( color: Colors.black, fontWeight: FontWeight.w500, fontSize: 18, ), start: Image( image: AssetImage('assets/images/icons/thinman.png'), color: Colors.white, ), end: Image( image: AssetImage('assets/images/icons/fatman.png'), color: Colors.white, ), ), ), SizedBox( height: 30, ), RaisedButton( color: Colors.green, child: Text( 'Calculate Daily Requirement', style: TextStyle(fontSize: 13, color: Colors.white), ), onPressed: () { setState(() { calculateWater(bodyWeight); }); }, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30.0), ), ), SizedBox( height: 25, ), Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: <Widget>[ Text( waterInLitre, style: TextStyle( color: Colors.green, fontWeight: FontWeight.w500, fontSize: 23, ), ), Padding( padding: const EdgeInsets.fromLTRB(10, 0, 10, 0), child: Text('OR')), Text( waterInGlass, style: TextStyle( color: Colors.green, fontWeight: FontWeight.w500, fontSize: 23, ), ), ], ), SizedBox( height: 25, ), Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: Wrap( spacing: 3, alignment: WrapAlignment.center, children: waterGlassList.map((glass) { return glass; }).toList()), ), SizedBox( height: 4, ), Container( width: 330, height: 1, color: Colors.black, ), SizedBox( height: 25, ), WaterRecommendationBox( waterInLitre: waterInLitre, waterInGlass: waterInGlass), SizedBox( height: 25, ), Icon(Icons.keyboard_arrow_down), Icon(Icons.keyboard_arrow_down), Icon(Icons.keyboard_arrow_down), Padding( padding: const EdgeInsets.fromLTRB(8, 28, 8, 4), child: Text( 'Additional Settings', style: TextStyle( fontSize: 22, fontWeight: FontWeight.w500, color: Colors.teal[700]), ), ), Container( width: 230, height: 1, color: Colors.black, ), SizedBox( height: 30, ), Container( decoration: BoxDecoration( border: Border.all(), borderRadius: BorderRadius.circular(20), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Expanded( child: Padding( padding: const EdgeInsets.fromLTRB(8, 8, 4, 8), child: Text( 'Glass Size', style: TextStyle( fontSize: 20, fontWeight: FontWeight.w400), textAlign: TextAlign.center, ), ), ), Container( width: 1, height: 30, color: Colors.black87, ), Padding( padding: const EdgeInsets.fromLTRB(12, 8, 12, 8), child: GestureDetector( child: CircleAvatar( child: Icon(Icons.remove), ), onTap: () { setState(() { if (glassVolume > 100) { glassVolume--; } calculateWater(bodyWeight); }); }, ), ), Text( volume, style: TextStyle( fontSize: 20, fontWeight: FontWeight.w400), ), Padding( padding: const EdgeInsets.fromLTRB(12, 8, 12, 8), child: GestureDetector( child: CircleAvatar( child: Icon(Icons.add), ), onTap: () { setState(() { glassVolume++; calculateWater(bodyWeight); }); }, ), ), ], ), ), SizedBox( height: 60, ), Text( 'It is recommended to drink additional 350ml of water for every 30 minutes of exercise you do.', style: TextStyle(fontSize: 16), ), SizedBox( height: 20, ), Text( 'Note: Your water intake requirement will vary according to your health and activity levels.', style: TextStyle( fontSize: 17, fontWeight: FontWeight.w700, ), ), SizedBox( height: 25, ), ], ), ), ), ), ); } } class WaterRecommendationBox extends StatelessWidget { const WaterRecommendationBox({ Key key, @required this.waterInLitre, @required this.waterInGlass, }) : super(key: key); final String waterInLitre; final String waterInGlass; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.fromLTRB(10, 10, 10, 30), child: Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'Recommended Daily Water Intake', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500), ), SizedBox( height: 15, ), Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Text( waterInLitre, style: TextStyle( color: Color(0xFF33BBEA), fontWeight: FontWeight.w500, fontSize: 28, ), ), SizedBox( height: 10, ), Text( 'OR', style: TextStyle(fontSize: 16), ), SizedBox( height: 10, ), Text( waterInGlass, style: TextStyle( color: Color(0xFF1375BC), fontWeight: FontWeight.w500, fontSize: 26, ), ), ], ), ), ], ), ), Expanded( child: SizedBox( width: 170, child: Image( image: AssetImage('assets/images/icons/drinkman.png'), fit: BoxFit.fill, ), ), ), ], ), ); } } class WaterGlass extends StatelessWidget { final double finalGlassVolume; const WaterGlass({ Key key, @required this.waterLevelAnimation, this.finalGlassVolume, }) : super(key: key); final Animation<double> waterLevelAnimation; @override Widget build(BuildContext context) { return Container( margin: EdgeInsets.all(6), width: 37, height: 55, child: CustomPaint( painter: GlassPainter( filledPercent: finalGlassVolume * waterLevelAnimation.value), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/incompatibleFoodsMenuPage.dart
import 'package:flutter/material.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class IncompatibleFoodsMenuPage extends StatelessWidget { final IncompatibleFoods data = IncompatibleFoods(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Incompatible Foods', style: Theme.of(context).textTheme.body2.copyWith( fontSize: 20, fontWeight: FontWeight.w500, ), ), SizedBox( width: 14, ), Stack( children: <Widget>[ Image.asset( 'assets/images/icons/breakfast.png', width: 50, ), Positioned( bottom: 0, right: 0, child: Image.asset( 'assets/images/icons/close.png', width: 20, color: Colors.red[700], ), ), ], ) ], ), ), body: Padding( padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 15), child: Container( child: Column( children: <Widget>[ Text( 'Incompatible Foods to Eat With:', style: Theme.of(context).textTheme.body2.copyWith( fontSize: 18, fontWeight: FontWeight.w600, color: Colors.red[700], ), ), SizedBox( height: 10, ), Expanded( child: ScrollConfiguration( child: GridView.count( primary: false, crossAxisSpacing: 5, mainAxisSpacing: 5, crossAxisCount: 2, childAspectRatio: 1.2, children: List.generate( foodData.length, (index) { return Center( child: FoodMenuBox( indexNo: index, thefood: foodData[index], ), ); }, ), ), behavior: RemoveEndOfListIndicator(), ), ), ], ), ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/screens.dart
export 'aboutPage.dart'; export 'diseasesPage.dart'; export 'healthNewsPage.dart'; export 'homepage.dart'; export 'symptomsPage.dart'; export 'loginsignup.dart'; export 'profilepage.dart'; export 'profileedit.dart'; export 'passwordchange.dart'; export 'ForumPage.dart'; export 'foodTipsPage.dart'; export 'healthToolsPage.dart'; export 'firstAidPage.dart'; export 'showBMI.dart'; export 'editPost.dart'; export 'eachFirstAidPage.dart'; export 'showFoods.dart'; export 'createPost.dart'; export 'showDrugs.dart'; export 'incompatibleFoodsPage.dart'; export 'calculateBMI.dart'; export 'bloodDonationPage.dart'; export 'eachProvincePage.dart'; export 'eachDrug.dart'; export 'dev_info_page.dart'; export 'eachPost.dart'; export 'eachDisease.dart'; export 'eachSymptom.dart'; export 'viewProfile.dart'; export 'categoryForum.dart'; export 'incompatibleFoodsMenuPage.dart'; export 'dailyWater.dart'; export 'imageModify.dart'; export 'disease_search_page.dart'; export 'symptom_search_page.dart'; export 'drug_search_page.dart'; export 'bmiHistory.dart';
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/incompatibleFoodsPage.dart
import 'package:flutter/material.dart'; import 'package:flutter_swiper/flutter_swiper.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; class IncompatibleFoodsPage extends StatelessWidget { final IncompatibleFoods data = IncompatibleFoods(); final int indexer; IncompatibleFoodsPage({Key key, @required this.indexer}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Incompatible Foods', style: Theme.of(context).textTheme.headline), SizedBox( width: 14, ), ], ), ), body: Column( children: <Widget>[ SizedBox( height: 15, ), Expanded( child: Padding( padding: const EdgeInsets.all(8.0), child: Container( child: Swiper( index: indexer, viewportFraction: 0.85, scale: 0.5, itemBuilder: (BuildContext context, int index) { return FoodBox( thefood: foodData[index], ); }, itemCount: foodData.length, control: SwiperControl(color: Colors.pinkAccent[100]), ), ), ), ), SizedBox( height: 30, ), ], )); } } class FoodBox extends StatelessWidget { final IncompatibleFoods thefood; const FoodBox({ Key key, this.thefood, }) : super(key: key); @override Widget build(BuildContext context) { return ClipRRect( borderRadius: BorderRadius.only( topLeft: Radius.circular(20), topRight: Radius.circular(100), bottomLeft: Radius.circular(20), bottomRight: Radius.circular(4)), child: Card( child: Container( child: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SizedBox( height: 8, ), Text( 'Don\'t Eat:', style: TextStyle( fontSize: 25, ), ), SizedBox( height: 150, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( thefood.foodName, style: TextStyle( fontSize: 40, fontFamily: 'Karla', ), ), Expanded( child: FadeInImage.assetNetwork( image: thefood.imageUrl, placeholder: "assets/gifs/loading.gif", ), ), ], ), ), SizedBox( height: 8, ), Text( 'With:', style: TextStyle( fontSize: 25, ), ), TheList(thefood: thefood), ], ), ), color: Theme.of(context).canvasColor, ), ), ); } } class TheList extends StatelessWidget { const TheList({ Key key, @required this.thefood, }) : super(key: key); final IncompatibleFoods thefood; @override Widget build(BuildContext context) { return Expanded( child: Stack( children: <Widget>[ Padding( padding: const EdgeInsets.all(12.0), child: Card( child: Center( child: ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: ListView.separated( shrinkWrap: true, scrollDirection: Axis.vertical, itemCount: thefood.incompatibleFoods.length, itemBuilder: (BuildContext context, int index) { return FoodName( foods: thefood.incompatibleFoods[index], ); }, separatorBuilder: (BuildContext context, int index) { return Container( color: Color(0xFFA9A9A9), width: 100, height: 1.50, ); }, ), ), ), ), ), ], ), ); } } class FoodName extends StatelessWidget { final String foods; const FoodName({ Key key, this.foods, }) : super(key: key); @override Widget build(BuildContext context) { return Container( child: Padding( padding: const EdgeInsets.all(5.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ //TODO: Add Images here // Padding( // padding: const EdgeInsets.all(8.0), // child: Image( // image: AssetImage('assets/images/icons/foodtips.png'), // fit: BoxFit.contain, // ), // ), Text( foods, style: TextStyle( fontSize: 19, ), ), ], ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/bmiHistory.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:nirogi/src/bloc/blocs.dart'; import 'package:nirogi/src/bloc/bmi_state.dart'; import 'package:nirogi/src/bloc/events.dart'; import 'package:nirogi/src/bloc/states.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/repository/repositories.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; class BmiHistory extends StatefulWidget { @override _BmiHistoryState createState() => _BmiHistoryState(); } class _BmiHistoryState extends State<BmiHistory> { Future<List<Bmi>> bmis; @override void initState() { super.initState(); bmis = bmiRepository.getBmiRecords(); } @override Widget build(BuildContext context) { final double width = MediaQuery.of(context).size.width; return Scaffold( appBar: AppBar( actions: <Widget>[ IconButton( onPressed: () { _showDeleteModal(); }, icon: Icon( Icons.delete, size: 30, color: Colors.red, ), ) ], title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('BMI History', style: Theme.of(context).textTheme.body2.copyWith( fontSize: 22, fontWeight: FontWeight.w500, )), SizedBox( width: 0.02 * width, ), Image.asset( 'assets/images/icons/bmi.png', width: 0.075 * width, ), ], ), ), body: FutureBuilder( future: bmis, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { if (snapshot.data.length == 0) { return Center( child: Text( 'No Records Found.', style: Theme.of(context).textTheme.headline.copyWith( fontSize: 17, color: Colors.blue[700], fontWeight: FontWeight.w500), ), ); } else { return ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: SingleChildScrollView( child: Column( children: <Widget>[ Container( padding: EdgeInsets.all(10), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ DataTable( columns: <DataColumn>[ DataColumn( label: Text( 'Calculated Date', style: Theme.of(context) .textTheme .body2 .copyWith( fontSize: 18, fontWeight: FontWeight.w500, color: Colors.red[700], ), ), ), DataColumn( label: Text( 'BMI', style: Theme.of(context) .textTheme .body2 .copyWith( fontSize: 18, fontWeight: FontWeight.w500, color: Colors.red[700], ), ), ), ], rows: snapshot.data.map<DataRow>( (bmi) { return DataRow( cells: <DataCell>[ DataCell( Text(bmi.createdAt), showEditIcon: false, placeholder: false, ), DataCell( Text( bmi.value.toString(), ), placeholder: false, ), ], ); }, ).toList(), ), ], ), ) ], ), ), ); } } else if (snapshot.hasError) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 10, ), Text(snapshot.error) ], ), ); } else { return Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ); } }, ), ); } void _showDeleteModal() { BmiBloc deleteBmiBloc = BmiBloc(); showDialog( context: context, builder: (BuildContext context) { return AlertDialog( contentPadding: EdgeInsets.all(5), title: Padding( padding: const EdgeInsets.only(bottom: 10), child: Text( 'DELETE?', style: Theme.of(context) .textTheme .body1 .copyWith(fontSize: 16, color: Colors.red[700]), textAlign: TextAlign.center, ), ), content: BlocBuilder( bloc: deleteBmiBloc, builder: (BuildContext context, state) { if (state is BmiUninitiatedState) { return Text( 'Do you really want to clear the history?', style: Theme.of(context).textTheme.body2.copyWith(fontSize: 14), textAlign: TextAlign.center, ); } else if (state is BmiSendingState) { return Padding( padding: const EdgeInsets.all(8.0), child: LinearProgressIndicator(), ); } else if (state is BmiSucessState) { Fluttertoast.showToast( msg: state.message, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.black, textColor: Colors.white, fontSize: 16.0); Navigator.of(context).pop(); return Text( 'Do you really want to clear the history?', style: Theme.of(context).textTheme.body2.copyWith(fontSize: 14), textAlign: TextAlign.center, ); } else if (state is BmiErrorState) { Fluttertoast.showToast( msg: state.error, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.red, textColor: Colors.white, fontSize: 16.0); Navigator.of(context).pop(); return Text( 'Do you really want to clear the history?', style: Theme.of(context).textTheme.body2.copyWith(fontSize: 14), textAlign: TextAlign.center, ); } }, ), actions: <Widget>[ FlatButton( color: Colors.transparent, onPressed: () { Navigator.pop(context); }, child: Text( 'Cancel', style: Theme.of(context).textTheme.body2.copyWith( fontSize: 16, color: Colors.grey, ), ), ), FlatButton( color: Colors.transparent, onPressed: () { deleteBmiBloc.add(BmiClearEvent()); }, child: Text( 'Delete', style: Theme.of(context).textTheme.body2.copyWith( fontSize: 16, color: Colors.red[700], ), ), ), ], ); }, ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/showFoods.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/repository/repositories.dart'; class ShowFoods extends StatelessWidget { final FoodTipsRepository _foodTipsRepository = FoodTipsRepository(); final int diseaseId; final String disease; ShowFoods({Key key, @required this.diseaseId, @required this.disease}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: Text(disease, style: Theme.of(context).textTheme.headline), ), body: FutureBuilder<FoodTips>( future: _foodTipsRepository.getFoodTipsForDisease(diseaseId: diseaseId), builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return SingleChildScrollView( child: Column( children: <Widget>[ TipsBox( foods: snapshot.data.toeat, heading: 'Foods To Eat: ', headingColor: Colors.green[600], lineColor: Colors.green, backgroundColor: Colors.green[100], tipIcon: Icons.check, ), SizedBox( height: 30, ), TipsBox( foods: snapshot.data.toavoid, heading: 'Foods To Avoid: ', headingColor: Colors.redAccent, lineColor: Colors.red, backgroundColor: Colors.red[100], tipIcon: Icons.close, ), ], ), ); } else if (snapshot.hasError) { return Column( children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 10, ), Text(snapshot.error) ], ); } else return Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ); }, ), ); } } class TipsBox extends StatelessWidget { const TipsBox({ Key key, @required this.foods, @required this.heading, this.headingColor, this.lineColor, this.tipIcon, this.backgroundColor, }) : super(key: key); final List<dynamic> foods; final String heading; final Color lineColor; final Color headingColor; final Color backgroundColor; final IconData tipIcon; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.fromLTRB(5, 10, 5, 20), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.fromLTRB(0, 5, 0, 2), child: Text( heading, style: TextStyle( fontFamily: Theme.of(context).textTheme.headline.fontFamily, color: headingColor, fontSize: 22), ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( height: 2.0, color: lineColor, width: 100, ), Padding( padding: const EdgeInsets.fromLTRB(6, 0, 6, 0), child: Icon( tipIcon, color: lineColor, ), ), Container( height: 2.0, color: lineColor, width: 100, ), ], ), SizedBox( height: 3.0, ), Container( height: 250, padding: EdgeInsets.symmetric(horizontal: 10), child: ListView.separated( physics: BouncingScrollPhysics(), scrollDirection: Axis.horizontal, itemCount: foods.length, itemBuilder: (BuildContext context, int index) { return FoodCard( foods: foods[index].name, backgroundColor: backgroundColor, imageUrl: foods[index].imageUrl, ); }, separatorBuilder: (BuildContext context, int index) { return SizedBox( width: 13.0, ); }, ), ), ], ), ); } } class FoodCard extends StatelessWidget { const FoodCard({ Key key, @required this.foods, @required this.imageUrl, this.backgroundColor, }) : super(key: key); final String foods; final String imageUrl; final Color backgroundColor; @override Widget build(BuildContext context) { return ClipRRect( borderRadius: BorderRadius.circular(10), child: Container( color: backgroundColor, height: 60.0, child: Stack( overflow: Overflow.clip, children: <Widget>[ Container( height: 300, width: 200, child: FadeInImage.assetNetwork( image: imageUrl, placeholder: "assets/gifs/loading.gif", width: 30, fit: BoxFit.cover, ), ), Positioned( left: 0.0, bottom: 0.0, height: 290, width: 200, child: Container( decoration: BoxDecoration( gradient: LinearGradient(colors: [ Colors.black.withOpacity(0.5), Colors.black.withOpacity(0) ], begin: Alignment.bottomCenter, end: Alignment.topCenter), ), ), ), Positioned( bottom: 7, left: 10, child: Text( foods, style: TextStyle( fontFamily: Theme.of(context).textTheme.headline.fontFamily, color: Colors.white, fontSize: 18), ), ), ], ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/createPost.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:nirogi/main.dart'; import 'package:nirogi/src/bloc/blocs.dart'; import 'package:nirogi/src/bloc/events.dart'; import 'package:nirogi/src/bloc/states.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:fluttertoast/fluttertoast.dart'; class CreatePost extends StatefulWidget { final int categoryKey; CreatePost({this.categoryKey = 1}); @override _CreatePostState createState() => _CreatePostState(); } class _CreatePostState extends State<CreatePost> { GlobalKey<FormState> _createPostField = GlobalKey<FormState>(); Post post; Category categoryValue; PostBloc addPostBloc; @override void initState() { post = Post(category: categories[widget.categoryKey - 1]); categoryValue = categories[widget.categoryKey - 1]; super.initState(); addPostBloc = PostBloc(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Create Post', style: Theme.of(context).textTheme.headline), SizedBox( width: 14, ), Image.asset( 'assets/images/icons/create.png', width: 30, ), ], ), ), body: ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: SingleChildScrollView( child: Container( padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20), child: Column( children: <Widget>[ Row( children: <Widget>[ Container( height: 40, width: 40, decoration: BoxDecoration( color: Colors.red[50], shape: BoxShape.circle, image: DecorationImage( image: AssetImage( 'assets/images/icons/profile.png', ), fit: BoxFit.contain, ), ), ), SizedBox( width: 10, ), Text( loggedinUser.name, style: Theme.of(context).textTheme.body2.copyWith( fontSize: 18, ), ), ], ), SizedBox( height: 10, ), Form( key: _createPostField, child: Column( children: <Widget>[ TextFormField( onSaved: (String value) { post.title = value.trim(); }, validator: (String value) { if (value.trim().isEmpty) { return "Empty title provided."; } return null; }, style: TextStyle( fontSize: 18, color: Colors.black, fontFamily: 'Montserrat', fontWeight: FontWeight.w500, ), decoration: InputDecoration( border: UnderlineInputBorder( borderSide: BorderSide(color: Colors.red[700]), ), labelText: 'Title', labelStyle: TextStyle( fontSize: 18, color: Colors.red[700], fontFamily: 'Montserrat', fontWeight: FontWeight.w500, ), icon: Icon( Icons.title, color: Colors.blue, ), ), ), SizedBox( height: 10, ), TextFormField( onSaved: (String value) { post.body = value.trim(); }, validator: (String value) { if (value.trim().isEmpty) { return "Empty body provided."; } return null; }, style: TextStyle( fontSize: 16, color: Colors.black, fontFamily: 'Montserrat', fontWeight: FontWeight.normal, ), keyboardType: TextInputType.multiline, maxLines: null, decoration: InputDecoration( border: UnderlineInputBorder( borderSide: BorderSide(color: Colors.red[700]), ), labelText: 'Body', labelStyle: TextStyle( fontSize: 18, color: Colors.red[700], fontFamily: 'Montserrat', fontWeight: FontWeight.w500, ), icon: Icon( Icons.subject, color: Colors.blue, ), ), ), SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Container( child: DropdownButton<Category>( value: categoryValue, elevation: 0, onChanged: (Category newValue) { setState(() { categoryValue = newValue; }); post.category = categoryValue; }, items: categories .map<DropdownMenuItem<Category>>( (Category value) { return DropdownMenuItem( value: value, child: Text( value.category, maxLines: 3, overflow: TextOverflow.ellipsis, style: Theme.of(context) .textTheme .body2 .copyWith( fontSize: 16, ), ), ); }).toList()), ), FlatButton( onPressed: () { if (_createPostField.currentState.validate()) { _createPostField.currentState.save(); addPostBloc.add(CreateNewPostevent(post: post)); } }, child: Text( 'SAVE', style: Theme.of(context).textTheme.body2.copyWith( fontSize: 20, color: Colors.blue, fontWeight: FontWeight.w500, ), ), ) ], ), ], ), ), BlocListener( child: SizedBox(), bloc: addPostBloc, listener: (BuildContext context, PostState state) { if (state is AddPostUninitiatedState) { return SizedBox(); } else if (state is AddPostSendingState) { return Container( child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ), ); } else if (state is AddPostSucessState) { Fluttertoast.showToast( msg: state.message, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.black, textColor: Colors.white, fontSize: 16.0); Navigator.pop(context); return SizedBox(); } else { var errorstate = state as AddPostErrorState; Fluttertoast.showToast( msg: errorstate.error, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.red, textColor: Colors.white, fontSize: 16.0); Navigator.pop(context); return SizedBox(); } }, ) ], ), ), ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/eachNews.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/repository/repositories.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:flutter_html/flutter_html.dart'; import 'package:html/dom.dart' as dom; class EachNews extends StatefulWidget { final NewsItem news; EachNews({@required this.news}); @override _EachNewsState createState() => _EachNewsState(); } class _EachNewsState extends State<EachNews> { ScrollController _customController; Future<NewsItem> news; bool _isCollapsed = false; @override void initState() { super.initState(); news = newsRepository.getNewsItem(newsId: widget.news.newsId); _customController = ScrollController() ..addListener( () => setState( () { _isCollapsed = (_customController.offset <= kToolbarHeight) ? false : true; }, ), ); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Theme.of(context).scaffoldBackgroundColor, body: FutureBuilder<NewsItem>( future: news, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: NestedScrollView( controller: _customController, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverAppBar( expandedHeight: 200.0, floating: false, pinned: true, centerTitle: true, title: _isCollapsed ? Text( widget.news.title, style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, color: Colors.red[700], fontWeight: FontWeight.w500, ), ) : Text( widget.news.title, style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, color: Colors.transparent, fontWeight: FontWeight.w500, ), ), flexibleSpace: FlexibleSpaceBar( background: FadeInImage.assetNetwork( image: widget.news.imageUrl, placeholder: "assets/gifs/loading.gif", fit: BoxFit.cover, ), ), ), ]; }, body: SingleChildScrollView( child: Container( padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10), child: Html( data: snapshot.data.body, customTextStyle: (dom.Node node, style) { if (node is dom.Element) { switch (node.localName) { case "code": { return style.copyWith( color: Colors.red[700], fontSize: 18, fontWeight: FontWeight.w500, fontFamily: 'Montserrat'); } break; case "b": { return style.copyWith( color: Colors.blue, fontFamily: 'Montserrat'); } break; default: { return style.copyWith( fontSize: 15, fontFamily: 'karla'); } } } }, ), ), ), ), ); } else if (snapshot.hasError) { return Container( child: Center( child: Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), ), ); } else { return Container( child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ), ); } }, ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/eachPost.dart
import 'package:flutter/material.dart'; import 'package:flutter/painting.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:nirogi/main.dart'; import 'package:nirogi/src/bloc/blocs.dart'; import 'package:nirogi/src/bloc/comment_state.dart'; import 'package:nirogi/src/bloc/events.dart'; import 'package:nirogi/src/bloc/getcomments_event.dart'; import 'package:nirogi/src/bloc/states.dart'; import 'package:nirogi/src/constants/env.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/screens/screens.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class EachPost extends StatefulWidget { Post post; EachPost({ @required this.post, Key key, }) : super(key: key); @override _EachPostState createState() => _EachPostState(); } class _EachPostState extends State<EachPost> { VoteBloc voteBloc; GetPostsBloc getPostsBloc; PostBloc addPostBloc; CommentBloc commentBloc; Comment comment; @override void initState() { super.initState(); comment = Comment(); voteBloc = VoteBloc(); getPostsBloc = GetPostsBloc(); getAllCommentsBloc.add(GetAllCommentsEvent( postId: widget.post.postId, sort: dropdownValue.title)); addPostBloc = PostBloc(); } void _showDeletePostModal() { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( contentPadding: EdgeInsets.all(5), title: Padding( padding: const EdgeInsets.only(bottom: 10), child: Text( 'Delete?', style: Theme.of(context) .textTheme .body1 .copyWith(fontSize: 16, color: Colors.red[700]), textAlign: TextAlign.center, ), ), content: Text( 'Do you really want to delete this post?', style: Theme.of(context).textTheme.body2.copyWith(fontSize: 14), textAlign: TextAlign.center, ), actions: <Widget>[ FlatButton( color: Colors.transparent, onPressed: () { Navigator.of(context).pop(); }, child: Text( 'Cancel', style: Theme.of(context).textTheme.body2.copyWith( fontSize: 16, color: Colors.grey, ), ), ), FlatButton( color: Colors.transparent, onPressed: () { addPostBloc.add(DeletePostEvent(postId: widget.post.postId)); Navigator.pop(context); Navigator.pop(context); getPostsBloc.add(GetAllPostsEvent(sort: 'popular')); }, child: Text( 'Delete', style: Theme.of(context).textTheme.body2.copyWith( fontSize: 16, color: Colors.red[700], ), ), ), ], ); }, ); } GlobalKey<FormFieldState> _textFieldKey = GlobalKey<FormFieldState>(); bool isButtonClicked = false; DropDownChoice dropdownValue = const DropDownChoice( title: 'votes', icon: 'assets/images/icons/upvote.png', ); @override Widget build(BuildContext context) { final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return WillPopScope( child: Scaffold( bottomNavigationBar: isButtonClicked ? Padding( padding: MediaQuery.of(context).viewInsets, child: Container( color: Colors.grey.withOpacity(0.05), width: MediaQuery.of(context).size.width, padding: EdgeInsets.fromLTRB( 0.035 * width, 0.005 * height, 0, 0.005 * height), child: Row( children: <Widget>[ CircleAvatar( backgroundImage: NetworkImage("$baseUrl/${loggedinUser.imageUrl}"), ), SizedBox(width: 0.04 * width), Flexible( child: TextFormField( key: _textFieldKey, validator: (value) { if (value.isEmpty) { return "Cannot create a empty comment"; } return null; }, style: Theme.of(context).textTheme.body2.copyWith( fontSize: 16, ), decoration: InputDecoration( focusedBorder: UnderlineInputBorder( borderSide: BorderSide.none, ), hintText: "Enter your comment here", hintStyle: Theme.of(context).textTheme.body2.copyWith( fontSize: 16, ), border: UnderlineInputBorder( borderSide: BorderSide.none, ), ), keyboardType: TextInputType.multiline, ), ), SizedBox(width: 0.005 * width), IconButton( padding: EdgeInsets.all(0), icon: Icon(Icons.send), color: Colors.red[700], onPressed: () async { if (_textFieldKey.currentState.validate()) { comment.comment = _textFieldKey.currentState.value; commentBloc.add(CreateNewCommentevent( comment: comment, postId: widget.post.postId, )); } }, ), BlocBuilder( bloc: commentBloc, builder: (BuildContext context, state) { if (state is CommentUninitiatedState) { return SizedBox(); } else if (state is CommentSendingState) { return SizedBox(); } else if (state is CommentSucessState) { Fluttertoast.showToast( msg: state.message, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.black, textColor: Colors.white, fontSize: 16.0); getAllCommentsBloc.add(GetAllCommentsEvent( postId: widget.post.postId, sort: dropdownValue.title)); return SizedBox(); } else { var errorstate = state as CommentErrorState; Fluttertoast.showToast( msg: errorstate.error, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.black, textColor: Colors.white, fontSize: 16.0); return SizedBox(); } }, ) ], ), ), ) : Container( height: 0, width: 0, ), floatingActionButton: !isButtonClicked ? FloatingActionButton( heroTag: 'Add Comment', tooltip: 'Add Comment', onPressed: () { commentBloc = new CommentBloc(); setState(() { isButtonClicked = !isButtonClicked; }); }, backgroundColor: Theme.of(context).canvasColor, child: PlusFloatingIcon(), ) : Container( height: 0.0, width: 0.0, ), appBar: AppBar( backgroundColor: Theme.of(context).canvasColor, title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Post', style: Theme.of(context).textTheme.headline), SizedBox( width: 0.03 * width, ), Image.asset( 'assets/images/icons/post.png', width: 0.07 * width, ), ], ), ), body: ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: SingleChildScrollView( child: Column( children: <Widget>[ Container( margin: EdgeInsets.only(top: 0.01 * height), padding: EdgeInsets.symmetric(horizontal: 0.03 * width), child: Column( children: <Widget>[ Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ votingButtons(width, context), SizedBox( width: 0.04 * width, ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Flexible( child: Padding( padding: EdgeInsets.only(top: 5.0), child: Text( widget.post.title, maxLines: 3, overflow: TextOverflow.ellipsis, style: Theme.of(context) .textTheme .body1 .copyWith( fontSize: 16, fontWeight: FontWeight.w600, ), textAlign: TextAlign.justify, ), ), ), widget.post.canModifyPost == true ? PopupMenuButton<ForumChoice>( onSelected: (ForumChoice choice) { if (choice.title == 'Edit') { Fluttertoast.cancel(); Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return EditPost( post: widget.post); }, ), ).then((editedPost) { setState(() { widget.post = editedPost; }); }); } else { _showDeletePostModal(); } }, itemBuilder: (BuildContext context) { return editchoice.map( (ForumChoice editchoice) { return PopupMenuItem< ForumChoice>( child: ForumChoiceCard( choice: editchoice, ), value: editchoice, ); }).toList(); }, ) : SizedBox(), ], ), GestureDetector( onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return CategoryForumPage( category: widget.post.category, ); })); }, child: Container( margin: EdgeInsets.only(top: 10), padding: EdgeInsets.symmetric( horizontal: 8, vertical: 6), decoration: BoxDecoration( color: Colors.blueGrey[300], borderRadius: BorderRadius.circular(8), ), child: Text( widget.post.category.category, style: Theme.of(context) .textTheme .body2 .copyWith( fontSize: 16, fontWeight: FontWeight.w500, ), ), ), ), SizedBox( height: 0.01 * height, ), Text( widget.post.body, style: Theme.of(context) .textTheme .body2 .copyWith( fontSize: 15, ), textAlign: TextAlign.justify, ), SizedBox( height: 10, ), Row( children: <Widget>[ Image.asset( 'assets/images/icons/recent.png', height: 0.02 * height), SizedBox( width: 5, ), Text( widget.post.createdAt, style: Theme.of(context) .textTheme .body2 .copyWith( fontSize: 16, ), ), SizedBox( width: 0.02 * width, ), Image.asset('assets/images/icons/eye.png', height: 0.02 * width), SizedBox( width: 5, ), Text( widget.post.views.toString(), style: Theme.of(context) .textTheme .body2 .copyWith( fontSize: 16, ), ), Expanded( child: SizedBox(), ), GestureDetector( onTap: () { Navigator.of(context).push( MaterialPageRoute(builder: (BuildContext context) { return ViewProfile( address: widget.post.address, imageUrl: widget.post.imageUrl, name: widget.post.name, userId: widget.post.userId, ); })); }, child: Row( children: <Widget>[ Container( child: Text( widget.post.name .split(' ')[0] .length > 12 ? widget.post.name .split(' ')[0] .substring(0, 12) : widget.post.name .split(' ')[0], style: Theme.of(context) .textTheme .body2 .copyWith( fontSize: 16, color: Colors.red[700], ), ), ), SizedBox( width: 5, ), Container( height: 0.1 * width, width: 0.1 * width, decoration: BoxDecoration( color: Colors.red[50], shape: BoxShape.circle, image: DecorationImage( image: NetworkImage( "$baseUrl/${widget.post.imageUrl}", ), fit: BoxFit.cover, ), ), ) ], ), ), ], ) ], ), ), ], ), BlocListener( child: SizedBox(), bloc: addPostBloc, listener: (BuildContext context, state) { if (state is AddPostUninitiatedState) { return SizedBox(); } else if (state is AddPostSendingState) { return Container( child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ), ); } else if (state is AddPostSucessState) { Fluttertoast.showToast( msg: state.message, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.black, textColor: Colors.white, fontSize: 16.0); return SizedBox(); } else { var errorstate = state as AddPostErrorState; Fluttertoast.showToast( msg: errorstate.error, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.red, textColor: Colors.white, fontSize: 16.0); return SizedBox(); } }, ) ], ), ), SizedBox( height: 5, ), Container( color: Theme.of(context).canvasColor, padding: EdgeInsets.symmetric(horizontal: 15), child: Row( children: <Widget>[ Image.asset('assets/images/icons/comment.png', height: 20), SizedBox( width: 5, ), Text( widget.post.commentCount.toString(), style: Theme.of(context).textTheme.body2.copyWith( fontSize: 20, ), ), Expanded( child: Text( 'Comments', style: Theme.of(context).textTheme.body2.copyWith( fontSize: 18, fontWeight: FontWeight.w600, ), textAlign: TextAlign.center, ), ), DropdownButton<DropDownChoice>( value: dropdownValue, elevation: 0, onChanged: (DropDownChoice choice) { setState(() { dropdownValue = choice; }); getAllCommentsBloc.add(GetAllCommentsEvent( postId: widget.post.postId, sort: dropdownValue.title)); }, items: <DropDownChoice>[ const DropDownChoice( title: 'votes', icon: 'assets/images/icons/upvote.png', ), const DropDownChoice( title: 'time', icon: 'assets/images/icons/recent.png', ), ].map<DropdownMenuItem<DropDownChoice>>( (DropDownChoice value) { return DropdownMenuItem<DropDownChoice>( value: value, child: Row( children: <Widget>[ Image.asset( value.icon, width: 0.04 * width, ), SizedBox( width: 0.02 * width, ), Text(value.title, style: Theme.of(context) .textTheme .body1 .copyWith(fontSize: 14)) ], ), ); }).toList(), ), ], ), ), _BuildCommentsList( canModifyPost: widget.post.canModifyPost, ), ], ), ), ), ), onWillPop: _floatingPressed, ); } Widget votingButtons(double width, BuildContext context) { return BlocListener( bloc: voteBloc, listener: (BuildContext context, state) { if (state is UpvotedState || state is DownVotedState) { widget.post.voteStatus = state.voteStatus; widget.post.voteCount = state.voteCount; } }, child: BlocBuilder( bloc: voteBloc, builder: (BuildContext context, state) { if (state is VoteUninitialisedState) { return Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ GestureDetector( onTap: widget.post.voteStatus == 1 ? null : () { voteBloc .add(PostUpvoteEvent(postId: widget.post.postId)); }, child: Image.asset( 'assets/images/icons/upArrow.png', width: 0.06 * width, color: widget.post.voteStatus == 1 ? Colors.red[700] : Colors.grey, ), ), SizedBox( height: 0.02 * width, ), Text( widget.post.voteCount.toString(), style: Theme.of(context).textTheme.body2.copyWith( fontSize: 18, ), ), SizedBox( height: 0.02 * width, ), GestureDetector( onTap: widget.post.voteStatus == -1 ? null : () { voteBloc.add( PostDownVoteEvent(postId: widget.post.postId)); }, child: Image.asset( 'assets/images/icons/downArrow.png', width: 0.06 * width, color: widget.post.voteStatus == -1 ? Colors.red[700] : Colors.grey, ), ), ], ); } else if (state is UpVoteSendingState || state is DownVoteSendingState) { return Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ GestureDetector( onTap: null, child: Image.asset( 'assets/images/icons/upArrow.png', width: 0.06 * width, color: Colors.grey, ), ), SizedBox( height: 0.02 * width, ), Text( widget.post.voteCount.toString(), style: Theme.of(context).textTheme.body2.copyWith( fontSize: 18, ), ), SizedBox( height: 0.02 * width, ), GestureDetector( onTap: null, child: Image.asset( 'assets/images/icons/downArrow.png', width: 0.06 * width, color: Colors.grey, ), ), ], ); } else { return Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ GestureDetector( onTap: widget.post.voteStatus == 1 ? null : () { voteBloc .add(PostUpvoteEvent(postId: widget.post.postId)); }, child: Image.asset( 'assets/images/icons/upArrow.png', width: 0.06 * width, color: widget.post.voteStatus == 1 ? Colors.red[700] : Colors.grey, ), ), SizedBox( height: 0.02 * width, ), Text( widget.post.voteCount.toString(), style: Theme.of(context).textTheme.body2.copyWith( fontSize: 18, ), ), SizedBox( height: 0.02 * width, ), GestureDetector( onTap: widget.post.voteStatus == -1 ? null : () { voteBloc.add( PostDownVoteEvent(postId: widget.post.postId)); }, child: Image.asset( 'assets/images/icons/downArrow.png', width: 0.06 * width, color: widget.post.voteStatus == -1 ? Colors.red[700] : Colors.grey, ), ), ], ); } }, ), ); } Future<bool> _floatingPressed() async { if (isButtonClicked) { setState(() { isButtonClicked = !isButtonClicked; }); return false; } else { return true; } } } class _BuildCommentsList extends StatelessWidget { final bool canModifyPost; _BuildCommentsList({ @required this.canModifyPost, Key key, }) : super(key: key); @override Widget build(BuildContext context) { final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return BlocBuilder( bloc: getAllCommentsBloc, builder: (BuildContext context, state) { if (state is CommentsUninitialisedState) { return Container( child: Center( child: Text('not loaded'), ), ); } else if (state is CommentsEmptyState) { return Container( margin: EdgeInsets.only(top: MediaQuery.of(context).size.height * 0.3), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( "No comments found", style: Theme.of(context).textTheme.body1.copyWith( fontSize: 17, color: Colors.red, ), ), ], ), ); } else if (state is CommentsFetchingState) { return Container( height: 40, margin: EdgeInsets.only(top: MediaQuery.of(context).size.height * 0.3), child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ), ); } else if (state is CommentsErrorState) { return Container( height: 40, margin: EdgeInsets.only(top: MediaQuery.of(context).size.height * 0.3), child: Center( child: Text("error"), ), ); } final stateAsCommentsFetchedState = state as CommentsFetchedState; final comments = stateAsCommentsFetchedState.comments; return Padding( padding: EdgeInsets.only( right: 0.02 * width, top: 0.01 * height, left: 0.04 * width, bottom: 0.01 * height), child: ListView.separated( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), itemCount: comments.length, scrollDirection: Axis.vertical, itemBuilder: (BuildContext context, int index) { return CommentCard( comment: comments[index], canModifyPost: canModifyPost, ); }, separatorBuilder: (BuildContext context, int index) { return Divider( color: Colors.grey, height: 0.01 * height, ); }, ), ); }, ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/bloodDonationPage.dart
import 'package:flutter/material.dart'; import 'dart:async'; import 'package:intl/intl.dart'; import 'package:rflutter_alert/rflutter_alert.dart'; class BloodDonation extends StatefulWidget { @override _BloodDonationState createState() => _BloodDonationState(); } class _BloodDonationState extends State<BloodDonation> { String selectedDate = 'Select Date'; DateTime date = DateTime.now(); String result; bool dateSelected = false; bool toShow = false; Future<Null> selectDate(BuildContext context) async { final DateTime picked = await showDatePicker( context: context, initialDate: date, firstDate: DateTime(2018), lastDate: DateTime(2025), builder: (BuildContext context, Widget child) { return Theme( data: ThemeData.light(), child: child, ); }); if (picked != null) { setState(() { selectedDate = DateFormat("dd-MM-yyyy").format(picked); date = picked.add(Duration(days: 56)); result = DateFormat("dd-MM-yyyy").format(date); toShow = false; dateSelected = true; }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Blood Donation', style: Theme.of(context).textTheme.headline, ), SizedBox( width: 14, ), Image.asset( 'assets/images/icons/blooddonation.png', width: 30, ), ], ), ), body: Padding( padding: const EdgeInsets.all(8.0), child: Card( elevation: 2, child: Padding( padding: const EdgeInsets.fromLTRB(18, 30, 18, 0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ TopHeader(), Container( decoration: BoxDecoration( border: Border.all(), borderRadius: BorderRadius.circular(20), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Expanded( child: Padding( padding: const EdgeInsets.fromLTRB(8, 8, 4, 8), child: Text( 'Select date of last donation :', style: TextStyle( fontSize: 16, ), ), ), ), Container( width: 1, height: 30, color: Colors.black87, ), SizedBox( width: 4, ), GestureDetector( child: Row( children: <Widget>[ Text( selectedDate, style: Theme.of(context).textTheme.body1, ), Icon(Icons.keyboard_arrow_down), ], ), onTap: () { selectDate(context); }, ), ], ), ), SizedBox( height: 30, ), RaisedButton( color: Color(0xFF629DDC), child: Text( 'Calculate Next Eligible Date', style: TextStyle(fontSize: 13, color: Colors.white), ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30.0), ), onPressed: () { setState(() { toShow = true; if (dateSelected == false) { Alert( context: context, title: 'No Date Selected', desc: 'Please select the date first.', type: AlertType.warning, ).show(); toShow = false; } }); }, ), SizedBox( height: 15, ), toShow == true ? BloodDonationResult( result: result, selectedDate: selectedDate) : Container(), ], ), ), ), ), ); } } class BloodDonationResult extends StatelessWidget { const BloodDonationResult({ Key key, @required this.result, @required this.selectedDate, }) : super(key: key); final String result; final String selectedDate; @override Widget build(BuildContext context) { return Expanded( child: Padding( padding: const EdgeInsets.fromLTRB(10, 5, 10, 20), child: Card( elevation: 3, color: Theme.of(context).canvasColor, child: Column( children: <Widget>[ Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Expanded( child: Padding( padding: const EdgeInsets.fromLTRB(10, 0, 0, 0), child: Text( 'You can donate blood after $result', style: Theme.of(context).textTheme.headline, ), ), ), Expanded( child: Image( image: AssetImage('assets/images/icons/blooder.png'), fit: BoxFit.fill, ), ), ], ), ), Container( height: 1, width: 300, color: Colors.black26, ), Padding( padding: const EdgeInsets.all(5.0), child: Text( 'Date of last donation: $selectedDate', style: Theme.of(context).textTheme.body1, ), ), ], ), ), ), ); } } class TopHeader extends StatelessWidget { const TopHeader({ Key key, }) : super(key: key); @override Widget build(BuildContext context) { return Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Expanded( flex: 2, child: Column( children: <Widget>[ Row( children: <Widget>[ Text( 'Calculate Your', style: TextStyle( fontSize: 19, ), ), Container(), ], ), SizedBox( height: 5, ), Text( 'Eligible Date for Blood Donation', style: Theme.of(context).textTheme.headline, ), SizedBox( height: 35, ), ], ), ), Expanded( flex: 1, child: Padding( padding: const EdgeInsets.all(18.0), child: Image( image: AssetImage('assets/images/icons/blood-drop.png'), fit: BoxFit.contain, ), ), ), ], ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/splashScreenPage.dart
import 'package:flutter/material.dart'; class SplashPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Container( height: 192, width: 192, child: Image.asset("assets/images/logos/brand-logo-dark.png"), ) ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/profilepage.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:nirogi/main.dart'; import 'package:nirogi/src/bloc/blocs.dart'; import 'package:nirogi/src/bloc/getposts_event.dart'; import 'package:nirogi/src/bloc/states.dart'; import 'package:nirogi/src/constants/env.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/widgets/widgets.dart'; import 'createPost.dart'; class ProfilePage extends StatefulWidget { @override _ProfilePageState createState() => _ProfilePageState(); } class _ProfilePageState extends State<ProfilePage> { GetPostsBloc getPostsBloc = GetPostsBloc(); @override void initState() { super.initState(); getPostsBloc.add(GetAllMyPostsEvent()); } @override Widget build(BuildContext context) { final double height = MediaQuery.of(context).size.height; final double width = MediaQuery.of(context).size.width; return loggedinUser == null ? Scaffold( body: Column( children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 10, ), Text("Please authenticate") ], ), ) : Scaffold( floatingActionButton: Container( margin: EdgeInsets.only(bottom: 0.033 * height), child: FloatingActionButton( heroTag: 'createPost', onPressed: () { getPostsBloc.close(); Navigator.push( context, MaterialPageRoute( builder: (context) => CreatePost(), ), ); }, backgroundColor: Theme.of(context).canvasColor, child: PlusFloatingIcon(), ), ), appBar: AppBar( elevation: 0, title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Profile', style: Theme.of(context).textTheme.headline), SizedBox( width: 0.02 * width, ), Image.asset( 'assets/images/icons/profile.png', width: 0.075 * width, ), ], ), actions: <Widget>[ PopupMenuButton<Choice>( onSelected: (Choice choice) { Navigator.of(context).pushNamed('/changepw'); }, itemBuilder: (BuildContext context) { return choice.map((Choice choice) { return PopupMenuItem<Choice>( child: ChoiceCard( choice: choice, ), value: choice, ); }).toList(); }, ) ], ), body: Stack( children: <Widget>[ Column( children: <Widget>[ Stack( children: <Widget>[ Column( children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Padding( padding: EdgeInsets.only( left: 0.025 * width, right: 0.036 * width, ), child: Container( height: 0.16 * height, width: 0.16 * height, decoration: BoxDecoration( shape: BoxShape.circle, image: DecorationImage( image: NetworkImage( "$baseUrl/${loggedinUser.imageUrl}", ), fit: BoxFit.cover), ), ), ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Column( children: <Widget>[ Container( width: MediaQuery.of(context) .size .width * 0.37, child: Text( loggedinUser.name, style: Theme.of(context) .textTheme .body2 .copyWith( color: Colors.red[700], fontSize: 20), maxLines: 3, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, ), ), Container( width: 120, child: Text( loggedinUser.address ?? "JHAPA NEPAL", style: Theme.of(context) .textTheme .body2 .copyWith( fontSize: 15, ), maxLines: 3, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, ), ), ], ), OutlineButton( shape: CircleBorder(), borderSide: BorderSide( color: Colors.blue, ), onPressed: () { Navigator.pushNamed( context, '/editprofile'); }, child: Icon(Icons.edit, color: Colors.blue), ), ], ), SizedBox( height: 25, ), Column( children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Image.asset( 'assets/images/icons/post.png', width: 0.075 * width, ), SizedBox( width: 10, ), Text( 'Posts', style: Theme.of(context) .textTheme .body1 .copyWith(fontSize: 18), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( height: 1.0, color: Colors.red, width: 0.115 * width, ), SizedBox( width: 5, ), Container( height: 10, width: 10, child: Image.asset( 'assets/images/icons/blood-drop.png'), ), SizedBox( width: 5, ), Container( height: 1.0, width: 0.13 * width, color: Colors.red, ), ], ) ], ), ], ), ), ], ), ], ), ], ), Expanded( child: Container( margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10), padding: EdgeInsets.symmetric(vertical: 10), child: BlocBuilder( bloc: getPostsBloc, builder: (BuildContext context, state) { if (state is PostsUninitialisedState) { return Container( child: Center( child: Text('not loaded'), ), ); } else if (state is PostsEmptyState) { return Container( child: Center( child: Text( "No posts found", style: Theme.of(context) .textTheme .body1 .copyWith( fontSize: 17, color: Colors.red, ), ), ), ); } else if (state is PostsFetchingState) { return Container( child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ), ); } else if (state is PostsErrorState) { return Center( child: Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), ); } final stateAsPostsFetchedState = state as PostsFetchedState; final posts = stateAsPostsFetchedState.posts; return RefreshIndicator( onRefresh: () async { getPostsBloc.add(GetAllMyPostsEvent()); }, child: ListView.separated( shrinkWrap: true, physics: BouncingScrollPhysics(), itemCount: posts.length, itemBuilder: (BuildContext context, int index) { return PostBlock( post: posts[index], ); }, separatorBuilder: (BuildContext context, int index) { return SizedBox( height: 0.02 * height, ); }, ), ); }, ), ), ), ], ), ], ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/healthNewsPage.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/repository/repositories.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class HealthNewsPage extends StatefulWidget { @override _HealthNewsPageState createState() => _HealthNewsPageState(); } class _HealthNewsPageState extends State<HealthNewsPage> { Future<List<NewsItem>> allNews; @override void initState() { super.initState(); allNews = newsRepository.getAllNews(); } @override Widget build(BuildContext context) { final width = MediaQuery.of(context).size.width; return Scaffold( drawer: AppDrawer(), appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Health News', style: Theme.of(context).textTheme.headline), SizedBox( width: 0.03 * width, ), Image.asset( 'assets/images/icons/news.png', width: 0.07 * width, ), ], ), ), body: buildTopNews(context), ); } Widget buildTopNews(BuildContext context) { final height = MediaQuery.of(context).size.height; return ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: SingleChildScrollView( child: FutureBuilder( future: allNews, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return Container( padding: EdgeInsets.only(top: 0.02 * height, bottom: 0.02 * height), child: ListView.separated( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemBuilder: (BuildContext context, int index) { return NewsCard( news: snapshot.data[index], ); }, itemCount: snapshot.data.length, separatorBuilder: (BuildContext context, int index) { return SizedBox( height: 0.03 * height, ); }, ), ); } else if (snapshot.hasError) { return Center( child: Container( height: MediaQuery.of(context).size.width, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 10, ), Text(snapshot.error) ], )), ); } else { return Container( margin: EdgeInsets.fromLTRB( 0, MediaQuery.of(context).size.height * 0.4, 0, 0), height: 40, width: MediaQuery.of(context).size.width, child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, )), ); } }, ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/ForumPage.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:nirogi/src/bloc/blocs.dart'; import 'package:nirogi/src/bloc/events.dart'; import 'package:nirogi/src/bloc/states.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/screens/screens.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class ForumPage extends StatefulWidget { @override _ForumPageState createState() => _ForumPageState(); } class _ForumPageState extends State<ForumPage> { GetPostsBloc getPostsBloc = GetPostsBloc(); String sort = 'popular'; @override void initState() { super.initState(); getPostsBloc.add(GetAllPostsEvent(sort: sort)); } @override void dispose() { super.dispose(); getPostsBloc.close(); } @override Widget build(BuildContext context) { final width = MediaQuery.of(context).size.width; final height = MediaQuery.of(context).size.height; return Scaffold( floatingActionButton: Container( margin: EdgeInsets.only(bottom: 0.033 * height), child: FloatingActionButton( heroTag: 'createPost', onPressed: () async { await Navigator.push( context, MaterialPageRoute( builder: (context) => CreatePost(), ), ); getPostsBloc.add(GetAllPostsEvent(sort: sort)); }, backgroundColor: Theme.of(context).canvasColor, child: PlusFloatingIcon(), ), ), drawer: AppDrawer(), appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Health Forum', style: Theme.of(context).textTheme.headline), SizedBox( width: 0.03 * width, ), Image.asset( 'assets/images/icons/forum.png', width: 0.09 * width, ), ], ), actions: <Widget>[ PopupMenuButton<ForumChoice>( initialValue: sort == "popular" ? forumChoice[0] : forumChoice[1], onSelected: (ForumChoice choice) { if (choice.sort != sort) { setState(() { sort = choice.sort; }); getPostsBloc.add(GetAllPostsEvent(sort: sort)); } }, itemBuilder: (BuildContext context) { return forumChoice.map((ForumChoice forumChoice) { return PopupMenuItem<ForumChoice>( child: ForumChoiceCard( choice: forumChoice, ), value: forumChoice, ); }).toList(); }, ) ], ), body: BlocBuilder( bloc: getPostsBloc, builder: (BuildContext context, state) { if (state is PostsUninitialisedState) { return Container( child: Center( child: Text('not loaded'), ), ); } else if (state is PostsEmptyState) { return Container( child: Center( child: Text( "No posts found", style: Theme.of(context).textTheme.body1.copyWith( fontSize: 17, color: Colors.red, ), ), ), ); } else if (state is PostsFetchingState) { return Container( child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ), ); } else if (state is PostsErrorState) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 10, ), Text("Network Error.") ], ), ); } final stateAsPostsFetchedState = state as PostsFetchedState; final posts = stateAsPostsFetchedState.posts; return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ _BuildPostsList( posts: posts, sort: sort, getPostsBloc: getPostsBloc, ), ], ); }, ), ); } } class _BuildPostsList extends StatefulWidget { final List<Post> posts; final String sort; final GetPostsBloc getPostsBloc; _BuildPostsList( {@required this.posts, @required this.sort, @required this.getPostsBloc}); @override __BuildPostsListState createState() => __BuildPostsListState(); } class __BuildPostsListState extends State<_BuildPostsList> { @override Widget build(BuildContext context) { final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return Expanded( child: Padding( padding: EdgeInsets.only( top: 0.01 * height, right: 0.02 * width, left: 0.04 * width, bottom: 0.01 * height), child: RefreshIndicator( onRefresh: () async { widget.getPostsBloc.add(GetAllPostsEvent(sort: widget.sort)); }, child: ListView.separated( shrinkWrap: true, physics: BouncingScrollPhysics(), itemCount: widget.posts.length, scrollDirection: Axis.vertical, itemBuilder: (BuildContext context, int index) { return ForumBlock( post: widget.posts[index], ); }, separatorBuilder: (BuildContext context, int index) { return Divider( color: Colors.grey, height: 0.015 * height, ); }, ), ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/drug_search_page.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:nirogi/src/bloc/blocs.dart'; import 'package:nirogi/src/bloc/events.dart'; import 'package:nirogi/src/bloc/states.dart'; import 'package:nirogi/src/screens/screens.dart'; class DrugSearchPage extends StatefulWidget { @override _DrugSearchPageState createState() => _DrugSearchPageState(); } class _DrugSearchPageState extends State<DrugSearchPage> { FocusNode focusNode; SearchBloc searchBloc; String searchQuery = ""; GlobalKey<FormFieldState> _key = GlobalKey<FormFieldState>(); @override void initState() { super.initState(); focusNode = FocusNode(); searchBloc = SearchBloc(); } @override void dispose() { super.dispose(); searchBloc.close(); } @override Widget build(BuildContext context) { FocusScope.of(context).requestFocus(focusNode); return Scaffold( appBar: AppBar( title: TextFormField( onFieldSubmitted: (value) { if (_key.currentState.validate()) { _key.currentState.save(); searchBloc.add(DrugSearchEvent(query: searchQuery)); } }, key: _key, validator: (value) { if (value.isEmpty || value.length < 3) { return "Enter at least 3 characters"; } return null; }, onSaved: (value) { searchQuery = value.trim(); }, focusNode: focusNode, style: TextStyle( fontSize: 16, color: Colors.black, fontFamily: 'Montserrat', fontWeight: FontWeight.normal, ), keyboardType: TextInputType.text, decoration: InputDecoration( contentPadding: EdgeInsets.all(0), border: UnderlineInputBorder( borderSide: BorderSide(color: Colors.red[700]), ), hintText: 'Search for drug', labelStyle: TextStyle( fontSize: 18, color: Colors.red[700], fontFamily: 'Montserrat', fontWeight: FontWeight.w500, ), suffix: IconButton( padding: EdgeInsets.all(0), icon: Icon(Icons.search), onPressed: () { if (_key.currentState.validate()) { _key.currentState.save(); searchBloc.add(DrugSearchEvent(query: searchQuery)); } }, ), ), ), ), body: Container( child: BlocBuilder( bloc: searchBloc, builder: (BuildContext context, state) { if (state is SearchUninitialisedState) { return Center( child: Text('Search for the drug here.'), ); } else if (state is SearchFetchingState) { return Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, )); } else if (state is SearchErrorState) { return Center( child: Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), )); } else if (state is SearchEmptyState) { return Center( child: Text("Nothing fround for the query\n\n$searchQuery"), ); } else if (state is SearchDrugFetchedState) { return Padding( padding: EdgeInsets.only(right: 10, left: 10), child: Container( child: ListView.separated( shrinkWrap: true, physics: BouncingScrollPhysics(), scrollDirection: Axis.vertical, itemCount: state.drugs.length, itemBuilder: (BuildContext context, int index) { return DrugCard(drug: state.drugs[index]); }, separatorBuilder: (BuildContext context, int index) { return SizedBox( height: 15.0, ); }, ), ), ); } }, ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/imageModify.dart
import 'package:flutter/material.dart'; import 'package:flutter/painting.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:image_cropper/image_cropper.dart'; import 'package:flutter_image_compress/flutter_image_compress.dart'; import 'package:image_picker/image_picker.dart'; import 'package:nirogi/src/bloc/blocs.dart'; import 'package:nirogi/src/bloc/events.dart'; import 'package:nirogi/src/bloc/states.dart'; import 'package:nirogi/src/bloc/uploadImage_bloc.dart'; import 'dart:io'; import 'package:nirogi/src/bloc/uploadImage_state.dart'; class ModifyImage extends StatefulWidget { @override _ModifyImageState createState() => _ModifyImageState(); } class _ModifyImageState extends State<ModifyImage> { UploadBloc uploadBloc = UploadBloc(); File _image; Future getImage() async { var image = await ImagePicker.pickImage(source: ImageSource.gallery); File croppedFile = await ImageCropper.cropImage( sourcePath: image.path, maxWidth: 512, maxHeight: 512, ); var result = await FlutterImageCompress.compressAndGetFile( croppedFile.path, croppedFile.path, quality: 88, ); setState(() { _image = result; }); } @override Widget build(BuildContext context) { final width = MediaQuery.of(context).size.width; return Scaffold( appBar: AppBar( elevation: 0, title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Modify Image', style: Theme.of(context).textTheme.body1.copyWith( fontSize: 18, fontWeight: FontWeight.w500, )), SizedBox( width: 0.03 * width, ), Image.asset( 'assets/images/icons/avatar.png', width: 0.07 * width, ), ], ), ), body: Center( child: Container( margin: EdgeInsets.symmetric(vertical: 80), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Material( borderRadius: BorderRadius.circular(10), elevation: 5, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(13), color: Colors.white, ), height: width * 0.65, width: width * 0.65, child: _image == null ? GestureDetector( onTap: getImage, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Image.asset( 'assets/images/icons/photo.png', height: 80, ), Padding( padding: const EdgeInsets.all(8.0), child: Text( 'Select an Image', style: Theme.of(context) .textTheme .body2 .copyWith( fontSize: 22, fontWeight: FontWeight.w500, ), textAlign: TextAlign.center, ), ), ], ), ) : Image.file( _image, fit: BoxFit.cover, ), ), ), SizedBox( height: 20, ), BlocBuilder( bloc: uploadBloc, builder: (BuildContext context, state) { if (state is UploadInitialState) { return Container( height: 50, width: 50, ); } else if (state is UploadSendingState) { return Container( height: 50, width: 50, child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ); } else if (state is UploadSuccessState) { Fluttertoast.showToast( msg: state.message, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.black, textColor: Colors.white, fontSize: 16.0); imageCache.clear(); Navigator.of(context).pop(); return Container( height: 50, width: 50, ); } else if (state is UploadFailedState) { Fluttertoast.showToast( msg: state.error, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.red, textColor: Colors.white, fontSize: 16.0); return Container( height: 50, width: 50, ); } }, ), SizedBox( height: 20, ), OutlineButton( borderSide: BorderSide( color: Colors.blue[700], ), child: Image.asset( 'assets/images/icons/upload.png', color: Colors.blue[700], height: 30, ), onPressed: () { uploadBloc.add(UploadProfilePicture(uploadImage: _image)); }, ) ], ), ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/eachDrug.dart
import 'package:flutter/material.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class EachDrug extends StatefulWidget { final Drug eachdrug; const EachDrug({ this.eachdrug, }); @override _EachDrugState createState() => _EachDrugState(eachdrug: eachdrug); } class _EachDrugState extends State<EachDrug> { final Drug eachdrug; _EachDrugState({ this.eachdrug, }); ScrollController _customController; bool _isCollapsed = false; @override void initState() { super.initState(); _customController = ScrollController() ..addListener( () => setState( () { _isCollapsed = (_customController.offset <= kToolbarHeight) ? false : true; }, ), ); } @override Widget build(BuildContext context) { return Scaffold( body: ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: NestedScrollView( controller: _customController, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverAppBar( expandedHeight: 230.0, floating: false, pinned: true, centerTitle: true, title: _isCollapsed ? Text( eachdrug.brandName, style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, color: Colors.red[700], fontWeight: FontWeight.w500, ), ) : Text( '', style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, color: Colors.transparent, fontWeight: FontWeight.w500, ), ), flexibleSpace: FlexibleSpaceBar( background: FadeInImage.assetNetwork( image: eachdrug.imageUrl, placeholder: "assets/gifs/loading.gif", fit: BoxFit.cover, )), ), ]; }, body: SingleChildScrollView( child: Column( children: <Widget>[ _DrugInfoCard(eachdrug: eachdrug), _BuildDrugQuery( eachdrug: eachdrug, ), ], ), ), ), ), ); } } class _DrugInfoCard extends StatelessWidget { final Drug eachdrug; _DrugInfoCard({ this.eachdrug, }); @override Widget build(BuildContext context) { return Container( width: MediaQuery.of(context).size.width, padding: EdgeInsets.only(left: 20, right: 10, top: 20, bottom: 0), color: Theme.of(context).canvasColor.withOpacity(0.5), child: Container( child: Column( children: <Widget>[ Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ TitleCard(title: "Brand Name"), InfoCard( info: eachdrug.brandName, fontFamily: "Karla", fontsize: 18.0, ), ], ), Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ TitleCard(title: "Generic Name"), InfoCard( info: eachdrug.genericName, fontFamily: "Alex", color: Colors.red[700], fontsize: 23.0, ), ], ), Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ TitleCard(title: "Dose"), InfoCard( info: eachdrug.dose, fontFamily: "Karla", color: Theme.of(context).textTheme.body1.color, fontsize: 18.0, ), ], ), Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ TitleCard(title: "Summary"), InfoCard( info: eachdrug.summary, fontFamily: "Karla", color: Theme.of(context).textTheme.body1.color, fontsize: 16.0, ), ], ), ], ), ), ); } } class TitleCard extends StatelessWidget { final String title; const TitleCard({ this.title, Key key, }) : super(key: key); @override Widget build(BuildContext context) { return Container( width: 150, padding: const EdgeInsets.only(bottom: 12.0), child: Text( "$title: ", style: Theme.of(context).textTheme.body2.copyWith( fontSize: 18, fontWeight: FontWeight.w500, color: Colors.blue[300]), ), ); } } class InfoCard extends StatelessWidget { final String info; final String fontFamily; final Color color; final double fontsize; const InfoCard({ this.info, this.fontFamily, this.color, this.fontsize, Key key, }) : super(key: key); @override Widget build(BuildContext context) { return Flexible( child: Container( padding: const EdgeInsets.only(bottom: 12.0), child: Text( info, style: TextStyle( fontSize: fontsize, color: color, fontFamily: fontFamily), maxLines: 5, overflow: TextOverflow.ellipsis, ), ), ); } } class _BuildDrugQuery extends StatelessWidget { final Drug eachdrug; _BuildDrugQuery({ this.eachdrug, }); @override Widget build(BuildContext context) { final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return Padding( padding: EdgeInsets.only( right: 0.03 * width, left: 0.03 * width, bottom: 0.01 * height), child: Container( child: ListView.separated( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), itemCount: eachdrug.sections.length, scrollDirection: Axis.vertical, itemBuilder: (BuildContext context, int index) { return QueryCard( sectionInfo: eachdrug.sections[index], ); }, separatorBuilder: (BuildContext context, int index) { return Divider( height: 25, color: Colors.red[700], ); }, ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/firstAidPage.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:nirogi/src/constants/env.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/repository/repositories.dart'; import 'package:nirogi/src/screens/screens.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; class FirstAidPage extends StatefulWidget { @override _FirstAidPageState createState() => _FirstAidPageState(); } class _FirstAidPageState extends State<FirstAidPage> { ScrollController _customController; bool _isCollapsed = false; @override void initState() { super.initState(); _customController = ScrollController() ..addListener( () => setState( () { _isCollapsed = (_customController.offset <= kToolbarHeight) ? false : true; }, ), ); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Theme.of(context).scaffoldBackgroundColor, body: FutureBuilder<List<Firstaid>>( future: firstAidRepository.getFirstAids(), builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return ScrollConfiguration( child: CustomScrollView( controller: _customController, slivers: <Widget>[ SliverAppBar( expandedHeight: 300.0, floating: false, pinned: true, centerTitle: true, title: _isCollapsed ? Text( "First Aid".toUpperCase(), style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, color: Colors.red[700], fontWeight: FontWeight.w500, ), ) : Text( "First Aid".toUpperCase(), style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, color: Colors.transparent, fontWeight: FontWeight.w500, ), ), flexibleSpace: FlexibleSpaceBar( background: Image.asset( 'assets/images/logos/firstaid.jpg', fit: BoxFit.cover, )), ), SliverPadding( padding: const EdgeInsets.all(10.0), sliver: SliverGrid( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 20, childAspectRatio: 0.9, mainAxisSpacing: 20, ), delegate: SliverChildBuilderDelegate( (BuildContext context, index) { return GestureDetector( onTap: () { Navigator.of(context).push(MaterialPageRoute( builder: (BuildContext context) { return EachFirstAidPage( firstAidId: snapshot.data[index].firstAidId, title: snapshot.data[index].title, ); })); }, child: Container( decoration: BoxDecoration( boxShadow: [ BoxShadow( color: Colors.black54, offset: Offset(0, 1), spreadRadius: 1, blurRadius: 3.25) ], borderRadius: BorderRadius.circular(30), ), child: ClipRRect( borderRadius: BorderRadius.circular(30), child: Stack( children: <Widget>[ Container( decoration: BoxDecoration( image: DecorationImage( image: NetworkImage( "$baseUrl/${snapshot.data[index].imageUrl}"), fit: BoxFit.cover), ), ), Positioned( bottom: 0, left: 0, right: 0, child: Container( alignment: Alignment(0.0, 0.0), color: Colors.red, height: 40, child: Text( snapshot.data[index].title .toUpperCase(), textAlign: TextAlign.center, style: Theme.of(context) .textTheme .headline .copyWith( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16, ), ), ), ) ], ), ), ), ); }, childCount: snapshot.data.length, ), ), ) ], ), behavior: RemoveEndOfListIndicator(), ); } else if (snapshot.hasError) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 10, ), Text(snapshot.error) ], ), ); } else return Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ); }, ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/diseasesPage.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/repository/repositories.dart'; import 'package:nirogi/src/screens/screens.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class DiseasesPage extends StatelessWidget { @override Widget build(BuildContext context) { final width = MediaQuery.of(context).size.width; return Scaffold( drawer: AppDrawer(), appBar: AppBar( actions: <Widget>[ IconButton( onPressed: () { Navigator.of(context) .push(MaterialPageRoute(builder: (BuildContext context) { return DiseaseSearchPage(); })); }, icon: Icon( Icons.search, size: 30, ), ) ], title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Diseases', style: Theme.of(context).textTheme.headline), SizedBox( width: 0.03 * width, ), Image.asset( 'assets/images/icons/disease.png', width: 0.07 * width, ), ], ), ), body: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ BuildDiseaseList(), ], )); } } class BuildDiseaseList extends StatefulWidget { const BuildDiseaseList({ Key key, }) : super(key: key); @override _BuildDiseaseListState createState() => _BuildDiseaseListState(); } class _BuildDiseaseListState extends State<BuildDiseaseList> { Future<List<Disease>> allDiseases; @override void initState() { allDiseases = diseaseRepository.getAllDiseases(); super.initState(); } @override Widget build(BuildContext context) { final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return FutureBuilder( future: allDiseases, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return Expanded( child: Padding( padding: EdgeInsets.only( right: 0.02 * width, left: 0.02 * width, bottom: 0.01 * height), child: ListView.separated( shrinkWrap: true, physics: BouncingScrollPhysics(), itemCount: snapshot.data.length, scrollDirection: Axis.vertical, itemBuilder: (BuildContext context, int index) { return DiseaseBlock( disease: snapshot.data[index], ); }, separatorBuilder: (BuildContext context, int index) { return SizedBox( height: 0.02 * height, ); }, ), ), ); } else if (snapshot.hasError) { return Expanded( child: Center( child: Container( height: MediaQuery.of(context).size.width, child: Column( children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 10, ), Text(snapshot.error) ], )), ), ); } else { return Expanded( child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ), ); } }, ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/categoryForum.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:nirogi/src/bloc/blocs.dart'; import 'package:nirogi/src/bloc/events.dart'; import 'package:nirogi/src/bloc/states.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/screens/screens.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class CategoryForumPage extends StatefulWidget { final Category category; const CategoryForumPage({Key key, @required this.category}) : super(key: key); @override _CategoryForumPageState createState() => _CategoryForumPageState(); } class _CategoryForumPageState extends State<CategoryForumPage> { GetPostsBloc getPostsBloc = GetPostsBloc(); @override void initState() { super.initState(); getPostsBloc.add(GetCategoryPostsEvent( categoryId: widget.category.categoryId, )); } @override Widget build(BuildContext context) { final width = MediaQuery.of(context).size.width; final height = MediaQuery.of(context).size.height; return Scaffold( floatingActionButton: Container( margin: EdgeInsets.only(bottom: 0.033 * height), child: FloatingActionButton( heroTag: 'createPost', onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => CreatePost( categoryKey: widget.category.categoryId, ), ), ); }, backgroundColor: Colors.white, child: PlusFloatingIcon(), ), ), appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Categorized Posts', style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, fontWeight: FontWeight.w500, )), SizedBox( width: 0.03 * width, ), Image.asset( 'assets/images/icons/forum.png', width: 0.09 * width, ), ], ), ), body: BlocBuilder( bloc: getPostsBloc, builder: (BuildContext context, state) { if (state is PostsUninitialisedState) { return Container( child: Center( child: Text('not loaded'), ), ); } else if (state is PostsEmptyState) { return Column( children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/error.flr', animation: 'go', fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 10, ), Text("Network Error.") ], ); } else if (state is PostsFetchingState) { return Container( child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ), ); } else if (state is PostsErrorState) { return Container( child: Center( child: Text("ERROR"), ), ); } final stateAsPostsFetchedState = state as PostsFetchedState; final posts = stateAsPostsFetchedState.posts; return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ _BuildPostsList( posts: posts, categoryId: widget.category.categoryId, getPostsBloc: getPostsBloc, ), ], ); }, ), ); } } class _BuildPostsList extends StatefulWidget { final GetPostsBloc getPostsBloc; final List<Post> posts; final int categoryId; _BuildPostsList( {@required this.posts, @required this.categoryId, @required this.getPostsBloc}); @override __BuildPostsListState createState() => __BuildPostsListState(); } class __BuildPostsListState extends State<_BuildPostsList> { @override Widget build(BuildContext context) { final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return Expanded( child: Padding( padding: EdgeInsets.only( top: 0.01 * height, right: 0.02 * width, left: 0.04 * width, bottom: 0.01 * height), child: RefreshIndicator( onRefresh: () async { widget.getPostsBloc .add(GetCategoryPostsEvent(categoryId: widget.categoryId)); }, child: ListView.separated( shrinkWrap: true, physics: BouncingScrollPhysics(), itemCount: widget.posts.length, scrollDirection: Axis.vertical, itemBuilder: (BuildContext context, int index) { return ForumBlock( post: widget.posts[index], ); }, separatorBuilder: (BuildContext context, int index) { return Divider( color: Colors.grey, height: 0.015 * height, ); }, ), ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/showDrugs.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/repository/repositories.dart'; import 'package:nirogi/src/screens/screens.dart'; class ShowDrugs extends StatefulWidget { @override _ShowDrugsState createState() => _ShowDrugsState(); } class _ShowDrugsState extends State<ShowDrugs> { bool canPop = false; Future<List<Drug>> allDrugs; @override void initState() { super.initState(); allDrugs = drugRepository.getCommonDrug(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( actions: <Widget>[ IconButton( onPressed: () { Navigator.of(context) .push(MaterialPageRoute(builder: (BuildContext context) { return DrugSearchPage(); })); }, icon: Icon( Icons.search, size: 30, ), ) ], title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Common Drugs', style: Theme.of(context).textTheme.headline, ), SizedBox( width: 14, ), Image.asset( 'assets/images/icons/medicine.png', width: 30, ), ], ), ), body: Padding( padding: const EdgeInsets.only(top: 8.0), child: FutureBuilder( future: allDrugs, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { canPop = true; return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Expanded( child: Padding( padding: EdgeInsets.only(right: 10, left: 10), child: Container( child: ListView.separated( shrinkWrap: true, physics: BouncingScrollPhysics(), scrollDirection: Axis.vertical, itemCount: snapshot.data.length, itemBuilder: (BuildContext context, int index) { return DrugCard(drug: snapshot.data[index]); }, separatorBuilder: (BuildContext context, int index) { return SizedBox( height: 15.0, ); }, ), ), ), ), ], ); } else if (snapshot.hasError) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 10, ), Text(snapshot.error) ], ), ); } else { return Container( child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ), ); } }, ), ), ); } } class DrugCard extends StatelessWidget { final Drug drug; const DrugCard({this.drug}); @override Widget build(BuildContext context) { return GestureDetector( onTap: () { Navigator.of(context).push( MaterialPageRoute(builder: (BuildContext context) { return EachDrug( eachdrug: drug, ); }), ); }, child: Material( borderRadius: BorderRadius.circular(5), elevation: 1.0, child: Container( height: 60.0, margin: EdgeInsets.symmetric(horizontal: 5, vertical: 7), child: Row( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Container( margin: EdgeInsets.fromLTRB(5, 0, 13, 0), child: CircleAvatar( radius: 23, child: Text( drug.brandName[0], style: TextStyle( fontSize: 30, color: Colors.white, ), ), backgroundColor: Colors.lightBlue[400], ), ), Expanded( child: Text( drug.brandName, style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, ), ), ), ], ), ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/homepage.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:flutter_page_indicator/flutter_page_indicator.dart'; import 'package:flutter_swiper/flutter_swiper.dart'; import 'package:nirogi/src/bloc/change_theme_bloc.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/repository/repositories.dart'; import 'package:nirogi/src/themes/clippers.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:nirogi/src/themes/themes.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { ScrollController _customController; Future<List<Disease>> topDiseases; Future<List<Symptom>> topSymptoms; Future<List<Drug>> commonDrug; Future<List<NewsItem>> topNews; bool _isCollapsed = false; @override void initState() { super.initState(); topDiseases = diseaseRepository.getTopDiseases(); topSymptoms = symptomRepository.getTopSymptoms(); commonDrug = drugRepository.getCommonDrug(); topNews = newsRepository.getAllNews(); _customController = ScrollController() ..addListener( () => setState( () { _isCollapsed = (_customController.offset <= kToolbarHeight) ? false : true; }, ), ); } @override Widget build(BuildContext context) { final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return Scaffold( backgroundColor: Theme.of(context).scaffoldBackgroundColor, drawer: AppDrawer(), body: NestedScrollView( controller: _customController, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverAppBar( pinned: true, expandedHeight: 0.19 * height, flexibleSpace: _isCollapsed ? SizedBox() : heroClipPath(context), title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( _isCollapsed ? 'Hami Nirogi' : '', style: Theme.of(context).textTheme.headline, ), SizedBox( width: 0.02 * width, ), Container( child: _isCollapsed ? Image.asset( 'assets/images/icons/meditation.png', width: 0.065 * width, ) : SizedBox(), ) ], ), ), ]; }, body: ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ heading('Common Diseases', context), SizedBox( height: 0.01 * height, ), buildCommonDiseases(context, topDiseases), SizedBox( height: 0.02 * height, ), heading('Common Symptoms', context), SizedBox( height: 0.01 * height, ), buildCommonSymptoms(context, topSymptoms), SizedBox( height: 0.02 * height, ), heading('Common Drugs', context), SizedBox( height: 0.02 * height, ), buildCommonDrugs(), SizedBox( height: 0.03 * height, ), heading('Top News', context), _buildTopNews(context), ], ), ), ), ), ); } FutureBuilder<List<Drug>> buildCommonDrugs() { return FutureBuilder( future: commonDrug, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return Container( height: 300, child: Swiper( viewportFraction: 0.7, scale: 0.9, itemBuilder: (BuildContext context, int index) { return DrugWidget(drug: snapshot.data[index]); }, indicatorLayout: PageIndicatorLayout.COLOR, autoplay: true, loop: false, itemCount: snapshot.data.length, containerWidth: 200, ), ); } else if (snapshot.hasError) { return Column( children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 10, ), Text(snapshot.error) ], ); } else { return Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ); } }, ); } Container buildCommonSymptoms( BuildContext context, Future<List<Symptom>> topSymptoms) { final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return Container( height: 0.23 * height, padding: EdgeInsets.symmetric(horizontal: 0.01 * width), child: FutureBuilder( future: topSymptoms, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return ListView.separated( physics: BouncingScrollPhysics(), itemCount: snapshot.data.length, scrollDirection: Axis.horizontal, itemBuilder: (BuildContext context, int index) { return SymptomCard( symptom: snapshot.data[index], ); }, separatorBuilder: (BuildContext context, int index) { return SizedBox( width: 0.03 * width, ); }, ); } else if (snapshot.hasError) { return Column( children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 10, ), Text(snapshot.error) ], ); } else { return Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ); } }), ); } Column heading(String heading, BuildContext context) { final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( heading, style: TextStyle( fontSize: Theme.of(context).textTheme.display1.fontSize.toDouble() * 0.55, fontFamily: 'Montserrat', ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( height: 3.0, color: Colors.red, width: 0.18 * width, ), SizedBox( width: 5, ), Container( height: 0.02 * height, width: 0.04 * width, child: Image.asset('assets/images/icons/blood-drop.png'), ), SizedBox( width: 5, ), Container( height: 3.0, width: 0.26 * width, color: Colors.red, ), ], ) ], ); } Container buildCommonDiseases( BuildContext context, Future<List<Disease>> topDiseases) { final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return Container( height: 0.23 * height, padding: EdgeInsets.symmetric(horizontal: 0.01 * width), child: FutureBuilder<List<Disease>>( future: topDiseases, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return ListView.separated( physics: BouncingScrollPhysics(), itemCount: snapshot.data.length, scrollDirection: Axis.horizontal, itemBuilder: (BuildContext context, int index) { return DiseaseCard( disease: snapshot.data[index], ); }, separatorBuilder: (BuildContext context, int index) { return SizedBox( width: 0.03 * width, ); }, ); } else if (snapshot.hasError) { return Column( children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 10, ), Text(snapshot.error) ], ); } else { return Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ); } }, ), ); } Stack heroClipPath(BuildContext context) { final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return Stack( children: <Widget>[ Padding( padding: EdgeInsets.only(top: 0.02 * height), child: ClipPath( child: Container( margin: EdgeInsets.only(top: 1), height: 0.27 * height, color: Colors.red[700], ), clipper: HomePageBorderClipper(), ), ), Padding( padding: EdgeInsets.only(top: 0.02 * height), child: ClipPath( clipper: HomePageClipper(), child: Container( padding: EdgeInsets.fromLTRB( 0.06 * width, 0.04 * height, 0.04 * width, 0.04 * height), width: MediaQuery.of(context).size.width, height: 0.195 * height, decoration: BoxDecoration( color: Theme.of(context).primaryColor, ), child: Row( children: <Widget>[ Container( width: MediaQuery.of(context).size.width * 0.8, child: Image.asset( changeThemeBloc.state.themeData == kDarkTheme ? 'assets/images/logos/brand-logo-light.png' : 'assets/images/logos/brand-logo-dark.png', fit: BoxFit.contain, ), ), ], ), ), ), ), ], ); } Widget _buildTopNews(BuildContext context) { final height = MediaQuery.of(context).size.height; return FutureBuilder( future: topNews, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return Container( padding: EdgeInsets.only(bottom: 0.02 * height), child: ListView.separated( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemBuilder: (BuildContext context, int index) { return NewsCard( news: snapshot.data[index], ); }, itemCount: snapshot.data.length, separatorBuilder: (BuildContext context, int index) { return SizedBox( height: 0.02 * height, ); }, ), ); } else if (snapshot.hasError) { return Column( children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 10, ), Text(snapshot.error) ], ); } else { return Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ); } }, ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/calculateBMI.dart
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:nirogi/src/screens/screens.dart'; enum Gender { male, female, } const inactiveMaleColor = Color(0xFF8BB8E1); const inactiveFemaleColor = Color(0xFFF3AFD7); const activeMaleColor = Color(0XFF2B86D3); const activeFemaleColor = Color(0XFFF2669C); const inactiveHeight = 60; const activeHeight = 75; Color maleColor = Color(0xFFF5F5F5); Color femaleColor = Color(0xFFF5F5F5); String showGender = 'Male'; class CalculateBMI extends StatefulWidget { @override _CalculateBMIState createState() => _CalculateBMIState(); } class _CalculateBMIState extends State<CalculateBMI> { Gender selectedGender = Gender.male; int weightValue = 70; int bodyHeight = 170; Color maleColor = activeMaleColor; Color femaleColor = inactiveFemaleColor; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('BMI Calculator', style: Theme.of(context).textTheme.headline), SizedBox( width: 14, ), Image.asset( 'assets/images/icons/bmi.png', width: 30, ), ], ), ), body: Container( color: Theme.of(context).scaffoldBackgroundColor, padding: const EdgeInsets.fromLTRB(15, 8, 15, 45), child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: Card( child: Padding( padding: const EdgeInsets.symmetric(vertical: 6), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text( selectedGender == Gender.male ? "Male" : "Female", style: TextStyle( fontSize: 17, color: Theme.of(context).textTheme.headline.color, fontWeight: FontWeight.bold), ), Line(), Text( weightValue.toString() + 'Kg', style: TextStyle( fontSize: 17, color: Theme.of(context).textTheme.headline.color, fontWeight: FontWeight.bold), ), Line(), Text( bodyHeight.toString() + 'cm', style: TextStyle( fontSize: 17, color: Theme.of(context).textTheme.headline.color, fontWeight: FontWeight.bold), ), ], ), ), ), ), Expanded( child: Row( children: <Widget>[ Expanded( child: Column( children: <Widget>[ Expanded( child: Card( child: SizedBox( width: double.infinity, child: Padding( padding: const EdgeInsets.all(8.0), child: Column( children: <Widget>[ Text( 'GENDER', style: TextStyle( fontFamily: 'Montserrat-Medium', fontSize: 20, color: Theme.of(context) .textTheme .headline .color, ), ), SizedBox( height: 3, ), Container( height: 0.2, width: double.infinity, color: Colors.black, ), Padding( padding: EdgeInsets.only(top: 46), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ GestureDetector( onTap: () { setState(() { selectedGender = Gender.male; }); }, child: Image.asset( 'assets/images/icons/male.png', fit: BoxFit.fill, color: selectedGender == Gender.male ? activeMaleColor : inactiveMaleColor, height: selectedGender == Gender.male ? 75 : 60, ), ), Text( 'or', style: TextStyle( fontSize: 20, ), ), GestureDetector( onTap: () { setState(() { selectedGender = Gender.female; }); }, child: Image.asset( 'assets/images/icons/female.png', fit: BoxFit.fill, color: selectedGender == Gender.female ? activeFemaleColor : inactiveFemaleColor, height: selectedGender == Gender.female ? 75 : 60, ), ), ], ), ), ], ), ), ), ), ), Expanded( child: SizedBox( width: double.infinity, child: Card( child: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Text( 'WEIGHT (Kg)', style: TextStyle( fontFamily: 'Montserrat-Medium', fontSize: 20, color: Theme.of(context) .textTheme .headline .color, ), ), SizedBox( height: 3, ), Container( height: 0.1, width: double.infinity, color: Colors.black, ), Center( child: Padding( padding: const EdgeInsets.fromLTRB( 8, 28, 8, 0), child: Column( children: <Widget>[ Text( weightValue.toString(), style: TextStyle( fontSize: 30.0, ), ), SizedBox( height: 20, ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ GestureDetector( child: CircleAvatar( child: Icon(Icons.remove), ), onTap: () { if (weightValue > 30) { setState(() { weightValue--; }); } }, ), SizedBox( width: 30, ), GestureDetector( child: CircleAvatar( child: Icon(Icons.add), ), onTap: () { if (weightValue < 150) { setState(() { weightValue++; }); } }, ), ], ), ], ), ), ), ], ), ), ), ), ), ], ), ), Expanded( child: SizedBox( width: double.infinity, child: Card( child: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text( 'HEIGHT (cm)', style: TextStyle( fontFamily: 'Montserrat-Medium', fontSize: 20, color: Theme.of(context) .textTheme .headline .color, ), ), SizedBox( height: 3, ), Container( height: 0.2, width: double.infinity, color: Colors.black, ), SizedBox( height: 25, ), Text( bodyHeight.toString(), style: TextStyle( fontSize: 30.0, ), ), Padding( padding: const EdgeInsets.symmetric(vertical: 10.0), child: Slider( value: bodyHeight.toDouble(), max: 220, min: 100, activeColor: Theme.of(context) .textTheme .headline .color, onChanged: (double newValue) { setState(() { bodyHeight = newValue.round(); }); }, ), ), Expanded( child: Stack( alignment: AlignmentDirectional.bottomEnd, children: <Widget>[ Positioned( child: Image( image: selectedGender == Gender.male ? AssetImage( 'assets/images/icons/male.png') : AssetImage( 'assets/images/icons/female.png'), fit: BoxFit.fill, color: selectedGender == Gender.female ? activeFemaleColor : activeMaleColor, height: bodyHeight.toDouble(), ), ), ], ), ), SizedBox( height: 25, ), ], ), ), ), ), ), ], ), ), Padding( padding: const EdgeInsets.fromLTRB(0, 20, 0, 0), child: RaisedButton( color: selectedGender == Gender.male ? Colors.lightBlue : activeFemaleColor, child: Padding( padding: const EdgeInsets.all(10.0), child: Text( 'Calculate!', style: TextStyle(fontSize: 16, color: Colors.white), ), ), onPressed: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { double bmi = (weightValue / pow((bodyHeight / 100), 2)); return ShowBMI( bmi: bmi, ); }, ), ); }, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30.0), ), ), ) ], ), ), ); } } class Line extends StatelessWidget { const Line({ Key key, }) : super(key: key); @override Widget build(BuildContext context) { return Container( width: 0.5, color: Color(0xFFA9A9A9), height: 23, ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/eachProvincePage.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:flutter_html/flutter_html.dart'; import 'package:nirogi/src/constants/env.dart'; import 'package:nirogi/src/repository/repositories.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:html/dom.dart' as dom; class EachProvincePage extends StatefulWidget { final String title; final int provinceId; EachProvincePage({@required this.provinceId, @required this.title}); @override _EachProvincePageState createState() => _EachProvincePageState(); } class _EachProvincePageState extends State<EachProvincePage> { ScrollController _customController; bool _isCollapsed = false; @override void initState() { super.initState(); _customController = ScrollController() ..addListener( () => setState( () { _isCollapsed = (_customController.offset <= kToolbarHeight) ? false : true; }, ), ); } @override Widget build(BuildContext context) { return Scaffold( body: FutureBuilder( future: provinceRepository.getProvince(provinceId: widget.provinceId), builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: CustomScrollView( controller: _customController, slivers: <Widget>[ SliverAppBar( expandedHeight: 300.0, floating: false, pinned: true, centerTitle: true, title: _isCollapsed ? Text( widget.title, style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, color: Colors.red[700], fontWeight: FontWeight.w500, ), ) : Text( widget.title, style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, color: Colors.transparent, fontWeight: FontWeight.w500, ), ), flexibleSpace: FlexibleSpaceBar( background: FadeInImage.assetNetwork( image: "$baseUrl/${snapshot.data.imageUrl}", placeholder: "assets/gifs/loading.gif", fit: BoxFit.fitWidth, )), ), SliverList( delegate: SliverChildBuilderDelegate( (context, index) { return Padding( padding: const EdgeInsets.all(10.0), child: Html( data: snapshot.data.body, customTextStyle: (dom.Node node, style) { if (node is dom.Element) { switch (node.localName) { case "code": { return style.copyWith( color: Colors.red[700], fontSize: 20, fontWeight: FontWeight.w500, fontFamily: 'Montserrat'); } break; case "b": { return style.copyWith( color: Colors.blue, fontFamily: 'Montserrat'); } break; default: { return style.copyWith( fontSize: 16, fontFamily: 'karla'); } } } }, ), ); }, childCount: 1, ), ), ], ), ); } else if (snapshot.hasError) { return Center( child: Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), ); } else { return Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ); } }, ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/showBMI.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:nirogi/src/bloc/blocs.dart'; import 'package:nirogi/src/bloc/events.dart'; import 'package:nirogi/src/bloc/states.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/screens/screens.dart'; class ShowBMI extends StatefulWidget { final String text; final double bmi; const ShowBMI({Key key, this.text, this.bmi}) : super(key: key); @override _ShowBMIState createState() => _ShowBMIState(); } class _ShowBMIState extends State<ShowBMI> { BmiBloc bmibloc = BmiBloc(); @override Color getBmiColor(bmi) { if (bmi < 18.5) { return Colors.blue; } else if (18.5 < bmi && bmi < 25) { return Color(0xFF08D8BF); } else if (25 < bmi && bmi < 30) { return Colors.yellow; } else if (30 < bmi && bmi < 35) { return Colors.orange; } else if (35 < bmi && bmi < 40) { return Color(0xFFF37B56); } else { return Colors.red; } } Color getCircleColor(double bmi) { if (bmi < 18.5) { return Colors.lightBlue[50]; } else if (18.5 < bmi && bmi < 25) { return Color(0xFFEDFBF9); } else if (25 < bmi && bmi < 30) { return Colors.yellow[50]; } else if (30 < bmi && bmi < 35) { return Colors.orange[50]; } else if (35 < bmi && bmi < 40) { return Colors.orange[50]; } else { return Colors.red[50]; } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Result', style: Theme.of(context).textTheme.headline), SizedBox( width: 39, ), ], ), ), body: Container( child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Your BMI Score', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 30, color: Colors.blueAccent), ), ], ), CircleAvatar( backgroundColor: getCircleColor(widget.bmi), radius: 80, child: Text( widget.bmi.toStringAsFixed(1), style: TextStyle( fontWeight: FontWeight.bold, fontSize: 40, color: getBmiColor(widget.bmi), ), ), ), Column( children: <Widget>[ Result( condition: 'Underweight', bmi: '< 18.5', isIt: widget.bmi < 18.5 ? true : false, txtcolor: widget.bmi < 18.5 ? Colors.blue : Colors.white, ), Result( condition: 'Normal', bmi: '18.5 - 25', isIt: 18.5 < widget.bmi && widget.bmi < 25 ? true : false, txtcolor: 18.5 < widget.bmi && widget.bmi < 25 ? Color(0xFF08D8BF) : Colors.white, ), Result( condition: 'Overweight', bmi: '25 - 30', isIt: 25 < widget.bmi && widget.bmi < 30 ? true : false, txtcolor: 25 < widget.bmi && widget.bmi < 30 ? Colors.yellow : Colors.white, ), Result( condition: 'Obese', bmi: '30 - 35', isIt: 30 < widget.bmi && widget.bmi < 35 ? true : false, txtcolor: 30 < widget.bmi && widget.bmi < 35 ? Colors.orange : Colors.white, ), Result( condition: 'Severely Obese', bmi: '35 - 40', isIt: 35 < widget.bmi && widget.bmi < 40 ? true : false, txtcolor: 35 < widget.bmi && widget.bmi < 40 ? Color(0xFFF37B56) : Colors.white, ), Result( condition: 'Very Severely Obese', bmi: '> 40', isIt: widget.bmi > 40 ? true : false, txtcolor: widget.bmi > 40 ? Colors.red : Colors.white, ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ GestureDetector( onTap: () { bmibloc.add( BmiAddevent( bmi: Bmi(value: widget.bmi), ), ); }, child: CircleAvatar( backgroundColor: Colors.lightGreen, radius: 33, child: BlocListener( bloc: bmibloc, listener: (BuildContext context, BmiState state) { if (state is BmiSucessState) { Fluttertoast.showToast( msg: state.message, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.black, textColor: Colors.white, fontSize: 16.0); Navigator.of(context).pop(); } else if (state is BmiErrorState) { Fluttertoast.showToast( msg: state.error, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.red, textColor: Colors.white, fontSize: 16.0); Navigator.of(context).pop(); } }, child: BlocBuilder( bloc: bmibloc, builder: (BuildContext context, BmiState state) { if (state is BmiUninitiatedState) { return Icon( Icons.save, color: Colors.black, size: 33, ); } else if (state is BmiSendingState) { return CircularProgressIndicator( backgroundColor: Colors.pink, ); } return Icon( Icons.save, color: Colors.black, size: 33, ); }, ), ), ), ), GestureDetector( onTap: () { Navigator.pop(context); }, child: CircleAvatar( radius: 33, child: Icon( Icons.refresh, size: 33, ), ), ), GestureDetector( onTap: () { Navigator.of(context).push( MaterialPageRoute(builder: (BuildContext context) { return BmiHistory(); })); }, child: CircleAvatar( backgroundColor: Colors.amberAccent, radius: 33, child: Icon( Icons.history, size: 33, color: Colors.black, ), ), ), ], ), ], ), ), ); } } class Result extends StatelessWidget { final String condition; final String bmi; final bool isIt; final Color txtcolor; const Result({ Key key, this.condition, this.bmi, this.isIt, this.txtcolor, }) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 6.0, horizontal: 45), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( condition, style: TextStyle( fontSize: 19, fontWeight: FontWeight.w400, color: isIt == false ? Theme.of(context).textTheme.headline.color : txtcolor, ), ), Text( bmi, style: TextStyle( fontSize: 19, fontWeight: FontWeight.w400, color: isIt == false ? Theme.of(context).textTheme.headline.color : txtcolor, ), ), ], ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/profileedit.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:nirogi/main.dart'; import 'package:nirogi/src/bloc/blocs.dart'; import 'package:nirogi/src/bloc/events.dart'; import 'package:nirogi/src/bloc/states.dart'; import 'package:nirogi/src/constants/env.dart'; import 'package:nirogi/src/functions/functions.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/repository/repositories.dart'; import 'package:nirogi/src/screens/screens.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class EditProfile extends StatefulWidget { EditProfile({Key key}) : super(key: key); @override _EditProfileState createState() => _EditProfileState(); } class _EditProfileState extends State<EditProfile> { SignupBloc signupBloc; GlobalKey<FormState> _formKey; final User updateuser = User(); @override void initState() { super.initState(); signupBloc = SignupBloc( authenticationBloc: BlocProvider.of<AuthenticationBloc>(context), userRepository: userRepository); _formKey = GlobalKey<FormState>(); } @override Widget build(BuildContext context) { final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return Scaffold( appBar: AppBar( elevation: 0, title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Edit Profile', style: Theme.of(context).textTheme.headline), SizedBox( width: 0.03 * width, ), Image.asset( 'assets/images/icons/createpost.png', width: 0.07 * width, ), ], ), actions: <Widget>[ PopupMenuButton<Choice>( onSelected: (Choice choice) { Navigator.of(context).pushNamed('/changepw'); }, itemBuilder: (BuildContext context) { return choice.map((Choice choice) { return PopupMenuItem<Choice>( child: ChoiceCard( choice: choice, ), value: choice, ); }).toList(); }, ) ], ), body: ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: SingleChildScrollView( child: Container( child: Stack( children: <Widget>[ Column( children: <Widget>[ SizedBox( height: 0.02 * height, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Stack( children: <Widget>[ Container( height: 0.17 * height, width: 0.17 * height, decoration: BoxDecoration( shape: BoxShape.circle, ), child: CircleAvatar( backgroundImage: NetworkImage( "$baseUrl/${loggedinUser.imageUrl}", ), ), ), Positioned( top: 0.10 * height, right: 0, child: SizedBox( height: 0.06 * height, width: 0.10 * width, child: FloatingActionButton( backgroundColor: Colors.white, onPressed: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return ModifyImage(); })); }, tooltip: 'Change Avatar', child: Image.asset( 'assets/images/icons/avatar.png', width: 0.07 * width, ), ), ), ), ], ), ], ), Container( margin: EdgeInsets.symmetric( horizontal: 0.05 * width, vertical: 0.02 * height), padding: EdgeInsets.all(20.0), child: Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Container( padding: EdgeInsets.fromLTRB(0, 0, 0, 0.004 * height), child: TextFormField( onSaved: (name) { updateuser.name = name; }, initialValue: loggedinUser.name, validator: (name) => validateName(name), style: TextStyle( fontSize: 16, fontFamily: 'Montserrat', fontWeight: FontWeight.normal, color: Colors.black, ), decoration: InputDecoration( errorText: "", border: UnderlineInputBorder( borderSide: BorderSide(color: Colors.transparent), ), labelText: 'Name', icon: Image.asset( 'assets/images/icons/user.png', color: Colors.blue[600], width: 0.06 * width, ), ), ), ), Divider( height: 0.02 * height, ), Container( padding: EdgeInsets.fromLTRB(0, 0, 0, 0.004 * height), child: TextFormField( onSaved: (email) { updateuser.email = email; }, initialValue: loggedinUser.email, validator: (email) => validateEmail(email), style: TextStyle( fontSize: 16, fontFamily: 'Montserrat', fontWeight: FontWeight.normal, color: Colors.black, ), keyboardType: TextInputType.emailAddress, decoration: InputDecoration( errorText: "", border: Theme.of(context) .inputDecorationTheme .border, icon: Image.asset( 'assets/images/icons/email.png', color: Colors.blue[600], width: 0.06 * width, ), labelText: 'Email', ), ), ), Divider( height: 0.02 * height, ), Container( padding: EdgeInsets.fromLTRB(0, 0, 0, 0.004 * height), child: TextFormField( onSaved: (address) { updateuser.address = address; }, initialValue: loggedinUser.address ?? "", style: TextStyle( fontSize: 16, fontFamily: 'Montserrat', fontWeight: FontWeight.normal, color: Colors.black, ), keyboardType: TextInputType.multiline, decoration: InputDecoration( errorText: "", border: Theme.of(context) .inputDecorationTheme .border, labelText: 'Address', icon: Image.asset( 'assets/images/icons/address.png', color: Colors.blue[600], width: 0.06 * width, ), ), ), ), ], ), ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ RaisedButton( padding: EdgeInsets.symmetric(horizontal: 20), color: Colors.blue[400], shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), child: Center( child: BlocBuilder( bloc: signupBloc, builder: (BuildContext context, state) { if (state is SignupInitialState) { return Text( 'Save Changes', style: Theme.of(context) .textTheme .button .copyWith( fontSize: 17, color: Colors.white), ); } else if (state is SignupLoadingState) { return CircularProgressIndicator( backgroundColor: Colors.pink, ); } else if (state is SignupSuccessState) { Fluttertoast.showToast( msg: "Updated. Please re-authenticate.", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.black, textColor: Colors.white, fontSize: 16.0); BlocProvider.of<AuthenticationBloc>(context) .add(LoggedOutEvent()); Navigator.pop(context); Navigator.pop(context); return Text( 'Save Changes', style: Theme.of(context) .textTheme .button .copyWith( fontSize: 17, color: Colors.white), ); } else { final errstate = state as SignupFailureState; Fluttertoast.showToast( msg: errstate.error, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.red, textColor: Colors.white, fontSize: 16.0); return Text( 'Save Changes', style: Theme.of(context) .textTheme .button .copyWith( fontSize: 17, color: Colors.white), ); } }, )), onPressed: () { if (_formKey.currentState.validate()) { _formKey.currentState.save(); signupBloc .add(UpdateProfileEvent(user: updateuser)); } }, ), ], ) ], ) ], ), ), ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/foodTipsPage.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/repository/repositories.dart'; import 'package:nirogi/src/screens/screens.dart'; class FoodTipsPage extends StatelessWidget { final FoodTipsRepository _repository = FoodTipsRepository(); final FoodTips foodtips = FoodTips(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Food Tips', style: Theme.of(context).textTheme.headline), SizedBox( width: 14, ), Image.asset( 'assets/images/icons/diet.png', width: 30, ), ], ), ), body: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Expanded( child: Padding( padding: EdgeInsets.only(right: 10, left: 10, bottom: 10), child: FutureBuilder( future: _repository.getFoodTipsDiseases(), builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return Container( child: ListView.separated( shrinkWrap: true, physics: BouncingScrollPhysics(), scrollDirection: Axis.vertical, itemCount: snapshot.data.length, itemBuilder: (BuildContext context, int index) { return TipsName(disease: snapshot.data[index]); }, separatorBuilder: (BuildContext context, int index) { return SizedBox( height: 15.0, ); }, ), ); } else if (snapshot.hasError) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 10, ), Text(snapshot.error) ], ), ); } else { return Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ); } }), ), ), ], )); } } class TipsName extends StatelessWidget { final Disease disease; TipsName({ Key key, @required this.disease, }) : super(key: key); @override Widget build(BuildContext context) { return GestureDetector( onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return ShowFoods( disease: disease.disease, diseaseId: disease.diseaseId, ); }, ), ); }, child: Material( borderRadius: BorderRadius.circular(5), elevation: 1.0, child: Container( height: 60.0, margin: EdgeInsets.symmetric(horizontal: 5, vertical: 7), child: Row( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Container( margin: EdgeInsets.fromLTRB(5, 0, 13, 0), child: CircleAvatar( radius: 23, child: Text( disease.disease[0], style: TextStyle( fontSize: 30, color: Colors.white, ), ), backgroundColor: Colors.lightBlue[400], ), ), Expanded( child: Text( disease.disease, style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, ), ), ), ], ), ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/dev_info_page.dart
import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; class DevInfoPage extends StatefulWidget { final String selectedUrl; final String devName; DevInfoPage({@required this.selectedUrl, this.devName}); @override createState() => _DevInfoPageState(this.selectedUrl, this.devName); } class _DevInfoPageState extends State<DevInfoPage> { var _selectedUrl; var _devName; final _key = UniqueKey(); num _stackToView = 1; _DevInfoPageState(this._selectedUrl, this._devName); void _haldleLoad(String value) { setState(() { _stackToView = 0; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(_devName, style: Theme.of(context).textTheme.headline), centerTitle: true, ), body: IndexedStack( index: _stackToView, children: [ Column( children: [ Expanded( child: WebView( key: _key, javascriptMode: JavascriptMode.unrestricted, initialUrl: _selectedUrl, onPageFinished: _haldleLoad, ), ) ], ), Container( child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ), ) ], ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/eachFirstAidPage.dart
import 'package:flutter/material.dart'; import 'package:flutter_html/flutter_html.dart'; import 'package:nirogi/src/constants/env.dart'; import 'package:nirogi/src/repository/repositories.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:html/dom.dart' as dom; class EachFirstAidPage extends StatefulWidget { final String title; final int firstAidId; EachFirstAidPage({@required this.firstAidId, @required this.title}); @override _EachFirstAidPageState createState() => _EachFirstAidPageState(); } class _EachFirstAidPageState extends State<EachFirstAidPage> { ScrollController _customController; bool _isCollapsed = false; @override void initState() { super.initState(); _customController = ScrollController() ..addListener( () => setState( () { _isCollapsed = (_customController.offset <= kToolbarHeight) ? false : true; }, ), ); } @override Widget build(BuildContext context) { return Scaffold( body: FutureBuilder( future: firstAidRepository.getSingleFirstAid(firstAidId: widget.firstAidId), builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: CustomScrollView( controller: _customController, slivers: <Widget>[ SliverAppBar( expandedHeight: 200.0, floating: false, pinned: true, centerTitle: true, title: _isCollapsed ? Text( widget.title, style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, color: Colors.red[700], fontWeight: FontWeight.w500, ), ) : Text( widget.title, style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, color: Colors.transparent, fontWeight: FontWeight.w500, ), ), flexibleSpace: FlexibleSpaceBar( background: FadeInImage.assetNetwork( image: "$baseUrl/${snapshot.data.imageUrl}", placeholder: "assets/gifs/loading.gif", fit: BoxFit.cover, )), ), SliverList( delegate: SliverChildBuilderDelegate( (context, index) { return Padding( padding: const EdgeInsets.all(10.0), child: Html( data: snapshot.data.body, customTextStyle: (dom.Node node, style) { if (node is dom.Element) { switch (node.localName) { case "code": { return style.copyWith( color: Colors.red[700], fontSize: 20, fontWeight: FontWeight.w500, fontFamily: 'Montserrat'); } break; case "b": { return style.copyWith( color: Colors.blue, fontFamily: 'Montserrat'); } break; default: { return style.copyWith( fontSize: 16, fontFamily: 'karla'); } } } }, ), ); }, childCount: 1, ), ), ], ), ); } else if (snapshot.hasError) { return Center( child: Text("error"), ); } else { return Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ); } }, ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/viewProfile.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:nirogi/src/bloc/blocs.dart'; import 'package:nirogi/src/bloc/getposts_event.dart'; import 'package:nirogi/src/bloc/states.dart'; import 'package:nirogi/src/constants/env.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class ViewProfile extends StatefulWidget { final String imageUrl; final String name; final String address; final int userId; const ViewProfile({ @required this.address, @required this.name, @required this.imageUrl, @required this.userId, }); @override _ViewProfileState createState() => _ViewProfileState(); } class _ViewProfileState extends State<ViewProfile> { final GetPostsBloc getPostsBloc = GetPostsBloc(); @override void initState() { super.initState(); getPostsBloc.add(GetUsersPostsEvent(userId: widget.userId)); } @override Widget build(BuildContext context) { final double height = MediaQuery.of(context).size.height; final double width = MediaQuery.of(context).size.width; return Scaffold( appBar: AppBar( elevation: 0, title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('View Profile', style: Theme.of(context).textTheme.headline), SizedBox( width: 0.02 * width, ), Image.asset( 'assets/images/icons/profile.png', width: 0.075 * width, ), ], ), ), body: Stack( children: <Widget>[ Column( children: <Widget>[ Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Padding( padding: EdgeInsets.only( left: 0.025 * width, right: 0.036 * width, ), child: Container( height: 0.16 * height, width: 0.16 * height, decoration: BoxDecoration( shape: BoxShape.circle, image: DecorationImage( image: NetworkImage('$baseUrl/${widget.imageUrl}'), ), ), ), ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Column( children: <Widget>[ Text( widget.name, style: Theme.of(context) .textTheme .body2 .copyWith( color: Colors.red[700], fontSize: 20), ), Text( widget.address, style: Theme.of(context) .textTheme .body2 .copyWith(fontSize: 15), ), ], ), SizedBox( height: 25, ), Column( children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Image.asset( 'assets/images/icons/post.png', width: 0.075 * width, ), SizedBox( width: 10, ), Text( 'Posts', style: Theme.of(context) .textTheme .body1 .copyWith(fontSize: 18), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( height: 1.0, color: Colors.red, width: 0.115 * width, ), SizedBox( width: 5, ), Container( height: 10, width: 10, child: Image.asset( 'assets/images/icons/blood-drop.png'), ), SizedBox( width: 5, ), Container( height: 1.0, width: 0.13 * width, color: Colors.red, ), ], ) ], ), ], ), ), ], ), ], ), Expanded( child: Container( margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10), padding: EdgeInsets.symmetric(vertical: 10), child: BlocBuilder( bloc: getPostsBloc, builder: (BuildContext context, state) { if (state is PostsUninitialisedState) { return Container( child: Center( child: Text('not loaded'), ), ); } else if (state is PostsEmptyState) { return Container( child: Center( child: Text("No posts found"), ), ); } else if (state is PostsFetchingState) { return Container( child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ), ); } else if (state is PostsErrorState) { return Container( child: Center( child: Text("error"), ), ); } final stateAsPostsFetchedState = state as PostsFetchedState; final posts = stateAsPostsFetchedState.posts; return RefreshIndicator( onRefresh: () { getPostsBloc .add(GetUsersPostsEvent(userId: widget.userId)); }, child: ListView.separated( shrinkWrap: true, physics: BouncingScrollPhysics(), itemCount: posts.length, itemBuilder: (BuildContext context, int index) { return PostBlock( post: posts[index], ); }, separatorBuilder: (BuildContext context, int index) { return SizedBox( height: 0.02 * height, ); }, ), ); }, ), ), ), ], ), ], ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/symptomsPage.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/repository/repositories.dart'; import 'package:nirogi/src/screens/screens.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class SymptomsPage extends StatelessWidget { @override Widget build(BuildContext context) { final width = MediaQuery.of(context).size.width; return Scaffold( drawer: AppDrawer(), appBar: AppBar( actions: <Widget>[ IconButton( onPressed: () { Navigator.of(context) .push(MaterialPageRoute(builder: (BuildContext context) { return SymptomSearchPage(); })); }, icon: Icon( Icons.search, size: 30, ), ) ], title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Symptoms', style: Theme.of(context).textTheme.headline), SizedBox( width: 0.03 * width, ), Image.asset( 'assets/images/icons/symptoms.png', width: 0.07 * width, ), ], ), ), body: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ _BuildSymptomList(), ], )); } } class _BuildSymptomList extends StatefulWidget { const _BuildSymptomList({ Key key, }) : super(key: key); @override __BuildSymptomListState createState() => __BuildSymptomListState(); } class __BuildSymptomListState extends State<_BuildSymptomList> { Future<List<Symptom>> allSymptoms; @override void initState() { super.initState(); allSymptoms = symptomRepository.getAllSymptoms(); } @override Widget build(BuildContext context) { final height = MediaQuery.of(context).size.height; final width = MediaQuery.of(context).size.width; return FutureBuilder( future: allSymptoms, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return Expanded( child: Padding( padding: EdgeInsets.only( right: 0.02 * width, left: 0.02 * width, bottom: 0.01 * height), child: ListView.separated( shrinkWrap: true, physics: BouncingScrollPhysics(), itemCount: snapshot.data.length, scrollDirection: Axis.vertical, itemBuilder: (BuildContext context, int index) { return SymptomBlock( symptom: snapshot.data[index], ); }, separatorBuilder: (BuildContext context, int index) { return SizedBox( height: 0.02 * height, ); }, ), ), ); } else if (snapshot.hasError) { return Expanded( child: Center( child: Container( height: MediaQuery.of(context).size.width, child: Column( children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 10, ), Text(snapshot.error) ], )), ), ); } else { return Expanded( child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ), ); } }, ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/editPost.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:nirogi/src/bloc/blocs.dart'; import 'package:nirogi/src/bloc/events.dart'; import 'package:nirogi/src/bloc/states.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; class EditPost extends StatefulWidget { final Post post; const EditPost({ @required this.post, Key key, }) : assert(post != null), super(key: key); @override _EditPostState createState() => _EditPostState(categoryId: post.category.categoryId); } class _EditPostState extends State<EditPost> { GlobalKey<FormState> _createPostField = GlobalKey<FormState>(); int categoryId; static Category categoryValue; _EditPostState({@required this.categoryId}) { categoryValue = categories[this.categoryId - 1]; } PostBloc addPostBloc; @override void initState() { super.initState(); addPostBloc = PostBloc(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Edit Post', style: Theme.of(context).textTheme.headline), SizedBox( width: 14, ), Image.asset( 'assets/images/icons/pen.png', width: 30, ), ], ), ), body: ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: SingleChildScrollView( child: Container( padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20), child: Column( children: <Widget>[ Row( children: <Widget>[ Container( height: 40, width: 40, decoration: BoxDecoration( color: Colors.red[50], shape: BoxShape.circle, image: DecorationImage( image: AssetImage( 'assets/images/icons/profile.png', ), fit: BoxFit.contain, ), ), ), SizedBox( width: 10, ), Text( widget.post.name, style: Theme.of(context).textTheme.body2.copyWith( fontSize: 18, color: Colors.black, ), ), ], ), SizedBox( height: 10, ), Form( key: _createPostField, child: Column( children: <Widget>[ TextFormField( onSaved: (String value) { widget.post.title = value.trim(); }, validator: (String value) { if (value.trim().isEmpty) { return "Empty title provided."; } return null; }, style: TextStyle( fontSize: 18, color: Colors.black, fontFamily: 'Montserrat', fontWeight: FontWeight.w500, ), initialValue: widget.post.title, decoration: InputDecoration( border: UnderlineInputBorder( borderSide: BorderSide(color: Colors.red[700]), ), labelText: 'Title', labelStyle: TextStyle( fontSize: 18, color: Colors.red[700], fontFamily: 'Montserrat', fontWeight: FontWeight.w500, ), icon: Icon( Icons.title, color: Colors.blue, ), ), ), SizedBox( height: 10, ), TextFormField( onSaved: (String value) { widget.post.body = value.trim(); }, validator: (String value) { if (value.trim().isEmpty) { return "Empty body provided."; } return null; }, style: TextStyle( fontSize: 16, color: Colors.black, fontFamily: 'Montserrat', fontWeight: FontWeight.normal, ), initialValue: widget.post.body, keyboardType: TextInputType.multiline, maxLines: null, decoration: InputDecoration( border: UnderlineInputBorder( borderSide: BorderSide(color: Colors.red[700]), ), labelText: 'Body', labelStyle: TextStyle( fontSize: 18, color: Colors.red[700], fontFamily: 'Montserrat', fontWeight: FontWeight.w500, ), icon: Icon( Icons.subject, color: Colors.blue, ), ), ), SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Container( child: DropdownButton<Category>( value: categoryValue, elevation: 0, onChanged: (Category newValue) { setState(() { categoryValue = newValue; }); }, items: categories .map<DropdownMenuItem<Category>>( (Category value) { return DropdownMenuItem( value: value, child: Text( value.category, maxLines: 3, overflow: TextOverflow.ellipsis, style: Theme.of(context) .textTheme .body2 .copyWith( fontSize: 16, ), ), ); }).toList()), ), FlatButton( onPressed: () { if (_createPostField.currentState.validate()) { _createPostField.currentState.save(); widget.post.category = categoryValue; addPostBloc.add(EditPostEvent( post: widget.post, postId: widget.post.postId, )); } }, child: Text( 'SAVE', style: Theme.of(context).textTheme.body2.copyWith( fontSize: 20, color: Colors.blue, fontWeight: FontWeight.w500, ), ), ) ], ), ], ), ), BlocListener( bloc: addPostBloc, child: SizedBox(), listener: (BuildContext context, PostState state) { if (state is AddPostUninitiatedState) { return SizedBox(); } else if (state is AddPostSendingState) { return Container( child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ), ); } else if (state is AddPostSucessState) { Fluttertoast.showToast( msg: state.message, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.black, textColor: Colors.white, fontSize: 16.0); Navigator.pop(context, widget.post); return SizedBox(); } else { var errorstate = state as AddPostErrorState; Fluttertoast.showToast( msg: errorstate.error, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.red, textColor: Colors.white, fontSize: 16.0); Navigator.pop(context, widget.post); return SizedBox(); } }, ) ], ), ), ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/eachDisease.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/repository/repositories.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:html/dom.dart' as dom; import 'package:flutter_html/flutter_html.dart'; class EachDisease extends StatefulWidget { final Disease disease; EachDisease({@required this.disease}); @override _EachDiseaseState createState() => _EachDiseaseState(); } class _EachDiseaseState extends State<EachDisease> { ScrollController _customController; Future<Disease> disease; bool _isCollapsed = false; @override void initState() { super.initState(); disease = diseaseRepository.getDisease(diseaseId: widget.disease.diseaseId); _customController = ScrollController() ..addListener( () => setState( () { _isCollapsed = (_customController.offset <= kToolbarHeight) ? false : true; }, ), ); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Theme.of(context).scaffoldBackgroundColor, body: FutureBuilder<Disease>( future: disease, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: NestedScrollView( controller: _customController, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverAppBar( expandedHeight: 200.0, floating: false, pinned: true, centerTitle: true, title: _isCollapsed ? Text( widget.disease.disease, style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, color: Colors.red[700], fontWeight: FontWeight.w500, ), ) : Text( widget.disease.disease, style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, color: Colors.transparent, fontWeight: FontWeight.w500, ), ), flexibleSpace: FlexibleSpaceBar( background: FadeInImage.assetNetwork( placeholder: "assets/gifs/loading.gif", image: widget.disease.imageUrl, fit: BoxFit.cover, ), ), ), ]; }, body: SingleChildScrollView( child: Container( padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10), child: Html( data: snapshot.data.body, customTextStyle: (dom.Node node, style) { if (node is dom.Element) { switch (node.localName) { case "code": { return style.copyWith( color: Colors.red[700], fontSize: 18, fontWeight: FontWeight.w500, fontFamily: 'Montserrat'); } break; case "b": { return style.copyWith( color: Colors.blue, fontFamily: 'Montserrat'); } break; default: { return style.copyWith( fontSize: 15, fontFamily: 'karla'); } } } }, ), ), ), ), ); } else if (snapshot.hasError) { return Container( child: Center( child: Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), ), ); } else { return Container( child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ), ); } }, ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/eachSymptom.dart
import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:nirogi/src/models/models.dart'; import 'package:nirogi/src/repository/repositories.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:flutter_html/flutter_html.dart'; import 'package:html/dom.dart' as dom; class EachSymptom extends StatefulWidget { final Symptom symptom; EachSymptom({@required this.symptom}); @override _EachSymptomState createState() => _EachSymptomState(); } class _EachSymptomState extends State<EachSymptom> { ScrollController _customController; Future<Symptom> symptom; bool _isCollapsed = false; @override void initState() { super.initState(); symptom = symptomRepository.getSymptom(symptomId: widget.symptom.symptomId); _customController = ScrollController() ..addListener( () => setState( () { _isCollapsed = (_customController.offset <= kToolbarHeight) ? false : true; }, ), ); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Theme.of(context).scaffoldBackgroundColor, body: FutureBuilder<Symptom>( future: symptom, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: NestedScrollView( controller: _customController, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverAppBar( expandedHeight: 200.0, floating: false, pinned: true, centerTitle: true, title: _isCollapsed ? Text( widget.symptom.symptom, style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, color: Colors.red[700], fontWeight: FontWeight.w500, ), ) : Text( widget.symptom.symptom, style: Theme.of(context).textTheme.body1.copyWith( fontSize: 20, color: Colors.transparent, fontWeight: FontWeight.w500, ), ), flexibleSpace: FlexibleSpaceBar( background: FadeInImage.assetNetwork( image: widget.symptom.imageUrl, placeholder: "assets/gifs/loading.gif", fit: BoxFit.cover, ), ), ), ]; }, body: SingleChildScrollView( child: Container( padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10), child: Html( data: snapshot.data.body, customTextStyle: (dom.Node node, style) { if (node is dom.Element) { switch (node.localName) { case "code": { return style.copyWith( color: Colors.red[700], fontSize: 18, fontWeight: FontWeight.w500, fontFamily: 'Montserrat'); } break; case "b": { return style.copyWith( color: Colors.blue, fontFamily: 'Montserrat'); } break; default: { return style.copyWith( fontSize: 15, fontFamily: 'karla'); } } } }, ), ), ), ), ); } else if (snapshot.hasError) { return Container( child: Center( child: Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/nointernet.flr', animation: 'init', fit: BoxFit.cover, shouldClip: false, ), ), ), ); } else { return Container( child: Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, ), ), ); } }, ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/loginsignup.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:nirogi/src/bloc/blocs.dart'; import 'package:nirogi/src/repository/repositories.dart'; import 'package:nirogi/src/themes/clippers.dart'; import "package:flare_flutter/flare_actor.dart"; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class LoginSignup extends StatefulWidget { final UserRepository userRepository; LoginSignup({Key key, @required this.userRepository}) : assert(userRepository != null), super(key: key); @override _LoginSignupState createState() => _LoginSignupState(); } class _LoginSignupState extends State<LoginSignup> { LoginBloc _loginBloc; SignupBloc _signupBloc; AuthenticationBloc _authenticationBloc; bool isLoginShown; UserRepository get _userRepository => widget.userRepository; @override void initState() { _authenticationBloc = BlocProvider.of<AuthenticationBloc>(context); _signupBloc = SignupBloc( userRepository: _userRepository, authenticationBloc: _authenticationBloc, ); _loginBloc = LoginBloc( authenticationBloc: _authenticationBloc, userRepository: _userRepository, ); isLoginShown = true; super.initState(); } @override void dispose() { _signupBloc.close(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Theme.of(context).scaffoldBackgroundColor, body: ScrollConfiguration( behavior: RemoveEndOfListIndicator(), child: SingleChildScrollView( child: Stack( children: <Widget>[ _LinearGradient(), _BackgroundClipPath(), Column( children: <Widget>[ SizedBox( height: 0.05 * MediaQuery.of(context).size.height, ), _TopPart(), SizedBox( height: 0.08 * MediaQuery.of(context).size.height, ), !isLoginShown ? SignupForm( authenticationBloc: _authenticationBloc, signupBloc: _signupBloc, ) : LoginForm( authenticationBloc: _authenticationBloc, loginBloc: _loginBloc, ), ], ), Positioned( bottom: 0.03 * MediaQuery.of(context).size.height, left: 10, right: 10, child: GestureDetector( child: Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ isLoginShown ? Text( "Don't have an account yet?", style: TextStyle( fontSize: 20, fontFamily: Theme.of(context) .textTheme .body1 .fontFamily, fontWeight: Theme.of(context) .textTheme .body1 .fontWeight, color: Colors.black, ), ) : Text( "Already have an account?", style: TextStyle( fontSize: 20, fontFamily: Theme.of(context) .textTheme .body1 .fontFamily, fontWeight: Theme.of(context) .textTheme .body1 .fontWeight, color: Colors.black, ), ), SizedBox( width: 10, ), Icon( Icons.arrow_forward, size: 30, color: Colors.red[700], ) ], ), ), onTap: () { setState(() { isLoginShown = !isLoginShown; }); }, ), ), ], ), ), ), ); } } class _TopPart extends StatelessWidget { const _TopPart({ Key key, }) : super(key: key); @override Widget build(BuildContext context) { return Center( child: Column( children: <Widget>[ Container( width: 0.32 * MediaQuery.of(context).size.width, height: 0.32 * MediaQuery.of(context).size.width, child: FlareActor( 'assets/animations/yoga.flr', animation: 'relaxing', color: Colors.white, fit: BoxFit.cover, shouldClip: false, ), ), SizedBox( height: 0.01 * MediaQuery.of(context).size.height, ), Text( 'HAMI NIROGI', style: Theme.of(context).textTheme.headline.copyWith( letterSpacing: 2, fontSize: 24, color: Colors.red[700], fontWeight: FontWeight.w600, ), ) ], ), ); } } class _LinearGradient extends StatelessWidget { const _LinearGradient({ Key key, }) : super(key: key); @override Widget build(BuildContext context) { return Column( children: <Widget>[ Container( height: MediaQuery.of(context).size.height * 0.6, decoration: BoxDecoration( gradient: LinearGradient( colors: [ Color(0xffF56545).withOpacity(0.8), Color(0xffFFE190).withOpacity(0.8), ], begin: Alignment.topCenter, end: Alignment.bottomCenter, ), ), ), Container( height: MediaQuery.of(context).size.height * 0.4, decoration: BoxDecoration( gradient: LinearGradient( colors: [ Color(0xffF56545).withOpacity(0.8), Color(0xffFFE190).withOpacity(0.8), ], end: Alignment.topCenter, begin: Alignment.bottomCenter, ), ), ) ], ); } } class _BackgroundClipPath extends StatelessWidget { const _BackgroundClipPath({ Key key, }) : super(key: key); @override Widget build(BuildContext context) { return ClipPath( clipper: LoginPageClipper(), child: Stack( children: <Widget>[ Container( height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, color: Colors.white, ), Positioned( child: Image.asset( 'assets/images/icons/dna.png', width: 0.14 * MediaQuery.of(context).size.width, ), bottom: 0.24 * MediaQuery.of(context).size.height, left: 4, ), Positioned( child: Image.asset( 'assets/images/icons/medicine.png', width: 0.14 * MediaQuery.of(context).size.width, ), top: 0.33 * MediaQuery.of(context).size.height, right: 4, ), Positioned( child: Image.asset( 'assets/images/icons/yoga.png', width: 0.3 * MediaQuery.of(context).size.width, ), top: 0.46 * MediaQuery.of(context).size.height, right: (MediaQuery.of(context).size.width / 2) - (0.15 * MediaQuery.of(context).size.width), ), ], ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/disease_search_page.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:nirogi/src/bloc/blocs.dart'; import 'package:nirogi/src/bloc/events.dart'; import 'package:nirogi/src/bloc/states.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class DiseaseSearchPage extends StatefulWidget { @override _DiseaseSearchPageState createState() => _DiseaseSearchPageState(); } class _DiseaseSearchPageState extends State<DiseaseSearchPage> { FocusNode focusNode; SearchBloc searchBloc; String searchQuery = ""; GlobalKey<FormFieldState> _key = GlobalKey<FormFieldState>(); @override void initState() { super.initState(); focusNode = FocusNode(); searchBloc = SearchBloc(); } @override void dispose() { super.dispose(); searchBloc.close(); } @override Widget build(BuildContext context) { FocusScope.of(context).requestFocus(focusNode); return Scaffold( appBar: AppBar( title: TextFormField( onFieldSubmitted: (value) { if (_key.currentState.validate()) { _key.currentState.save(); searchBloc.add(DiseaseSearchEvent(query: searchQuery)); } }, key: _key, validator: (value) { if (value.isEmpty || value.length < 3) { return "Enter at least 3 characters"; } return null; }, onSaved: (value) { searchQuery = value.trim(); }, focusNode: focusNode, style: TextStyle( fontSize: 16, color: Colors.black, fontFamily: 'Montserrat', fontWeight: FontWeight.normal, ), keyboardType: TextInputType.text, decoration: InputDecoration( contentPadding: EdgeInsets.all(0), border: UnderlineInputBorder( borderSide: BorderSide(color: Colors.red[700]), ), hintText: 'Search for disease', labelStyle: TextStyle( fontSize: 18, color: Colors.red[700], fontFamily: 'Montserrat', fontWeight: FontWeight.w500, ), suffix: IconButton( padding: EdgeInsets.all(0), icon: Icon(Icons.search), onPressed: () { if (_key.currentState.validate()) { _key.currentState.save(); searchBloc.add(DiseaseSearchEvent(query: searchQuery)); } }, ), ), ), ), body: Container( child: BlocBuilder( bloc: searchBloc, builder: (BuildContext context, state) { if (state is SearchUninitialisedState) { return Center( child: Text('Search for the disease here.'), ); } else if (state is SearchFetchingState) { return Center( child: CircularProgressIndicator( backgroundColor: Colors.pink, )); } else if (state is SearchErrorState) { return Center( child: Text("error occured"), ); } else if (state is SearchEmptyState) { return Center( child: RichText( textAlign: TextAlign.center, text: TextSpan(children: [ TextSpan( text: "Nothing found for\n\n", style: Theme.of(context).textTheme.body1.copyWith( fontSize: 15, color: Colors.black, )), TextSpan( text: searchQuery, style: Theme.of(context).textTheme.headline.copyWith( fontSize: 17, color: Colors.blue[700], fontWeight: FontWeight.w500), ) ]), ), ); } else if (state is SearchDiseaseFetchedState) { return Padding( padding: EdgeInsets.only(right: 10, left: 10), child: Container( child: ListView.separated( shrinkWrap: true, physics: BouncingScrollPhysics(), scrollDirection: Axis.vertical, itemCount: state.diseases.length, itemBuilder: (BuildContext context, int index) { return DiseaseBlock(disease: state.diseases[index]); }, separatorBuilder: (BuildContext context, int index) { return SizedBox( height: 15.0, ); }, ), ), ); } }, ), ), ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/screens/healthToolsPage.dart
import 'package:flutter/material.dart'; import 'package:nirogi/src/screens/screens.dart'; import 'package:nirogi/src/themes/scrollOverlay.dart'; import 'package:nirogi/src/widgets/widgets.dart'; class HealthToolsPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( drawer: AppDrawer(), appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Health Tools and Tips', style: Theme.of(context).textTheme.headline, ), SizedBox( width: 14, ), Image.asset( 'assets/images/icons/healthtool.png', width: 30, ), ], ), ), body: ScrollConfiguration( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 5), child: GridView.count( primary: false, crossAxisSpacing: 10.0, crossAxisCount: 2, mainAxisSpacing: 0, children: <Widget>[ ToolCard( imageUrl: "assets/images/icons/diet.png", name: "Food Tips", onTapWidget: FoodTipsPage(), ), ToolCard( imageUrl: "assets/images/icons/medicine.png", name: "Information on Common Drugs", onTapWidget: ShowDrugs(), ), ToolCard( imageUrl: "assets/images/icons/firstaid.png", name: "First Aid", onTapWidget: FirstAidPage(), ), IncompatibleFoods(), ToolCard( imageUrl: "assets/images/icons/bmi.png", name: "BMI Calculator", onTapWidget: CalculateBMI(), ), ToolCard( imageUrl: "assets/images/icons/blooddonation.png", name: "Blood Donation Date", onTapWidget: BloodDonation(), ), ToolCard( imageUrl: "assets/images/icons/water.png", name: "Daily Water Requirement", onTapWidget: DailyWater(), ), ], ), ), behavior: RemoveEndOfListIndicator(), ), ); } } class IncompatibleFoods extends StatelessWidget { const IncompatibleFoods({ Key key, }) : super(key: key); @override Widget build(BuildContext context) { return InkWell( child: Card( elevation: 5, color: Theme.of(context).canvasColor, child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Container( margin: EdgeInsets.only(top: 10, bottom: 20), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Stack( children: <Widget>[ Image.asset( 'assets/images/icons/breakfast.png', width: 90, ), Positioned( bottom: 0, right: 0, child: Image.asset( 'assets/images/icons/close.png', width: 30, color: Colors.red[700], ), ), ], ) ], ), ), Text( "Incompatible Foods", style: Theme.of(context).textTheme.body1.copyWith( fontSize: 18, fontWeight: FontWeight.w500, ), textAlign: TextAlign.center, ) ], ), ), onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return IncompatibleFoodsMenuPage(); }, ), ); }, ); } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/functions/functions.dart
export 'validator.dart';
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/functions/validator.dart
dynamic validateEmail(String email) { final RegExp exp = RegExp(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"); if (exp.allMatches(email).length > 0) { return null; } else { return 'Enter a valid email.'; } } dynamic validatePassword(String password) { final RegExp exp = new RegExp( r"^(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}$"); if (exp.allMatches(password).length > 0) { return null; } else { return 'Password must be alphanumeric, 8 characters long'; } } dynamic validateName(String name) { final RegExp exp = new RegExp('[A-Za-z]{2,25}( [A-Za-z]{2,25})?'); if (exp.allMatches(name).length > 0) { return null; } else { return 'Enter a valid name.'; } }
0
mirrored_repositories/nirogi/lib/src
mirrored_repositories/nirogi/lib/src/functions/reset_error.dart
String resetError() { return ""; }
0
mirrored_repositories/login_signup_example
mirrored_repositories/login_signup_example/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:login_signup_example/page/home_page.dart'; import 'package:login_signup_example/page/user_page.dart'; import 'package:login_signup_example/utils/user_preferences.dart'; import 'package:login_signup_example/utils/user_simple_preferences.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, ]); await UserPreferences.init(); runApp(MyApp()); } class MyApp extends StatelessWidget { static final String title = 'Login & Signup'; @override Widget build(BuildContext context) => MaterialApp( debugShowCheckedModeBanner: false, title: title, theme: ThemeData( colorScheme: ColorScheme.dark(), scaffoldBackgroundColor: Colors.blue.shade300, accentColor: Colors.indigoAccent.withOpacity(0.8), unselectedWidgetColor: Colors.blue.shade200, switchTheme: SwitchThemeData( thumbColor: MaterialStateProperty.all(Colors.white), ), ), home: HomePage(), ); }
0
mirrored_repositories/login_signup_example/lib
mirrored_repositories/login_signup_example/lib/page/home_page.dart
import 'package:flutter/material.dart'; import 'package:login_signup_example/page/login_page.dart'; import 'package:login_signup_example/page/user_page.dart'; import 'package:login_signup_example/widget/button_widget.dart'; import 'package:login_signup_example/widget/title_widget.dart'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) => Scaffold( body: SafeArea( child: Container( padding: EdgeInsets.symmetric(horizontal: 32, vertical: 96), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ TitleWidget(icon: Icons.home, text: 'Signup'), buildButtons(), ], ), ), ), ); Widget buildButtons() => Column( children: [ const SizedBox(height: 24), ButtonWidget( text: 'Login', onClicked: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => LoginPage(), )), ), const SizedBox(height: 24), ButtonWidget( text: 'Register', onClicked: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => UserPage(), )), ), ], ); }
0
mirrored_repositories/login_signup_example/lib
mirrored_repositories/login_signup_example/lib/page/user_page.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:login_signup_example/model/user.dart'; import 'package:login_signup_example/utils/user_preferences.dart'; import 'package:login_signup_example/widget/birthday_widget.dart'; import 'package:login_signup_example/widget/button_widget.dart'; import 'package:login_signup_example/widget/pets_buttons_widget.dart'; import 'package:login_signup_example/widget/switch_widget.dart'; import 'package:path_provider/path_provider.dart'; import 'package:uuid/uuid.dart'; class UserPage extends StatefulWidget { final String idUser; const UserPage({ Key key, this.idUser, }) : super(key: key); @override _UserPageState createState() => _UserPageState(); } class _UserPageState extends State<UserPage> { User user; @override void initState() { super.initState(); final id = Uuid().v4(); print('Id: $id'); user = widget.idUser == null ? User(id: id) : UserPreferences.getUser(widget.idUser); } @override Widget build(BuildContext context) => Scaffold( body: SafeArea( child: Stack( children: [ buildUsers(), if (widget.idUser == null) Positioned( left: 16, top: 24, child: GestureDetector( onTap: () => Navigator.of(context).pop(), child: Icon(Icons.arrow_back, size: 32), ), ), if (widget.idUser != null) Positioned( right: 16, top: 24, child: GestureDetector( onTap: () => Navigator.of(context).pop(), child: Icon(Icons.logout, size: 32), ), ), ], ), ), ); Widget buildUsers() => ListView( padding: EdgeInsets.all(16), children: [ buildImage(), const SizedBox(height: 32), buildName(), const SizedBox(height: 12), buildBirthday(), const SizedBox(height: 12), buildPets(), const SizedBox(height: 12), buildAllowNotifications(), buildAllowNewsletter(), const SizedBox(height: 32), buildButton(), ], ); Widget buildImage() => GestureDetector( child: buildAvatar(), onTap: () async { final image = await ImagePicker().getImage(source: ImageSource.gallery); if (image == null) return; final directory = await getApplicationDocumentsDirectory(); final id = '_${widget.idUser}_${Uuid().v4()}'; final imageFile = File('${directory.path}/${id}_avatar.png'); final newImage = await File(image.path).copy(imageFile.path); setState(() => user = user.copy(imagePath: newImage.path)); }, ); Widget buildAvatar() { final double size = 64; if (user.imagePath.isNotEmpty) { return CircleAvatar( radius: size, backgroundColor: Theme.of(context).accentColor, child: ClipOval( child: Image.file( File(user.imagePath), width: size * 2, height: size * 2, fit: BoxFit.cover, ), ), ); } else { return CircleAvatar( radius: size, backgroundColor: Theme.of(context).unselectedWidgetColor, child: Icon(Icons.add, color: Colors.white, size: size), ); } } Widget buildName() => buildTitle( title: 'Name', child: TextFormField( initialValue: user.name, decoration: InputDecoration( border: OutlineInputBorder(), hintText: 'Your Name', ), onChanged: (name) => setState(() => user = user.copy(name: name)), ), ); Widget buildBirthday() => BirthdayWidget( birthday: user.dateOfBirth, onChangedBirthday: (dateOfBirth) => setState(() => user = user.copy(dateOfBirth: dateOfBirth)), ); Widget buildPets() => buildTitle( title: 'Pets', child: PetsButtonsWidget( pets: user.pets, onSelectedPet: (pet) => setState(() { final pets = user.pets.contains(pet) ? (List.of(user.pets)..remove(pet)) : (List.of(user.pets)..add(pet)); setState(() => user = user.copy(pets: pets)); }), ), ); Widget buildAllowNotifications() => SwitchWidget( title: 'Allow Notifications', value: user.settings.allowNotifications, onChanged: (allowNotifications) { final settings = user.settings.copy( allowNotifications: allowNotifications, ); setState(() => user = user.copy(settings: settings)); }, ); Widget buildAllowNewsletter() => SwitchWidget( title: 'Allow Newsletter', value: user.settings.allowNewsletter, onChanged: (allowNewsletter) { final settings = user.settings.copy( allowNewsletter: allowNewsletter, ); setState(() => user = user.copy(settings: settings)); }, ); Widget buildButton() => ButtonWidget( text: 'Save', onClicked: () async { final isNewUser = widget.idUser == null; if (isNewUser) { await UserPreferences.addUsers(user); await UserPreferences.setUser(user); Navigator.of(context).pushReplacement(MaterialPageRoute( builder: (context) => UserPage(idUser: user.id), )); } else { await UserPreferences.setUser(user); } }); Widget buildTitle({ @required String title, @required Widget child, }) => Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( title, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), ), const SizedBox(height: 8), child, ], ); }
0
mirrored_repositories/login_signup_example/lib
mirrored_repositories/login_signup_example/lib/page/login_page.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:login_signup_example/model/user.dart'; import 'package:login_signup_example/page/user_page.dart'; import 'package:login_signup_example/utils/user_preferences.dart'; import 'package:login_signup_example/widget/title_widget.dart'; class LoginPage extends StatefulWidget { @override _LoginPageState createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { List<User> users; @override void initState() { super.initState(); users = UserPreferences.getUsers(); } @override Widget build(BuildContext context) => Scaffold( body: SafeArea( child: Stack( children: [ Container( padding: EdgeInsets.symmetric(horizontal: 32, vertical: 96), child: Column( children: <Widget>[ TitleWidget(icon: Icons.login, text: 'Login'), const SizedBox(height: 48), Expanded(child: buildUsers()), ], ), ), Positioned( left: 16, top: 24, child: GestureDetector( onTap: () => Navigator.of(context).pop(), child: Icon(Icons.arrow_back, size: 32), ), ), ], ), ), ); Widget buildUsers() { if (users.isEmpty) { return Center( child: Text( 'There are no users!', style: TextStyle(fontSize: 24), ), ); } else { return ListView.separated( itemCount: users.length, separatorBuilder: (context, index) => Container(height: 12), itemBuilder: (context, index) { final user = users[index]; return buildUser(user); }, ); } } Widget buildUser(User user) { final imageFile = File(user.imagePath); return ListTile( tileColor: Colors.white24, onTap: () => Navigator.of(context).pushReplacement(MaterialPageRoute( builder: (context) => UserPage(idUser: user.id), )), leading: user.imagePath.isEmpty ? null : CircleAvatar(backgroundImage: FileImage(imageFile)), title: Text(user.name, style: TextStyle(fontSize: 24)), ); } }
0
mirrored_repositories/login_signup_example/lib
mirrored_repositories/login_signup_example/lib/model/settings.dart
class Settings { final bool allowNewsletter; final bool allowNotifications; const Settings({ this.allowNewsletter = true, this.allowNotifications = true, }); Settings copy({ bool allowNewsletter, bool allowNotifications, }) => Settings( allowNewsletter: allowNewsletter ?? this.allowNewsletter, allowNotifications: allowNotifications ?? this.allowNotifications, ); static Settings fromJson(Map<String, dynamic> json) => Settings( allowNewsletter: json['allowNewsletter'], allowNotifications: json['allowNotifications'], ); Map<String, dynamic> toJson() => { 'allowNewsletter': allowNewsletter, 'allowNotifications': allowNotifications, }; }
0
mirrored_repositories/login_signup_example/lib
mirrored_repositories/login_signup_example/lib/model/user.dart
import 'package:login_signup_example/model/settings.dart'; class User { final String id; final String name; final DateTime dateOfBirth; final String imagePath; final List<String> pets; final Settings settings; const User({ this.id = '', this.name = '', this.dateOfBirth, this.imagePath = '', this.pets = const [], this.settings = const Settings(), }); User copy({ String id, String name, DateTime dateOfBirth, String imagePath, List<String> pets, Settings settings, }) => User( id: id ?? this.id, name: name ?? this.name, dateOfBirth: dateOfBirth ?? this.dateOfBirth, imagePath: imagePath ?? this.imagePath, pets: pets ?? this.pets, settings: settings ?? this.settings, ); static User fromJson(Map<String, dynamic> json) => User( id: json['id'], name: json['name'], dateOfBirth: DateTime.tryParse(json['dateOfBirth']), imagePath: json['imagePath'], pets: List<String>.from(json['pets']), settings: Settings.fromJson(json['settings']), ); Map<String, dynamic> toJson() => { 'id': id, 'name': name, 'dateOfBirth': dateOfBirth.toIso8601String(), 'imagePath': imagePath, 'pets': pets, 'settings': settings.toJson(), }; @override String toString() => 'User{id: $id, name: $name}'; }
0
mirrored_repositories/login_signup_example/lib
mirrored_repositories/login_signup_example/lib/widget/button_widget.dart
import 'package:flutter/material.dart'; class ButtonWidget extends StatelessWidget { final String text; final VoidCallback onClicked; const ButtonWidget({ @required this.text, @required this.onClicked, }); @override Widget build(BuildContext context) => ElevatedButton( style: ElevatedButton.styleFrom( minimumSize: Size.fromHeight(52), primary: Colors.white, elevation: 5, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(25), ), ), child: Text( text, style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), onPressed: onClicked, ); }
0
mirrored_repositories/login_signup_example/lib
mirrored_repositories/login_signup_example/lib/widget/switch_widget.dart
import 'package:flutter/material.dart'; class SwitchWidget extends StatelessWidget { final String title; final bool value; final ValueChanged<bool> onChanged; const SwitchWidget({ @required this.title, @required this.value, @required this.onChanged, }); @override Widget build(BuildContext context) => ListTile( contentPadding: EdgeInsets.zero, onTap: () => onChanged(!value), title: Text( title, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), ), trailing: Transform.scale( scale: 1.3, child: Switch( value: value, activeTrackColor: Theme.of(context).accentColor, onChanged: onChanged, ), ), ); }
0
mirrored_repositories/login_signup_example/lib
mirrored_repositories/login_signup_example/lib/widget/pets_buttons_widget.dart
import 'package:flutter/material.dart'; class PetsButtonsWidget extends StatelessWidget { final List<String> pets; final ValueChanged<String> onSelectedPet; const PetsButtonsWidget({ Key key, @required this.pets, @required this.onSelectedPet, }) : super(key: key); @override Widget build(BuildContext context) { final background = Theme.of(context).unselectedWidgetColor; final allPets = ['Dog', 'Cat', 'Other']; return Container( alignment: Alignment.centerLeft, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: background, ), child: ToggleButtons( isSelected: allPets.map((pet) => pets.contains(pet)).toList(), selectedColor: Colors.white, color: Colors.white, fillColor: Theme.of(context).accentColor, borderRadius: BorderRadius.circular(10), renderBorder: false, children: allPets.map(buildPet).toList(), onPressed: (index) => onSelectedPet(allPets[index]), ), ), ); } Widget buildPet(String text) => Container( padding: EdgeInsets.symmetric(horizontal: 24), child: Text(text), ); }
0
mirrored_repositories/login_signup_example/lib
mirrored_repositories/login_signup_example/lib/widget/title_widget.dart
import 'package:flutter/material.dart'; class TitleWidget extends StatelessWidget { final IconData icon; final String text; const TitleWidget({ Key key, @required this.icon, @required this.text, }) : super(key: key); @override Widget build(BuildContext context) => Column( children: [ Icon(icon, size: 100), const SizedBox(height: 16), Text( text, style: TextStyle(fontSize: 42, fontWeight: FontWeight.w400), textAlign: TextAlign.center, ), ], ); }
0
mirrored_repositories/login_signup_example/lib
mirrored_repositories/login_signup_example/lib/widget/birthday_widget.dart
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; class BirthdayWidget extends StatefulWidget { final DateTime birthday; final ValueChanged<DateTime> onChangedBirthday; const BirthdayWidget({ Key key, @required this.birthday, @required this.onChangedBirthday, }) : super(key: key); @override _BirthdayWidgetState createState() => _BirthdayWidgetState(); } class _BirthdayWidgetState extends State<BirthdayWidget> { final controller = TextEditingController(); final focusNode = FocusNode(); @override void initState() { super.initState(); setDate(); } @override void didUpdateWidget(covariant BirthdayWidget oldWidget) { super.didUpdateWidget(oldWidget); setDate(); } void setDate() => setState(() { controller.text = widget.birthday == null ? '' : DateFormat.yMd().format(widget.birthday); }); @override Widget build(BuildContext context) => FocusBuilder( onChangeVisibility: (isVisible) { if (isVisible) { selectDate(context); // } else { FocusScope.of(context).requestFocus(FocusNode()); } }, focusNode: focusNode, builder: (hasFocus) => TextFormField( controller: controller, validator: (value) => value.isEmpty ? 'Is Required' : null, decoration: InputDecoration( prefixText: ' ', hintText: 'Your birthday', prefixIcon: Icon(Icons.calendar_today_rounded), border: OutlineInputBorder(), ), ), ); Future selectDate(BuildContext context) async { final birthday = await showDatePicker( context: context, initialDate: widget.birthday ?? DateTime.now(), firstDate: DateTime(1950), lastDate: DateTime(2100), ); if (birthday == null) return; widget.onChangedBirthday(birthday); } } class FocusBuilder extends StatefulWidget { final FocusNode focusNode; final Widget Function(bool hasFocus) builder; final ValueChanged<bool> onChangeVisibility; const FocusBuilder({ @required this.focusNode, @required this.builder, @required this.onChangeVisibility, Key key, }) : super(key: key); @override _FocusBuilderState createState() => _FocusBuilderState(); } class _FocusBuilderState extends State<FocusBuilder> { @override Widget build(BuildContext context) => GestureDetector( behavior: HitTestBehavior.opaque, onTap: () => widget.onChangeVisibility(true), child: Focus( focusNode: widget.focusNode, onFocusChange: widget.onChangeVisibility, child: widget.builder(widget.focusNode.hasFocus), ), ); }
0
mirrored_repositories/login_signup_example/lib
mirrored_repositories/login_signup_example/lib/utils/user_preferences.dart
import 'dart:convert'; import 'package:login_signup_example/model/user.dart'; import 'package:shared_preferences/shared_preferences.dart'; class UserPreferences { static SharedPreferences _preferences; static const _keyUsers = 'users'; static Future init() async => _preferences = await SharedPreferences.getInstance(); static Future setUser(User user) async { final json = jsonEncode(user.toJson()); final idUser = user.id; await _preferences.setString(idUser, json); } static User getUser(String idUser) { final json = _preferences.getString(idUser); return User.fromJson(jsonDecode(json)); } static Future addUsers(User user) async { final idUsers = _preferences.getStringList(_keyUsers) ?? <String>[]; final newIdUsers = List.of(idUsers)..add(user.id); await _preferences.setStringList(_keyUsers, newIdUsers); } static List<User> getUsers() { final idUsers = _preferences.getStringList(_keyUsers); if (idUsers == null) { return <User>[]; } else { return idUsers.map<User>(getUser).toList(); } } }
0
mirrored_repositories/login_signup_example/lib
mirrored_repositories/login_signup_example/lib/utils/user_simple_preferences.dart
import 'package:shared_preferences/shared_preferences.dart'; class UserSimplePreferences { static SharedPreferences _preferences; static const _keyUsername = 'username'; static const _keyPets = 'pets'; static const _keyBirthday = 'birthday'; static Future init() async => _preferences = await SharedPreferences.getInstance(); static Future setUsername(String username) async => await _preferences.setString(_keyUsername, username); static String getUsername() => _preferences.getString(_keyUsername); static Future setPets(List<String> pets) async => await _preferences.setStringList(_keyPets, pets); static List<String> getPets() => _preferences.getStringList(_keyPets); static Future setBirthday(DateTime dateOfBirth) async { final birthday = dateOfBirth.toIso8601String(); return await _preferences.setString(_keyBirthday, birthday); } static DateTime getBirthday() { final birthday = _preferences.getString(_keyBirthday); return birthday == null ? null : DateTime.tryParse(birthday); } }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/firebase_options.dart
// File generated by FlutterFire CLI. // ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; import 'package:flutter/foundation.dart' show defaultTargetPlatform, kIsWeb, TargetPlatform; /// Default [FirebaseOptions] for use with your Firebase apps. /// /// Example: /// ```dart /// import 'firebase_options.dart'; /// // ... /// await Firebase.initializeApp( /// options: DefaultFirebaseOptions.currentPlatform, /// ); /// ``` class DefaultFirebaseOptions { static FirebaseOptions get currentPlatform { if (kIsWeb) { return web; } switch (defaultTargetPlatform) { case TargetPlatform.android: return android; case TargetPlatform.iOS: return ios; case TargetPlatform.macOS: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for macos - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); case TargetPlatform.windows: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for windows - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); case TargetPlatform.linux: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for linux - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); default: throw UnsupportedError( 'DefaultFirebaseOptions are not supported for this platform.', ); } } static const FirebaseOptions android = FirebaseOptions( apiKey: 'AIzaSyBeszZHLYJNyjUhpujMH9yZ4ol9JqsAmPU', appId: '1:288842837392:android:1353619813061d867a5715', messagingSenderId: '288842837392', projectId: 'we-chat-75f13', storageBucket: 'we-chat-75f13.appspot.com', ); static const FirebaseOptions ios = FirebaseOptions( apiKey: 'AIzaSyCCYZoZ5DvuitZJ7qK5iWM3ARHBDoFFriY', appId: '1:288842837392:ios:f39c8dc31525a6687a5715', messagingSenderId: '288842837392', projectId: 'we-chat-75f13', storageBucket: 'we-chat-75f13.appspot.com', androidClientId: '288842837392-gvt1l790g0t1fmnurc5pmko3oss8b1tq.apps.googleusercontent.com', iosClientId: '288842837392-sgib97u6439i4jte3bo19u00fh663euu.apps.googleusercontent.com', iosBundleId: 'com.harshRajpurohit.weChat', ); static const FirebaseOptions web = FirebaseOptions( apiKey: 'AIzaSyBW-1MjB067GUwQHPnYmWkr_4iMz13UgRs', appId: '1:288842837392:web:6ae5bafc6d7d4f407a5715', messagingSenderId: '288842837392', projectId: 'we-chat-75f13', authDomain: 'we-chat-75f13.firebaseapp.com', storageBucket: 'we-chat-75f13.appspot.com', ); }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/main.dart
import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_notification_channel/flutter_notification_channel.dart'; import 'package:flutter_notification_channel/notification_importance.dart'; import 'package:we_chat/screens/splash_screen.dart'; import 'package:firebase_core/firebase_core.dart'; import 'firebase_options.dart'; //global object for accessing device screen size late Size mq; void main() { WidgetsFlutterBinding.ensureInitialized(); //enter full-screen SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky); //for setting orientation to portrait only SystemChrome.setPreferredOrientations( [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]) .then((value) { _initializeFirebase(); runApp(const MyApp()); }); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'We Chat', debugShowCheckedModeBanner: false, theme: ThemeData( appBarTheme: const AppBarTheme( centerTitle: true, elevation: 1, iconTheme: IconThemeData(color: Colors.black), titleTextStyle: TextStyle( color: Colors.black, fontWeight: FontWeight.normal, fontSize: 19), backgroundColor: Colors.white, )), home: const SplashScreen()); } } _initializeFirebase() async { await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); var result = await FlutterNotificationChannel().registerNotificationChannel( description: 'For Showing Message Notification', id: 'chats', importance: NotificationImportance.IMPORTANCE_HIGH, name: 'Chats'); log('\nNotification Channel Result: $result'); }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/widgets/chat_user_card.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../api/apis.dart'; import '../helper/my_date_util.dart'; import '../main.dart'; import '../models/chat_user.dart'; import '../models/message.dart'; import '../screens/chat_screen.dart'; import 'dialogs/profile_dialog.dart'; //card to represent a single user in home screen class ChatUserCard extends StatefulWidget { final ChatUser user; const ChatUserCard({super.key, required this.user}); @override State<ChatUserCard> createState() => _ChatUserCardState(); } class _ChatUserCardState extends State<ChatUserCard> { //last message info (if null --> no message) Message? _message; @override Widget build(BuildContext context) { return Card( margin: EdgeInsets.symmetric(horizontal: mq.width * .04, vertical: 4), // color: Colors.blue.shade100, elevation: 0.5, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), child: InkWell( onTap: () { //for navigating to chat screen Navigator.push( context, MaterialPageRoute( builder: (_) => ChatScreen(user: widget.user))); }, child: StreamBuilder( stream: APIs.getLastMessage(widget.user), builder: (context, snapshot) { final data = snapshot.data?.docs; final list = data?.map((e) => Message.fromJson(e.data())).toList() ?? []; if (list.isNotEmpty) _message = list[0]; return ListTile( //user profile picture leading: InkWell( onTap: () { showDialog( context: context, builder: (_) => ProfileDialog(user: widget.user)); }, child: ClipRRect( borderRadius: BorderRadius.circular(mq.height * .03), child: CachedNetworkImage( width: mq.height * .055, height: mq.height * .055, imageUrl: widget.user.image, fit: BoxFit.cover, errorWidget: (context, url, error) => const CircleAvatar( child: Icon(CupertinoIcons.person)), ), ), ), //user name title: Text(widget.user.name), //last message subtitle: Text( _message != null ? _message!.type == Type.image ? 'image' : _message!.msg : widget.user.about, maxLines: 1), //last message time trailing: _message == null ? null //show nothing when no message is sent : _message!.read.isEmpty && _message!.fromId != APIs.user.uid ? //show for unread message Container( width: 15, height: 15, decoration: BoxDecoration( color: Colors.greenAccent.shade400, borderRadius: BorderRadius.circular(10)), ) : //message sent time Text( MyDateUtil.getLastMessageTime( context: context, time: _message!.sent), style: const TextStyle(color: Colors.black54), ), ); }, )), ); } }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/widgets/message_card.dart
import 'dart:developer'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:gallery_saver_updated/gallery_saver.dart'; import '../api/apis.dart'; import '../helper/dialogs.dart'; import '../helper/my_date_util.dart'; import '../main.dart'; import '../models/message.dart'; // for showing single message details class MessageCard extends StatefulWidget { const MessageCard({super.key, required this.message}); final Message message; @override State<MessageCard> createState() => _MessageCardState(); } class _MessageCardState extends State<MessageCard> { @override Widget build(BuildContext context) { bool isMe = APIs.user.uid == widget.message.fromId; return InkWell( onLongPress: () { _showBottomSheet(isMe); }, child: isMe ? _greenMessage() : _blueMessage()); } // sender or another user message Widget _blueMessage() { //update last read message if sender and receiver are different if (widget.message.read.isEmpty) { APIs.updateMessageReadStatus(widget.message); } return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ //message content Flexible( child: Container( padding: EdgeInsets.all(widget.message.type == Type.image ? mq.width * .03 : mq.width * .04), margin: EdgeInsets.symmetric( horizontal: mq.width * .04, vertical: mq.height * .01), decoration: BoxDecoration( color: const Color.fromARGB(255, 221, 245, 255), border: Border.all(color: Colors.lightBlue), //making borders curved borderRadius: const BorderRadius.only( topLeft: Radius.circular(30), topRight: Radius.circular(30), bottomRight: Radius.circular(30))), child: widget.message.type == Type.text ? //show text Text( widget.message.msg, style: const TextStyle(fontSize: 15, color: Colors.black87), ) : //show image ClipRRect( borderRadius: BorderRadius.circular(15), child: CachedNetworkImage( imageUrl: widget.message.msg, fit: BoxFit.cover, placeholder: (context, url) => const Padding( padding: EdgeInsets.all(8.0), child: CircularProgressIndicator(strokeWidth: 2), ), errorWidget: (context, url, error) => const Icon(Icons.image, size: 70), ), ), ), ), //message time Padding( padding: EdgeInsets.only(right: mq.width * .04), child: Text( MyDateUtil.getFormattedTime( context: context, time: widget.message.sent), style: const TextStyle(fontSize: 13, color: Colors.black54), ), ), ], ); } // our or user message Widget _greenMessage() { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ //message time Row( children: [ //for adding some space SizedBox(width: mq.width * .04), //double tick blue icon for message read if (widget.message.read.isNotEmpty) const Icon(Icons.done_all_rounded, color: Colors.blue, size: 20), //for adding some space const SizedBox(width: 2), //sent time Text( MyDateUtil.getFormattedTime( context: context, time: widget.message.sent), style: const TextStyle(fontSize: 13, color: Colors.black54), ), ], ), //message content Flexible( child: Container( padding: EdgeInsets.all(widget.message.type == Type.image ? mq.width * .03 : mq.width * .04), margin: EdgeInsets.symmetric( horizontal: mq.width * .04, vertical: mq.height * .01), decoration: BoxDecoration( color: const Color.fromARGB(255, 218, 255, 176), border: Border.all(color: Colors.lightGreen), //making borders curved borderRadius: const BorderRadius.only( topLeft: Radius.circular(30), topRight: Radius.circular(30), bottomLeft: Radius.circular(30))), child: widget.message.type == Type.text ? //show text Text( widget.message.msg, style: const TextStyle(fontSize: 15, color: Colors.black87), ) : //show image ClipRRect( borderRadius: BorderRadius.circular(15), child: CachedNetworkImage( imageUrl: widget.message.msg, placeholder: (context, url) => const Padding( padding: EdgeInsets.all(8.0), child: CircularProgressIndicator(strokeWidth: 2), ), errorWidget: (context, url, error) => const Icon(Icons.image, size: 70), ), ), ), ), ], ); } // bottom sheet for modifying message details void _showBottomSheet(bool isMe) { showModalBottomSheet( context: context, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(20), topRight: Radius.circular(20))), builder: (_) { return ListView( shrinkWrap: true, children: [ //black divider Container( height: 4, margin: EdgeInsets.symmetric( vertical: mq.height * .015, horizontal: mq.width * .4), decoration: BoxDecoration( color: Colors.grey, borderRadius: BorderRadius.circular(8)), ), widget.message.type == Type.text ? //copy option _OptionItem( icon: const Icon(Icons.copy_all_rounded, color: Colors.blue, size: 26), name: 'Copy Text', onTap: () async { await Clipboard.setData( ClipboardData(text: widget.message.msg)) .then((value) { //for hiding bottom sheet Navigator.pop(context); Dialogs.showSnackbar(context, 'Text Copied!'); }); }) : //save option _OptionItem( icon: const Icon(Icons.download_rounded, color: Colors.blue, size: 26), name: 'Save Image', onTap: () async { try { log('Image Url: ${widget.message.msg}'); await GallerySaver.saveImage(widget.message.msg, albumName: 'We Chat') .then((success) { //for hiding bottom sheet Navigator.pop(context); if (success != null && success) { Dialogs.showSnackbar( context, 'Image Successfully Saved!'); } }); } catch (e) { log('ErrorWhileSavingImg: $e'); } }), //separator or divider if (isMe) Divider( color: Colors.black54, endIndent: mq.width * .04, indent: mq.width * .04, ), //edit option if (widget.message.type == Type.text && isMe) _OptionItem( icon: const Icon(Icons.edit, color: Colors.blue, size: 26), name: 'Edit Message', onTap: () { //for hiding bottom sheet Navigator.pop(context); _showMessageUpdateDialog(); }), //delete option if (isMe) _OptionItem( icon: const Icon(Icons.delete_forever, color: Colors.red, size: 26), name: 'Delete Message', onTap: () async { await APIs.deleteMessage(widget.message).then((value) { //for hiding bottom sheet Navigator.pop(context); }); }), //separator or divider Divider( color: Colors.black54, endIndent: mq.width * .04, indent: mq.width * .04, ), //sent time _OptionItem( icon: const Icon(Icons.remove_red_eye, color: Colors.blue), name: 'Sent At: ${MyDateUtil.getMessageTime(context: context, time: widget.message.sent)}', onTap: () {}), //read time _OptionItem( icon: const Icon(Icons.remove_red_eye, color: Colors.green), name: widget.message.read.isEmpty ? 'Read At: Not seen yet' : 'Read At: ${MyDateUtil.getMessageTime(context: context, time: widget.message.read)}', onTap: () {}), ], ); }); } //dialog for updating message content void _showMessageUpdateDialog() { String updatedMsg = widget.message.msg; showDialog( context: context, builder: (_) => AlertDialog( contentPadding: const EdgeInsets.only( left: 24, right: 24, top: 20, bottom: 10), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20)), //title title: const Row( children: [ Icon( Icons.message, color: Colors.blue, size: 28, ), Text(' Update Message') ], ), //content content: TextFormField( initialValue: updatedMsg, maxLines: null, onChanged: (value) => updatedMsg = value, decoration: InputDecoration( border: OutlineInputBorder( borderRadius: BorderRadius.circular(15))), ), //actions actions: [ //cancel button MaterialButton( onPressed: () { //hide alert dialog Navigator.pop(context); }, child: const Text( 'Cancel', style: TextStyle(color: Colors.blue, fontSize: 16), )), //update button MaterialButton( onPressed: () { //hide alert dialog Navigator.pop(context); APIs.updateMessage(widget.message, updatedMsg); }, child: const Text( 'Update', style: TextStyle(color: Colors.blue, fontSize: 16), )) ], )); } } //custom options card (for copy, edit, delete, etc.) class _OptionItem extends StatelessWidget { final Icon icon; final String name; final VoidCallback onTap; const _OptionItem( {required this.icon, required this.name, required this.onTap}); @override Widget build(BuildContext context) { return InkWell( onTap: () => onTap(), child: Padding( padding: EdgeInsets.only( left: mq.width * .05, top: mq.height * .015, bottom: mq.height * .015), child: Row(children: [ icon, Flexible( child: Text(' $name', style: const TextStyle( fontSize: 15, color: Colors.black54, letterSpacing: 0.5))) ]), )); } }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/widgets
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/widgets/dialogs/profile_dialog.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../main.dart'; import '../../models/chat_user.dart'; import '../../screens/view_profile_screen.dart'; class ProfileDialog extends StatelessWidget { const ProfileDialog({super.key, required this.user}); final ChatUser user; @override Widget build(BuildContext context) { return AlertDialog( contentPadding: EdgeInsets.zero, backgroundColor: Colors.white.withOpacity(.9), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), content: SizedBox( width: mq.width * .6, height: mq.height * .35, child: Stack( children: [ //user profile picture Positioned( top: mq.height * .075, left: mq.width * .1, child: ClipRRect( borderRadius: BorderRadius.circular(mq.height * .25), child: CachedNetworkImage( width: mq.width * .5, height: mq.width * .5, fit: BoxFit.cover, imageUrl: user.image, errorWidget: (context, url, error) => const CircleAvatar(child: Icon(CupertinoIcons.person)), ), ), ), //user name Positioned( left: mq.width * .04, top: mq.height * .02, width: mq.width * .55, child: Text(user.name, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.w500)), ), //info button Positioned( right: 8, top: 6, child: MaterialButton( onPressed: () { //for hiding image dialog Navigator.pop(context); //move to view profile screen Navigator.push( context, MaterialPageRoute( builder: (_) => ViewProfileScreen(user: user))); }, minWidth: 0, padding: const EdgeInsets.all(0), shape: const CircleBorder(), child: const Icon(Icons.info_outline, color: Colors.blue, size: 30), )) ], )), ); } }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/models/chat_user.dart
class ChatUser { ChatUser({ required this.image, required this.about, required this.name, required this.createdAt, required this.isOnline, required this.id, required this.lastActive, required this.email, required this.pushToken, }); late String image; late String about; late String name; late String createdAt; late bool isOnline; late String id; late String lastActive; late String email; late String pushToken; ChatUser.fromJson(Map<String, dynamic> json) { image = json['image'] ?? ''; about = json['about'] ?? ''; name = json['name'] ?? ''; createdAt = json['created_at'] ?? ''; isOnline = json['is_online'] ?? ''; id = json['id'] ?? ''; lastActive = json['last_active'] ?? ''; email = json['email'] ?? ''; pushToken = json['push_token'] ?? ''; } Map<String, dynamic> toJson() { final data = <String, dynamic>{}; data['image'] = image; data['about'] = about; data['name'] = name; data['created_at'] = createdAt; data['is_online'] = isOnline; data['id'] = id; data['last_active'] = lastActive; data['email'] = email; data['push_token'] = pushToken; return data; } }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/models/message.dart
class Message { Message({ required this.toId, required this.msg, required this.read, required this.type, required this.fromId, required this.sent, }); late final String toId; late final String msg; late final String read; late final String fromId; late final String sent; late final Type type; Message.fromJson(Map<String, dynamic> json) { toId = json['toId'].toString(); msg = json['msg'].toString(); read = json['read'].toString(); type = json['type'].toString() == Type.image.name ? Type.image : Type.text; fromId = json['fromId'].toString(); sent = json['sent'].toString(); } Map<String, dynamic> toJson() { final data = <String, dynamic>{}; data['toId'] = toId; data['msg'] = msg; data['read'] = read; data['type'] = type.name; data['fromId'] = fromId; data['sent'] = sent; return data; } } enum Type { text, image }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/api/notification_access_token.dart
import 'dart:developer'; import 'package:googleapis_auth/auth_io.dart'; class NotificationAccessToken { static String? _token; //to generate token only once for an app run static Future<String?> get getToken async => _token ?? await _getAccessToken(); // to get admin bearer token static Future<String?> _getAccessToken() async { try { const fMessagingScope = 'https://www.googleapis.com/auth/firebase.messaging'; final client = await clientViaServiceAccount( // To get Admin Json File: Go to Firebase > Project Settings > Service Accounts // > Click on 'Generate new private key' Btn & Json file will be downloaded // Paste Your Generated Json File Content ServiceAccountCredentials.fromJson({ "type": "service_account", "project_id": "we-chat-75f13", "private_key_id": "1a1621fe6a5374932428ae0f4a05782b7acccb14", "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC6R/L0jOehSyDP\nFX8Sgq+E3HXtgLRppZHy5FQUmDB6pEPCCGG8gOnt/2GzFlIcAI0SSFt//JMwqGoD\n4I5BeV9oKSrmR8YFFllmQrazIL5Ynf9NrNB1pR0+UjAWfgU3O8f5ZclaG5HnFap/\nB93Jt6MatWDKQilnjPnFB+CxyWkXmKls3Qv4W1mot7JC+OoscLz13w9U/+plLZmF\ne9CS/Gynp8F1IlKbWJSEy8ltkHEhpzpm9RDrWD+trBbWHVnhuaOz7rqO4Ydts+TK\npNugK/ksL5B6SFtqZfkvsnZzR2tKh0VtLJLfH5I8tEGWJteli/0RqnRXhBruPrLa\nP4fZo3wxAgMBAAECggEAKa2z8R3+rGKyFEtXu2VEjqpB83IOy615JnqKSnJTtHkA\n1Q7JiWLhlDfF3QszM2M3LR5F5LC3IRWpZLUvNvyISXaei9gGuPgrZ/soxBLhK9Qr\n/W3bVVssXBeI/VtUYOuN/mHVB4VwI19AXrw8liexhWYMIizj9TCAaOJulnC9RAMo\ntxAu2Xt69vE+cIgPTUzf01fY7NXHVnQs3aXvuD3LfQVHQXwbU/BApSNCPn3Df4YQ\nAUQhSXGprEtDmF89d1sCg/v92DxXH22B/nqpUh51iLSzCW6QjUGy4YlwdJ0U/qhj\nRrefq6sC4dJgVcbmJyQkgyAdouZKA2niFfSHeVqXTQKBgQDx+He1kJCWlE2AOFAK\noTNlLSsJxjj6fRhcuxWykZCXvVP2xi+CfYFCN+n+ZDGhU3pi1NDJ8Twh4M7EFCM7\npGmhW7qDgiXqpB3R8lt3huH+3rPqP6z+2zDi+HxCJckpWpb32TorgkIdSRp3eM0s\n03kl0rB6xW59LMNMKBz2/mn5RQKBgQDFFOPp+u6MerJjjuVD9aWTzYuCON0z3DO/\n4bbGIP6vZ4SzmlYtdDHBcZp/ogLIgK4AGYNwWSap6kQVDV/6llxQu9uLtPpwkrza\n3BTKrSQdtu7tvdHWSu5cCqkWIz4hVEDpHWeXoFkg37GDVbK+CZdYOb2y5d2Bel/6\nYY2DoQ5H/QKBgB8Rt1VB5b7f9f+Tu3tR7YZ9QTx1DlXjgCBQCV4vYLCLJ9/U3L7V\nnKZDBbGbbd/4FwvfpZt4dS8obYQxzcBXwRRt8cn3CSVSw1100BfN4vDV6aYXXQAw\nZtuN6m6X6Xd84UubweNaS2D1RQe4JCgwUyrvHaf199TszXrW37k7O6I9AoGAVFxF\n1wEvnXhj5dPj9Xwv/R2N6xcWML3AdRFUIGk9O63vEsYsv1YueiR7wsiBsnvKf4Zs\nSeoPb8o0jGJmRCiaqYBQUPQOA6P8LR7p03vbqtCEY8XODZGTiFiT2kMJtFCRXHfW\nwQPFQxodrR9A3LHUU9KbjflxIJxWeyHI5qBJMa0CgYEAz2iWE5rNtJ1mLrsC/o8j\njDV0RHzhN2f2pAxLlXHJ40nvQ5Nbyk5gCI2llUTN73YPNJXcM6ZKARyzlx0cA0TE\nolbpV91lb5j2L2HLAz1nciOzh1IRCJRk7T7j01TrygOv2n6fyWfUGuHCR5lztaiv\nykRUUKoMSaezOlB88DIqTIQ=\n-----END PRIVATE KEY-----\n", "client_email": "[email protected]", "client_id": "115556782220674603906", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-9y8mc%40we-chat-75f13.iam.gserviceaccount.com", "universe_domain": "googleapis.com" }), [fMessagingScope], ); _token = client.credentials.accessToken.data; return _token; } catch (e) { log('$e'); return null; } } }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/api/apis.dart
import 'dart:convert'; import 'dart:developer'; import 'dart:io'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:http/http.dart'; import '../models/chat_user.dart'; import '../models/message.dart'; import 'notification_access_token.dart'; class APIs { // for authentication static FirebaseAuth get auth => FirebaseAuth.instance; // for accessing cloud firestore database static FirebaseFirestore firestore = FirebaseFirestore.instance; // for accessing firebase storage static FirebaseStorage storage = FirebaseStorage.instance; // for storing self information static ChatUser me = ChatUser( id: user.uid, name: user.displayName.toString(), email: user.email.toString(), about: "Hey, I'm using We Chat!", image: user.photoURL.toString(), createdAt: '', isOnline: false, lastActive: '', pushToken: ''); // to return current user static User get user => auth.currentUser!; // for accessing firebase messaging (Push Notification) static FirebaseMessaging fMessaging = FirebaseMessaging.instance; // for getting firebase messaging token static Future<void> getFirebaseMessagingToken() async { await fMessaging.requestPermission(); await fMessaging.getToken().then((t) { if (t != null) { me.pushToken = t; log('Push Token: $t'); } }); // for handling foreground messages // FirebaseMessaging.onMessage.listen((RemoteMessage message) { // log('Got a message whilst in the foreground!'); // log('Message data: ${message.data}'); // if (message.notification != null) { // log('Message also contained a notification: ${message.notification}'); // } // }); } // for sending push notification (Updated Codes) static Future<void> sendPushNotification( ChatUser chatUser, String msg) async { try { final body = { "message": { "token": chatUser.pushToken, "notification": { "title": me.name, //our name should be send "body": msg, }, } }; // Firebase Project > Project Settings > General Tab > Project ID const projectID = 'we-chat-75f13'; // get firebase admin token final bearerToken = await NotificationAccessToken.getToken; log('bearerToken: $bearerToken'); // handle null token if (bearerToken == null) return; var res = await post( Uri.parse( 'https://fcm.googleapis.com/v1/projects/$projectID/messages:send'), headers: { HttpHeaders.contentTypeHeader: 'application/json', HttpHeaders.authorizationHeader: 'Bearer $bearerToken' }, body: jsonEncode(body), ); log('Response status: ${res.statusCode}'); log('Response body: ${res.body}'); } catch (e) { log('\nsendPushNotificationE: $e'); } } // for checking if user exists or not? static Future<bool> userExists() async { return (await firestore.collection('users').doc(user.uid).get()).exists; } // for adding an chat user for our conversation static Future<bool> addChatUser(String email) async { final data = await firestore .collection('users') .where('email', isEqualTo: email) .get(); log('data: ${data.docs}'); if (data.docs.isNotEmpty && data.docs.first.id != user.uid) { //user exists log('user exists: ${data.docs.first.data()}'); firestore .collection('users') .doc(user.uid) .collection('my_users') .doc(data.docs.first.id) .set({}); return true; } else { //user doesn't exists return false; } } // for getting current user info static Future<void> getSelfInfo() async { await firestore.collection('users').doc(user.uid).get().then((user) async { if (user.exists) { me = ChatUser.fromJson(user.data()!); await getFirebaseMessagingToken(); //for setting user status to active APIs.updateActiveStatus(true); log('My Data: ${user.data()}'); } else { await createUser().then((value) => getSelfInfo()); } }); } // for creating a new user static Future<void> createUser() async { final time = DateTime.now().millisecondsSinceEpoch.toString(); final chatUser = ChatUser( id: user.uid, name: user.displayName.toString(), email: user.email.toString(), about: "Hey, I'm using We Chat!", image: user.photoURL.toString(), createdAt: time, isOnline: false, lastActive: time, pushToken: ''); return await firestore .collection('users') .doc(user.uid) .set(chatUser.toJson()); } // for getting id's of known users from firestore database static Stream<QuerySnapshot<Map<String, dynamic>>> getMyUsersId() { return firestore .collection('users') .doc(user.uid) .collection('my_users') .snapshots(); } // for getting all users from firestore database static Stream<QuerySnapshot<Map<String, dynamic>>> getAllUsers( List<String> userIds) { log('\nUserIds: $userIds'); return firestore .collection('users') .where('id', whereIn: userIds.isEmpty ? [''] : userIds) //because empty list throws an error // .where('id', isNotEqualTo: user.uid) .snapshots(); } // for adding an user to my user when first message is send static Future<void> sendFirstMessage( ChatUser chatUser, String msg, Type type) async { await firestore .collection('users') .doc(chatUser.id) .collection('my_users') .doc(user.uid) .set({}).then((value) => sendMessage(chatUser, msg, type)); } // for updating user information static Future<void> updateUserInfo() async { await firestore.collection('users').doc(user.uid).update({ 'name': me.name, 'about': me.about, }); } // update profile picture of user static Future<void> updateProfilePicture(File file) async { //getting image file extension final ext = file.path.split('.').last; log('Extension: $ext'); //storage file ref with path final ref = storage.ref().child('profile_pictures/${user.uid}.$ext'); //uploading image await ref .putFile(file, SettableMetadata(contentType: 'image/$ext')) .then((p0) { log('Data Transferred: ${p0.bytesTransferred / 1000} kb'); }); //updating image in firestore database me.image = await ref.getDownloadURL(); await firestore .collection('users') .doc(user.uid) .update({'image': me.image}); } // for getting specific user info static Stream<QuerySnapshot<Map<String, dynamic>>> getUserInfo( ChatUser chatUser) { return firestore .collection('users') .where('id', isEqualTo: chatUser.id) .snapshots(); } // update online or last active status of user static Future<void> updateActiveStatus(bool isOnline) async { firestore.collection('users').doc(user.uid).update({ 'is_online': isOnline, 'last_active': DateTime.now().millisecondsSinceEpoch.toString(), 'push_token': me.pushToken, }); } ///************** Chat Screen Related APIs ************** // chats (collection) --> conversation_id (doc) --> messages (collection) --> message (doc) // useful for getting conversation id static String getConversationID(String id) => user.uid.hashCode <= id.hashCode ? '${user.uid}_$id' : '${id}_${user.uid}'; // for getting all messages of a specific conversation from firestore database static Stream<QuerySnapshot<Map<String, dynamic>>> getAllMessages( ChatUser user) { return firestore .collection('chats/${getConversationID(user.id)}/messages/') .orderBy('sent', descending: true) .snapshots(); } // for sending message static Future<void> sendMessage( ChatUser chatUser, String msg, Type type) async { //message sending time (also used as id) final time = DateTime.now().millisecondsSinceEpoch.toString(); //message to send final Message message = Message( toId: chatUser.id, msg: msg, read: '', type: type, fromId: user.uid, sent: time); final ref = firestore .collection('chats/${getConversationID(chatUser.id)}/messages/'); await ref.doc(time).set(message.toJson()).then((value) => sendPushNotification(chatUser, type == Type.text ? msg : 'image')); } //update read status of message static Future<void> updateMessageReadStatus(Message message) async { firestore .collection('chats/${getConversationID(message.fromId)}/messages/') .doc(message.sent) .update({'read': DateTime.now().millisecondsSinceEpoch.toString()}); } //get only last message of a specific chat static Stream<QuerySnapshot<Map<String, dynamic>>> getLastMessage( ChatUser user) { return firestore .collection('chats/${getConversationID(user.id)}/messages/') .orderBy('sent', descending: true) .limit(1) .snapshots(); } //send chat image static Future<void> sendChatImage(ChatUser chatUser, File file) async { //getting image file extension final ext = file.path.split('.').last; //storage file ref with path final ref = storage.ref().child( 'images/${getConversationID(chatUser.id)}/${DateTime.now().millisecondsSinceEpoch}.$ext'); //uploading image await ref .putFile(file, SettableMetadata(contentType: 'image/$ext')) .then((p0) { log('Data Transferred: ${p0.bytesTransferred / 1000} kb'); }); //updating image in firestore database final imageUrl = await ref.getDownloadURL(); await sendMessage(chatUser, imageUrl, Type.image); } //delete message static Future<void> deleteMessage(Message message) async { await firestore .collection('chats/${getConversationID(message.toId)}/messages/') .doc(message.sent) .delete(); if (message.type == Type.image) { await storage.refFromURL(message.msg).delete(); } } //update message static Future<void> updateMessage(Message message, String updatedMsg) async { await firestore .collection('chats/${getConversationID(message.toId)}/messages/') .doc(message.sent) .update({'msg': updatedMsg}); } }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/helper/my_date_util.dart
import 'package:flutter/material.dart'; class MyDateUtil { // for getting formatted time from milliSecondsSinceEpochs String static String getFormattedTime( {required BuildContext context, required String time}) { final date = DateTime.fromMillisecondsSinceEpoch(int.parse(time)); return TimeOfDay.fromDateTime(date).format(context); } // for getting formatted time for sent & read static String getMessageTime( {required BuildContext context, required String time}) { final DateTime sent = DateTime.fromMillisecondsSinceEpoch(int.parse(time)); final DateTime now = DateTime.now(); final formattedTime = TimeOfDay.fromDateTime(sent).format(context); if (now.day == sent.day && now.month == sent.month && now.year == sent.year) { return formattedTime; } return now.year == sent.year ? '$formattedTime - ${sent.day} ${_getMonth(sent)}' : '$formattedTime - ${sent.day} ${_getMonth(sent)} ${sent.year}'; } //get last message time (used in chat user card) static String getLastMessageTime( {required BuildContext context, required String time, bool showYear = false}) { final DateTime sent = DateTime.fromMillisecondsSinceEpoch(int.parse(time)); final DateTime now = DateTime.now(); if (now.day == sent.day && now.month == sent.month && now.year == sent.year) { return TimeOfDay.fromDateTime(sent).format(context); } return showYear ? '${sent.day} ${_getMonth(sent)} ${sent.year}' : '${sent.day} ${_getMonth(sent)}'; } //get formatted last active time of user in chat screen static String getLastActiveTime( {required BuildContext context, required String lastActive}) { final int i = int.tryParse(lastActive) ?? -1; //if time is not available then return below statement if (i == -1) return 'Last seen not available'; DateTime time = DateTime.fromMillisecondsSinceEpoch(i); DateTime now = DateTime.now(); String formattedTime = TimeOfDay.fromDateTime(time).format(context); if (time.day == now.day && time.month == now.month && time.year == time.year) { return 'Last seen today at $formattedTime'; } if ((now.difference(time).inHours / 24).round() == 1) { return 'Last seen yesterday at $formattedTime'; } String month = _getMonth(time); return 'Last seen on ${time.day} $month on $formattedTime'; } // get month name from month no. or index static String _getMonth(DateTime date) { switch (date.month) { case 1: return 'Jan'; case 2: return 'Feb'; case 3: return 'Mar'; case 4: return 'Apr'; case 5: return 'May'; case 6: return 'Jun'; case 7: return 'Jul'; case 8: return 'Aug'; case 9: return 'Sept'; case 10: return 'Oct'; case 11: return 'Nov'; case 12: return 'Dec'; } return 'NA'; } }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/helper/dialogs.dart
import 'package:flutter/material.dart'; class Dialogs { static void showSnackbar(BuildContext context, String msg) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text(msg), backgroundColor: Colors.blue.withOpacity(.8), behavior: SnackBarBehavior.floating)); } static void showProgressBar(BuildContext context) { showDialog( context: context, builder: (_) => const Center( child: CircularProgressIndicator( strokeWidth: 1, ))); } }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/screens/view_profile_screen.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../helper/my_date_util.dart'; import '../main.dart'; import '../models/chat_user.dart'; //view profile screen -- to view profile of user class ViewProfileScreen extends StatefulWidget { final ChatUser user; const ViewProfileScreen({super.key, required this.user}); @override State<ViewProfileScreen> createState() => _ViewProfileScreenState(); } class _ViewProfileScreenState extends State<ViewProfileScreen> { @override Widget build(BuildContext context) { return GestureDetector( // for hiding keyboard onTap: FocusScope.of(context).unfocus, child: Scaffold( //app bar appBar: AppBar(title: Text(widget.user.name)), //user about floatingActionButton: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( 'Joined On: ', style: TextStyle( color: Colors.black87, fontWeight: FontWeight.w500, fontSize: 15), ), Text( MyDateUtil.getLastMessageTime( context: context, time: widget.user.createdAt, showYear: true), style: const TextStyle(color: Colors.black54, fontSize: 15)), ], ), //body body: Padding( padding: EdgeInsets.symmetric(horizontal: mq.width * .05), child: SingleChildScrollView( child: Column( children: [ // for adding some space SizedBox(width: mq.width, height: mq.height * .03), //user profile picture ClipRRect( borderRadius: BorderRadius.circular(mq.height * .1), child: CachedNetworkImage( width: mq.height * .2, height: mq.height * .2, fit: BoxFit.cover, imageUrl: widget.user.image, errorWidget: (context, url, error) => const CircleAvatar( child: Icon(CupertinoIcons.person)), ), ), // for adding some space SizedBox(height: mq.height * .03), // user email label Text(widget.user.email, style: const TextStyle(color: Colors.black87, fontSize: 16)), // for adding some space SizedBox(height: mq.height * .02), //user about Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( 'About: ', style: TextStyle( color: Colors.black87, fontWeight: FontWeight.w500, fontSize: 15), ), Text(widget.user.about, style: const TextStyle( color: Colors.black54, fontSize: 15)), ], ), ], ), ), )), ); } }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/screens/profile_screen.dart
import 'dart:developer'; import 'dart:io'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:image_picker/image_picker.dart'; import '../api/apis.dart'; import '../helper/dialogs.dart'; import '../main.dart'; import '../models/chat_user.dart'; import 'auth/login_screen.dart'; //profile screen -- to show signed in user info class ProfileScreen extends StatefulWidget { final ChatUser user; const ProfileScreen({super.key, required this.user}); @override State<ProfileScreen> createState() => _ProfileScreenState(); } class _ProfileScreenState extends State<ProfileScreen> { final _formKey = GlobalKey<FormState>(); String? _image; @override Widget build(BuildContext context) { return GestureDetector( // for hiding keyboard onTap: FocusScope.of(context).unfocus, child: Scaffold( //app bar appBar: AppBar(title: const Text('Profile Screen')), //floating button to log out floatingActionButton: Padding( padding: const EdgeInsets.only(bottom: 10), child: FloatingActionButton.extended( backgroundColor: Colors.redAccent, onPressed: () async { //for showing progress dialog Dialogs.showProgressBar(context); await APIs.updateActiveStatus(false); //sign out from app await APIs.auth.signOut().then((value) async { await GoogleSignIn().signOut().then((value) { //for hiding progress dialog Navigator.pop(context); //for moving to home screen Navigator.pop(context); // APIs.auth = FirebaseAuth.instance; //replacing home screen with login screen Navigator.pushReplacement( context, MaterialPageRoute( builder: (_) => const LoginScreen())); }); }); }, icon: const Icon(Icons.logout), label: const Text('Logout')), ), //body body: Form( key: _formKey, child: Padding( padding: EdgeInsets.symmetric(horizontal: mq.width * .05), child: SingleChildScrollView( child: Column( children: [ // for adding some space SizedBox(width: mq.width, height: mq.height * .03), //user profile picture Stack( children: [ //profile picture _image != null ? //local image ClipRRect( borderRadius: BorderRadius.circular(mq.height * .1), child: Image.file(File(_image!), width: mq.height * .2, height: mq.height * .2, fit: BoxFit.cover)) : //image from server ClipRRect( borderRadius: BorderRadius.circular(mq.height * .1), child: CachedNetworkImage( width: mq.height * .2, height: mq.height * .2, fit: BoxFit.cover, imageUrl: widget.user.image, errorWidget: (context, url, error) => const CircleAvatar( child: Icon(CupertinoIcons.person)), ), ), //edit image button Positioned( bottom: 0, right: 0, child: MaterialButton( elevation: 1, onPressed: () { _showBottomSheet(); }, shape: const CircleBorder(), color: Colors.white, child: const Icon(Icons.edit, color: Colors.blue), ), ) ], ), // for adding some space SizedBox(height: mq.height * .03), // user email label Text(widget.user.email, style: const TextStyle( color: Colors.black54, fontSize: 16)), // for adding some space SizedBox(height: mq.height * .05), // name input field TextFormField( initialValue: widget.user.name, onSaved: (val) => APIs.me.name = val ?? '', validator: (val) => val != null && val.isNotEmpty ? null : 'Required Field', decoration: InputDecoration( prefixIcon: const Icon(Icons.person, color: Colors.blue), border: OutlineInputBorder( borderRadius: BorderRadius.circular(12)), hintText: 'eg. Happy Singh', label: const Text('Name')), ), // for adding some space SizedBox(height: mq.height * .02), // about input field TextFormField( initialValue: widget.user.about, onSaved: (val) => APIs.me.about = val ?? '', validator: (val) => val != null && val.isNotEmpty ? null : 'Required Field', decoration: InputDecoration( prefixIcon: const Icon(Icons.info_outline, color: Colors.blue), border: OutlineInputBorder( borderRadius: BorderRadius.circular(12)), hintText: 'eg. Feeling Happy', label: const Text('About')), ), // for adding some space SizedBox(height: mq.height * .05), // update profile button ElevatedButton.icon( style: ElevatedButton.styleFrom( shape: const StadiumBorder(), minimumSize: Size(mq.width * .5, mq.height * .06)), onPressed: () { if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); APIs.updateUserInfo().then((value) { Dialogs.showSnackbar( context, 'Profile Updated Successfully!'); }); } }, icon: const Icon(Icons.edit, size: 28), label: const Text('UPDATE', style: TextStyle(fontSize: 16)), ) ], ), ), ), )), ); } // bottom sheet for picking a profile picture for user void _showBottomSheet() { showModalBottomSheet( context: context, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(20), topRight: Radius.circular(20))), builder: (_) { return ListView( shrinkWrap: true, padding: EdgeInsets.only(top: mq.height * .03, bottom: mq.height * .05), children: [ //pick profile picture label const Text('Pick Profile Picture', textAlign: TextAlign.center, style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500)), //for adding some space SizedBox(height: mq.height * .02), //buttons Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ //pick from gallery button ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.white, shape: const CircleBorder(), fixedSize: Size(mq.width * .3, mq.height * .15)), onPressed: () async { final ImagePicker picker = ImagePicker(); // Pick an image final XFile? image = await picker.pickImage( source: ImageSource.gallery, imageQuality: 80); if (image != null) { log('Image Path: ${image.path}'); setState(() { _image = image.path; }); APIs.updateProfilePicture(File(_image!)); // for hiding bottom sheet if (mounted) Navigator.pop(context); } }, child: Image.asset('images/add_image.png')), //take picture from camera button ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.white, shape: const CircleBorder(), fixedSize: Size(mq.width * .3, mq.height * .15)), onPressed: () async { final ImagePicker picker = ImagePicker(); // Pick an image final XFile? image = await picker.pickImage( source: ImageSource.camera, imageQuality: 80); if (image != null) { log('Image Path: ${image.path}'); setState(() { _image = image.path; }); APIs.updateProfilePicture(File(_image!)); // for hiding bottom sheet if (mounted) Navigator.pop(context); } }, child: Image.asset('images/camera.png')), ], ) ], ); }); } }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/screens/home_screen.dart
import 'dart:developer'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../api/apis.dart'; import '../helper/dialogs.dart'; import '../main.dart'; import '../models/chat_user.dart'; import '../widgets/chat_user_card.dart'; import 'profile_screen.dart'; //home screen -- where all available contacts are shown class HomeScreen extends StatefulWidget { const HomeScreen({super.key}); @override State<HomeScreen> createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { // for storing all users List<ChatUser> _list = []; // for storing searched items final List<ChatUser> _searchList = []; // for storing search status bool _isSearching = false; @override void initState() { super.initState(); APIs.getSelfInfo(); //for updating user active status according to lifecycle events //resume -- active or online //pause -- inactive or offline SystemChannels.lifecycle.setMessageHandler((message) { log('Message: $message'); if (APIs.auth.currentUser != null) { if (message.toString().contains('resume')) { APIs.updateActiveStatus(true); } if (message.toString().contains('pause')) { APIs.updateActiveStatus(false); } } return Future.value(message); }); } @override Widget build(BuildContext context) { return GestureDetector( //for hiding keyboard when a tap is detected on screen onTap: FocusScope.of(context).unfocus, child: PopScope( // onWillPop: () { // if (_isSearching) { // setState(() { // _isSearching = !_isSearching; // }); // return Future.value(false); // } else { // return Future.value(true); // } // }, //if search is on & back button is pressed then close search //or else simple close current screen on back button click canPop: !_isSearching, onPopInvoked: (_) async { if (_isSearching) { setState(() => _isSearching = !_isSearching); } else { Navigator.of(context).pop(); } }, // child: Scaffold( //app bar appBar: AppBar( leading: const Icon(CupertinoIcons.home), title: _isSearching ? TextField( decoration: const InputDecoration( border: InputBorder.none, hintText: 'Name, Email, ...'), autofocus: true, style: const TextStyle(fontSize: 17, letterSpacing: 0.5), //when search text changes then updated search list onChanged: (val) { //search logic _searchList.clear(); for (var i in _list) { if (i.name.toLowerCase().contains(val.toLowerCase()) || i.email.toLowerCase().contains(val.toLowerCase())) { _searchList.add(i); setState(() { _searchList; }); } } }, ) : const Text('We Chat'), actions: [ //search user button IconButton( onPressed: () { setState(() { _isSearching = !_isSearching; }); }, icon: Icon(_isSearching ? CupertinoIcons.clear_circled_solid : Icons.search)), //more features button IconButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (_) => ProfileScreen(user: APIs.me))); }, icon: const Icon(Icons.more_vert)) ], ), //floating button to add new user floatingActionButton: Padding( padding: const EdgeInsets.only(bottom: 10), child: FloatingActionButton( onPressed: () { _addChatUserDialog(); }, child: const Icon(Icons.add_comment_rounded)), ), //body body: StreamBuilder( stream: APIs.getMyUsersId(), //get id of only known users builder: (context, snapshot) { switch (snapshot.connectionState) { //if data is loading case ConnectionState.waiting: case ConnectionState.none: return const Center(child: CircularProgressIndicator()); //if some or all data is loaded then show it case ConnectionState.active: case ConnectionState.done: return StreamBuilder( stream: APIs.getAllUsers( snapshot.data?.docs.map((e) => e.id).toList() ?? []), //get only those user, who's ids are provided builder: (context, snapshot) { switch (snapshot.connectionState) { //if data is loading case ConnectionState.waiting: case ConnectionState.none: // return const Center( // child: CircularProgressIndicator()); //if some or all data is loaded then show it case ConnectionState.active: case ConnectionState.done: final data = snapshot.data?.docs; _list = data ?.map((e) => ChatUser.fromJson(e.data())) .toList() ?? []; if (_list.isNotEmpty) { return ListView.builder( itemCount: _isSearching ? _searchList.length : _list.length, padding: EdgeInsets.only(top: mq.height * .01), physics: const BouncingScrollPhysics(), itemBuilder: (context, index) { return ChatUserCard( user: _isSearching ? _searchList[index] : _list[index]); }); } else { return const Center( child: Text('No Connections Found!', style: TextStyle(fontSize: 20)), ); } } }, ); } }, ), ), ), ); } // for adding new chat user void _addChatUserDialog() { String email = ''; showDialog( context: context, builder: (_) => AlertDialog( contentPadding: const EdgeInsets.only( left: 24, right: 24, top: 20, bottom: 10), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20)), //title title: const Row( children: [ Icon( Icons.person_add, color: Colors.blue, size: 28, ), Text(' Add User') ], ), //content content: TextFormField( maxLines: null, onChanged: (value) => email = value, decoration: InputDecoration( hintText: 'Email Id', prefixIcon: const Icon(Icons.email, color: Colors.blue), border: OutlineInputBorder( borderRadius: BorderRadius.circular(15))), ), //actions actions: [ //cancel button MaterialButton( onPressed: () { //hide alert dialog Navigator.pop(context); }, child: const Text('Cancel', style: TextStyle(color: Colors.blue, fontSize: 16))), //add button MaterialButton( onPressed: () async { //hide alert dialog Navigator.pop(context); if (email.isNotEmpty) { await APIs.addChatUser(email).then((value) { if (!value) { Dialogs.showSnackbar( context, 'User does not Exists!'); } }); } }, child: const Text( 'Add', style: TextStyle(color: Colors.blue, fontSize: 16), )) ], )); } }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/screens/chat_screen.dart
import 'dart:developer'; import 'dart:io'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:emoji_picker_flutter/emoji_picker_flutter.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import '../api/apis.dart'; import '../helper/my_date_util.dart'; import '../main.dart'; import '../models/chat_user.dart'; import '../models/message.dart'; import '../widgets/message_card.dart'; import 'view_profile_screen.dart'; class ChatScreen extends StatefulWidget { final ChatUser user; const ChatScreen({super.key, required this.user}); @override State<ChatScreen> createState() => _ChatScreenState(); } class _ChatScreenState extends State<ChatScreen> { //for storing all messages List<Message> _list = []; //for handling message text changes final _textController = TextEditingController(); //showEmoji -- for storing value of showing or hiding emoji //isUploading -- for checking if image is uploading or not? bool _showEmoji = false, _isUploading = false; @override Widget build(BuildContext context) { return GestureDetector( onTap: FocusScope.of(context).unfocus, child: PopScope( // onWillPop: () { // if (_showEmoji) { // setState(() => _showEmoji = !_showEmoji); // return Future.value(false); // } else { // return Future.value(true); // } // }, //if emojis are shown & back button is pressed then hide emojis //or else simple close current screen on back button click canPop: !_showEmoji, onPopInvoked: (_) async { if (_showEmoji) { setState(() => _showEmoji = !_showEmoji); } else { Navigator.of(context).pop(); } }, // child: Scaffold( //app bar appBar: AppBar( automaticallyImplyLeading: false, flexibleSpace: _appBar(), ), backgroundColor: const Color.fromARGB(255, 234, 248, 255), //body body: SafeArea( child: Column( children: [ Expanded( child: StreamBuilder( stream: APIs.getAllMessages(widget.user), builder: (context, snapshot) { switch (snapshot.connectionState) { //if data is loading case ConnectionState.waiting: case ConnectionState.none: return const SizedBox(); //if some or all data is loaded then show it case ConnectionState.active: case ConnectionState.done: final data = snapshot.data?.docs; _list = data ?.map((e) => Message.fromJson(e.data())) .toList() ?? []; if (_list.isNotEmpty) { return ListView.builder( reverse: true, itemCount: _list.length, padding: EdgeInsets.only(top: mq.height * .01), physics: const BouncingScrollPhysics(), itemBuilder: (context, index) { return MessageCard(message: _list[index]); }); } else { return const Center( child: Text('Say Hii! 👋', style: TextStyle(fontSize: 20)), ); } } }, ), ), //progress indicator for showing uploading if (_isUploading) const Align( alignment: Alignment.centerRight, child: Padding( padding: EdgeInsets.symmetric(vertical: 8, horizontal: 20), child: CircularProgressIndicator(strokeWidth: 2))), //chat input filed _chatInput(), //show emojis on keyboard emoji button click & vice versa if (_showEmoji) SizedBox( height: mq.height * .35, child: EmojiPicker( textEditingController: _textController, config: const Config(), ), ) ], ), ), ), ), ); } // app bar widget Widget _appBar() { return SafeArea( child: InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (_) => ViewProfileScreen(user: widget.user))); }, child: StreamBuilder( stream: APIs.getUserInfo(widget.user), builder: (context, snapshot) { final data = snapshot.data?.docs; final list = data?.map((e) => ChatUser.fromJson(e.data())).toList() ?? []; return Row( children: [ //back button IconButton( onPressed: () => Navigator.pop(context), icon: const Icon(Icons.arrow_back, color: Colors.black54)), //user profile picture ClipRRect( borderRadius: BorderRadius.circular(mq.height * .03), child: CachedNetworkImage( width: mq.height * .05, height: mq.height * .05, fit: BoxFit.cover, imageUrl: list.isNotEmpty ? list[0].image : widget.user.image, errorWidget: (context, url, error) => const CircleAvatar( child: Icon(CupertinoIcons.person)), ), ), //for adding some space const SizedBox(width: 10), //user name & last seen time Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ //user name Text(list.isNotEmpty ? list[0].name : widget.user.name, style: const TextStyle( fontSize: 16, color: Colors.black87, fontWeight: FontWeight.w500)), //for adding some space const SizedBox(height: 2), //last seen time of user Text( list.isNotEmpty ? list[0].isOnline ? 'Online' : MyDateUtil.getLastActiveTime( context: context, lastActive: list[0].lastActive) : MyDateUtil.getLastActiveTime( context: context, lastActive: widget.user.lastActive), style: const TextStyle( fontSize: 13, color: Colors.black54)), ], ) ], ); })), ); } // bottom chat input field Widget _chatInput() { return Padding( padding: EdgeInsets.symmetric( vertical: mq.height * .01, horizontal: mq.width * .025), child: Row( children: [ //input field & buttons Expanded( child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15)), child: Row( children: [ //emoji button IconButton( onPressed: () { FocusScope.of(context).unfocus(); setState(() => _showEmoji = !_showEmoji); }, icon: const Icon(Icons.emoji_emotions, color: Colors.blueAccent, size: 25)), Expanded( child: TextField( controller: _textController, keyboardType: TextInputType.multiline, maxLines: null, onTap: () { if (_showEmoji) setState(() => _showEmoji = !_showEmoji); }, decoration: const InputDecoration( hintText: 'Type Something...', hintStyle: TextStyle(color: Colors.blueAccent), border: InputBorder.none), )), //pick image from gallery button IconButton( onPressed: () async { final ImagePicker picker = ImagePicker(); // Picking multiple images final List<XFile> images = await picker.pickMultiImage(imageQuality: 70); // uploading & sending image one by one for (var i in images) { log('Image Path: ${i.path}'); setState(() => _isUploading = true); await APIs.sendChatImage(widget.user, File(i.path)); setState(() => _isUploading = false); } }, icon: const Icon(Icons.image, color: Colors.blueAccent, size: 26)), //take image from camera button IconButton( onPressed: () async { final ImagePicker picker = ImagePicker(); // Pick an image final XFile? image = await picker.pickImage( source: ImageSource.camera, imageQuality: 70); if (image != null) { log('Image Path: ${image.path}'); setState(() => _isUploading = true); await APIs.sendChatImage( widget.user, File(image.path)); setState(() => _isUploading = false); } }, icon: const Icon(Icons.camera_alt_rounded, color: Colors.blueAccent, size: 26)), //adding some space SizedBox(width: mq.width * .02), ], ), ), ), //send message button MaterialButton( onPressed: () { if (_textController.text.isNotEmpty) { if (_list.isEmpty) { //on first message (add user to my_user collection of chat user) APIs.sendFirstMessage( widget.user, _textController.text, Type.text); } else { //simply send message APIs.sendMessage( widget.user, _textController.text, Type.text); } _textController.text = ''; } }, minWidth: 0, padding: const EdgeInsets.only(top: 10, bottom: 10, right: 5, left: 10), shape: const CircleBorder(), color: Colors.green, child: const Icon(Icons.send, color: Colors.white, size: 28), ) ], ), ); } }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/screens/splash_screen.dart
import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../main.dart'; import '../api/apis.dart'; import 'auth/login_screen.dart'; import 'home_screen.dart'; //splash screen 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: 2), () { //exit full-screen SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle( systemNavigationBarColor: Colors.white, statusBarColor: Colors.white)); if (APIs.auth.currentUser != null) { log('\nUser: ${APIs.auth.currentUser}'); //navigate to home screen Navigator.pushReplacement( context, MaterialPageRoute(builder: (_) => const HomeScreen())); } else { //navigate to login screen Navigator.pushReplacement( context, MaterialPageRoute(builder: (_) => const LoginScreen())); } }); } @override Widget build(BuildContext context) { //initializing media query (for getting device screen size) mq = MediaQuery.of(context).size; return Scaffold( //body body: Stack(children: [ //app logo Positioned( top: mq.height * .15, right: mq.width * .25, width: mq.width * .5, child: Image.asset('images/icon.png')), //google login button Positioned( bottom: mq.height * .15, width: mq.width, child: const Text('MADE IN INDIA WITH ❤️', textAlign: TextAlign.center, style: TextStyle( fontSize: 16, color: Colors.black87, letterSpacing: .5))), ]), ); } }
0
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/screens
mirrored_repositories/ApnaChat-Realtime-Chat-App-In-Flutter-Firebase/lib/screens/auth/login_screen.dart
import 'dart:developer'; import 'dart:io'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:google_sign_in/google_sign_in.dart'; import '../../api/apis.dart'; import '../../helper/dialogs.dart'; import '../../main.dart'; import '../home_screen.dart'; //login screen -- implements google sign in or sign up feature for app class LoginScreen extends StatefulWidget { const LoginScreen({super.key}); @override State<LoginScreen> createState() => _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { bool _isAnimate = false; @override void initState() { super.initState(); //for auto triggering animation Future.delayed(const Duration(milliseconds: 500), () { setState(() => _isAnimate = true); }); } // handles google login button click _handleGoogleBtnClick() { //for showing progress bar Dialogs.showProgressBar(context); _signInWithGoogle().then((user) async { //for hiding progress bar Navigator.pop(context); if (user != null) { log('\nUser: ${user.user}'); log('\nUserAdditionalInfo: ${user.additionalUserInfo}'); if (await APIs.userExists() && mounted) { Navigator.pushReplacement( context, MaterialPageRoute(builder: (_) => const HomeScreen())); } else { await APIs.createUser().then((value) { Navigator.pushReplacement( context, MaterialPageRoute(builder: (_) => const HomeScreen())); }); } } }); } Future<UserCredential?> _signInWithGoogle() async { try { await InternetAddress.lookup('google.com'); // Trigger the authentication flow final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn(); // Obtain the auth details from the request final GoogleSignInAuthentication? googleAuth = await googleUser?.authentication; // Create a new credential final credential = GoogleAuthProvider.credential( accessToken: googleAuth?.accessToken, idToken: googleAuth?.idToken, ); // Once signed in, return the UserCredential return await APIs.auth.signInWithCredential(credential); } catch (e) { log('\n_signInWithGoogle: $e'); if (mounted) { Dialogs.showSnackbar(context, 'Something Went Wrong (Check Internet!)'); } return null; } } //sign out function // _signOut() async { // await FirebaseAuth.instance.signOut(); // await GoogleSignIn().signOut(); // } @override Widget build(BuildContext context) { //initializing media query (for getting device screen size) // mq = MediaQuery.of(context).size; return Scaffold( //app bar appBar: AppBar( automaticallyImplyLeading: false, title: const Text('Welcome to We Chat'), ), //body body: Stack(children: [ //app logo AnimatedPositioned( top: mq.height * .15, right: _isAnimate ? mq.width * .25 : -mq.width * .5, width: mq.width * .5, duration: const Duration(seconds: 1), child: Image.asset('images/icon.png')), //google login button Positioned( bottom: mq.height * .15, left: mq.width * .05, width: mq.width * .9, height: mq.height * .06, child: ElevatedButton.icon( style: ElevatedButton.styleFrom( backgroundColor: const Color.fromARGB(255, 223, 255, 187), shape: const StadiumBorder(), elevation: 1), // on tap onPressed: _handleGoogleBtnClick, //google icon icon: Image.asset('images/google.png', height: mq.height * .03), //login with google label label: RichText( text: const TextSpan( style: TextStyle(color: Colors.black, fontSize: 16), children: [ TextSpan(text: 'Login with '), TextSpan( text: 'Google', style: TextStyle(fontWeight: FontWeight.w500)), ]), ))), ]), ); } }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/app.dart
import 'dart:async'; import 'package:example/pages/choose_user_page.dart'; import 'package:example/pages/splash_screen.dart'; import 'package:example/routes/app_routes.dart'; import 'package:example/routes/routes.dart'; import 'package:example/state/init_data.dart'; import 'package:example/utils/app_config.dart'; import 'package:example/utils/local_notification_observer.dart'; import 'package:example/utils/localizations.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:go_router/go_router.dart'; import 'package:provider/provider.dart'; import 'package:sentry_flutter/sentry_flutter.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import 'package:stream_chat_localizations/stream_chat_localizations.dart'; import 'package:stream_chat_persistence/stream_chat_persistence.dart'; import 'package:streaming_shared_preferences/streaming_shared_preferences.dart'; import 'firebase_options.dart'; /// Constructs callback for background notification handling. /// /// Will be invoked from another Isolate, that's why it's required to /// initialize everything again: /// - Firebase /// - StreamChatClient /// - StreamChatPersistenceClient @pragma('vm:entry-point') Future<void> _onFirebaseBackgroundMessage(RemoteMessage message) async { debugPrint('[onBackgroundMessage] #firebase; message: ${message.toMap()}'); final data = message.data; // ensure that Push Notification was sent by Stream. if (data['sender'] != 'stream.chat') { return; } // ensure that Push Notification relates to a new message event. if (data['type'] != 'message.new') { return; } // If you're going to use Firebase services in the background, make sure // you call `initializeApp` before using Firebase services. await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); // read existing user info. String? apiKey, userId, token; if (!kIsWeb) { const secureStorage = FlutterSecureStorage(); apiKey = await secureStorage.read(key: kStreamApiKey); userId = await secureStorage.read(key: kStreamUserId); token = await secureStorage.read(key: kStreamToken); } if (userId == null || token == null) { return; } final chatClient = buildStreamChatClient(apiKey ?? kDefaultStreamApiKey); try { await chatClient.connectUser( User(id: userId), token, // do not open WS connection connectWebSocket: false, ); // initialize persistence with current user if (!chatPersistentClient.isConnected) { await chatPersistentClient.connect(userId); } final messageId = data['id']; final cid = data['cid']; // pre-cache the new message using client and persistence. final response = await chatClient.getMessage(messageId); await chatPersistentClient.updateMessages(cid, [response.message]); } catch (e, stk) { debugPrint('[onBackgroundMessage] #firebase; failed: $e; $stk'); } } final chatPersistentClient = StreamChatPersistenceClient( logLevel: Level.SEVERE, connectionMode: ConnectionMode.regular, ); void _sampleAppLogHandler(LogRecord record) async { if (kDebugMode) StreamChatClient.defaultLogHandler(record); // report errors to sentry.io if (record.error != null || record.stackTrace != null) { await Sentry.captureException( record.error, stackTrace: record.stackTrace, ); } } StreamChatClient buildStreamChatClient(String apiKey) { late Level logLevel; if (kDebugMode) { logLevel = Level.INFO; } else { logLevel = Level.SEVERE; } return StreamChatClient( apiKey, logLevel: logLevel, logHandlerFunction: _sampleAppLogHandler, )..chatPersistenceClient = chatPersistentClient; } class StreamChatSampleApp extends StatefulWidget { const StreamChatSampleApp({super.key}); @override State<StreamChatSampleApp> createState() => _StreamChatSampleAppState(); } class _StreamChatSampleAppState extends State<StreamChatSampleApp> with SplashScreenStateMixin, TickerProviderStateMixin { final InitNotifier _initNotifier = InitNotifier(); final firebaseSubscriptions = <StreamSubscription<dynamic>>[]; StreamSubscription<String?>? userIdSubscription; Future<InitData> _initConnection() async { String? apiKey, userId, token; if (!kIsWeb) { const secureStorage = FlutterSecureStorage(); apiKey = await secureStorage.read(key: kStreamApiKey); userId = await secureStorage.read(key: kStreamUserId); token = await secureStorage.read(key: kStreamToken); } final client = buildStreamChatClient(apiKey ?? kDefaultStreamApiKey); if (userId != null && token != null) { await client.connectUser( User(id: userId), token, ); } final prefs = await StreamingSharedPreferences.instance; return InitData(client, prefs); } Future<void> _initFirebaseMessaging(StreamChatClient client) async { userIdSubscription?.cancel(); userIdSubscription = client.state.currentUserStream .map((it) => it?.id) .distinct() .listen((userId) async { // User logged in if (userId != null) { // Requests notification permission. await FirebaseMessaging.instance.requestPermission(); // Sets callback for background messages. FirebaseMessaging.onBackgroundMessage(_onFirebaseBackgroundMessage); // Sets callback for the notification click event. firebaseSubscriptions.add(FirebaseMessaging.onMessageOpenedApp .listen(_onFirebaseMessageOpenedApp(client))); // Sets callback for foreground messages firebaseSubscriptions.add(FirebaseMessaging.onMessage .listen(_onFirebaseForegroundMessage(client))); // Sets callback for the token refresh event. firebaseSubscriptions.add(FirebaseMessaging.instance.onTokenRefresh .listen(_onFirebaseTokenRefresh(client))); final token = await FirebaseMessaging.instance.getToken(); if (token != null) { // add Token to Stream await client.addDevice(token, PushProvider.firebase); } } // User logged out else { firebaseSubscriptions.cancelAll(); final token = await FirebaseMessaging.instance.getToken(); if (token != null) { // remove token from Stream await client.removeDevice(token); } } }); } /// Constructs callback for notification click event. OnRemoteMessage _onFirebaseMessageOpenedApp(StreamChatClient client) { return (message) async { debugPrint('[onMessageOpenedApp] #firebase; message: ${message.toMap()}'); // This callback is getting invoked when the user clicks // on the notification in case if notification was shown by OS. final channelType = (message.data['channel_type'] as String?) ?? ''; final channelId = (message.data['channel_id'] as String?) ?? ''; final channelCid = (message.data['cid'] as String?) ?? ''; var channel = client.state.channels[channelCid]; if (channel == null) { channel = client.channel( channelType, id: channelId, ); await channel.watch(); } // Navigates to Channel page, which is associated with the notification. GoRouter.of(_navigatorKey.currentContext!).pushNamed( Routes.CHANNEL_PAGE.name, pathParameters: Routes.CHANNEL_PAGE.params(channel), ); }; } /// Constructs callback for foreground notification handling. OnRemoteMessage _onFirebaseForegroundMessage(StreamChatClient client) { return (message) async { debugPrint( '[onForegroundMessage] #firebase; message: ${message.toMap()}'); }; } /// Constructs callback for notification refresh event. Future<void> Function(String) _onFirebaseTokenRefresh( StreamChatClient client, ) { return (token) async { debugPrint('[onTokenRefresh] #firebase; token: $token'); // This callback is getting invoked when the token got refreshed. await client.addDevice(token, PushProvider.firebase); }; } @override void initState() { final timeOfStartMs = DateTime.now().millisecondsSinceEpoch; _initConnection().then( (initData) { setState(() { _initNotifier.initData = initData; }); final now = DateTime.now().millisecondsSinceEpoch; if (now - timeOfStartMs > 1500) { SchedulerBinding.instance.addPostFrameCallback((timeStamp) { forwardAnimations(); }); } else { Future.delayed(const Duration(milliseconds: 1500)).then((value) { forwardAnimations(); }); } _initFirebaseMessaging(initData.client); }, ); super.initState(); } @override void dispose() { super.dispose(); userIdSubscription?.cancel(); firebaseSubscriptions.cancelAll(); } final GlobalKey<NavigatorState> _navigatorKey = GlobalKey(); LocalNotificationObserver? localNotificationObserver; /// Conditionally sets up the router and adding an observer for the /// current chat client. GoRouter _setupRouter() { if (localNotificationObserver != null) { localNotificationObserver!.dispose(); } localNotificationObserver = LocalNotificationObserver( _initNotifier.initData!.client, _navigatorKey); return GoRouter( refreshListenable: _initNotifier, initialLocation: Routes.CHANNEL_LIST_PAGE.path, navigatorKey: _navigatorKey, observers: [localNotificationObserver!], redirect: (context, state) { final loggedIn = _initNotifier.initData?.client.state.currentUser != null; final loggingIn = state.matchedLocation == Routes.CHOOSE_USER.path || state.matchedLocation == Routes.ADVANCED_OPTIONS.path; if (!loggedIn) { return loggingIn ? null : Routes.CHOOSE_USER.path; } // if the user is logged in but still on the login page, send them to // the home page if (loggedIn && state.matchedLocation == Routes.CHOOSE_USER.path) { return Routes.CHANNEL_LIST_PAGE.path; } return null; }, routes: appRoutes, ); } @override Widget build(BuildContext context) { return Stack( alignment: Alignment.center, children: [ if (_initNotifier.initData != null) ChangeNotifierProvider.value( value: _initNotifier, builder: (context, child) => Builder( builder: (context) { context.watch<InitNotifier>(); // rebuild on change return PreferenceBuilder<int>( preference: _initNotifier.initData!.preferences.getInt( 'theme', defaultValue: 0, ), builder: (context, snapshot) => MaterialApp.router( theme: ThemeData.light(), darkTheme: ThemeData.dark(), themeMode: const { -1: ThemeMode.dark, 0: ThemeMode.system, 1: ThemeMode.light, }[snapshot], supportedLocales: const [ Locale('en'), Locale('it'), ], localizationsDelegates: const [ AppLocalizationsDelegate(), GlobalStreamChatLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, ], builder: (context, child) => StreamChat( client: _initNotifier.initData!.client, child: child, ), routerConfig: _setupRouter(), ), ); }, ), ), if (!animationCompleted) buildAnimation(), ], ); } } typedef OnRemoteMessage = Future<void> Function(RemoteMessage); extension on List<StreamSubscription> { void cancelAll() { for (final subscription in this) { unawaited(subscription.cancel()); } clear(); } }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/firebase_options.dart
// File generated by FlutterFire CLI. // ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; import 'package:flutter/foundation.dart' show defaultTargetPlatform, kIsWeb, TargetPlatform; /// Default [FirebaseOptions] for use with your Firebase apps. /// /// Example: /// ```dart /// import 'firebase_options.dart'; /// // ... /// await Firebase.initializeApp( /// options: DefaultFirebaseOptions.currentPlatform, /// ); /// ``` class DefaultFirebaseOptions { static FirebaseOptions get currentPlatform { if (kIsWeb) { return web; } switch (defaultTargetPlatform) { case TargetPlatform.android: return android; case TargetPlatform.iOS: return ios; case TargetPlatform.macOS: return macos; case TargetPlatform.windows: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for windows - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); case TargetPlatform.linux: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for linux - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); default: throw UnsupportedError( 'DefaultFirebaseOptions are not supported for this platform.', ); } } static const FirebaseOptions web = FirebaseOptions( apiKey: 'AIzaSyA4Obi2paSQ1IZZ88OcMC98DJlpV16DAzE', appId: '1:674907137625:web:a4b97e5d080ec165d7f348', messagingSenderId: '674907137625', projectId: 'stream-chat-internal', authDomain: 'stream-chat-internal.firebaseapp.com', databaseURL: 'https://stream-chat-internal.firebaseio.com', storageBucket: 'stream-chat-internal.appspot.com', measurementId: 'G-F2RV4P139L', ); static const FirebaseOptions android = FirebaseOptions( apiKey: 'AIzaSyBArS4RH7lUn3xbD-jhzWl5hVWZhliRgY0', appId: '1:674907137625:android:e55b74fd5747e39ad7f348', messagingSenderId: '674907137625', projectId: 'stream-chat-internal', databaseURL: 'https://stream-chat-internal.firebaseio.com', storageBucket: 'stream-chat-internal.appspot.com', ); static const FirebaseOptions ios = FirebaseOptions( apiKey: 'AIzaSyBTAsaKFUPLAJqfsLiz0yPUVzwrgJkOwSE', appId: '1:674907137625:ios:cafb9fb076a453c4d7f348', messagingSenderId: '674907137625', projectId: 'stream-chat-internal', databaseURL: 'https://stream-chat-internal.firebaseio.com', storageBucket: 'stream-chat-internal.appspot.com', androidClientId: '674907137625-2scfo9a5cs074dced5vhm712ej6hhtpm.apps.googleusercontent.com', iosClientId: '674907137625-flarfn9cefu4lermgpbc4b8rm8l15ian.apps.googleusercontent.com', iosBundleId: 'io.getstream.flutter', ); static const FirebaseOptions macos = FirebaseOptions( apiKey: 'AIzaSyBTAsaKFUPLAJqfsLiz0yPUVzwrgJkOwSE', appId: '1:674907137625:ios:c719c700198c28b1d7f348', messagingSenderId: '674907137625', projectId: 'stream-chat-internal', databaseURL: 'https://stream-chat-internal.firebaseio.com', storageBucket: 'stream-chat-internal.appspot.com', androidClientId: '674907137625-2scfo9a5cs074dced5vhm712ej6hhtpm.apps.googleusercontent.com', iosClientId: '674907137625-p3msks3snq0h22l7ekpqcf0frr0vt8mg.apps.googleusercontent.com', iosBundleId: 'io.getstream.streamChatV1', ); }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/main.dart
import 'dart:async'; import 'package:example/app.dart'; import 'package:example/utils/app_config.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:sentry_flutter/sentry_flutter.dart'; import 'firebase_options.dart'; Future<void> main() async { /// Captures errors reported by the Flutter framework. FlutterError.onError = (FlutterErrorDetails details) { if (kDebugMode) { // In development mode, simply print to console. FlutterError.dumpErrorToConsole(details); } else { // In production mode, report to the application zone to report to sentry. Zone.current.handleUncaughtError(details.exception, details.stack!); } }; /// Captures errors reported by the native environment, including native iOS /// and Android code. Future<void> reportError(dynamic error, StackTrace stackTrace) async { // Print the exception to the console. if (kDebugMode) { // Print the full stacktrace in debug mode. print(stackTrace); return; } else { // Send the Exception and Stacktrace to sentry in Production mode. await Sentry.captureException(error, stackTrace: stackTrace); } } /// Runs the app wrapped in a [Zone] that captures errors and sends them to /// sentry. runZonedGuarded( () async { WidgetsFlutterBinding.ensureInitialized(); // Wait for Sentry and Firebase to initialize before running the app. await Future.wait([ SentryFlutter.init((options) => options.dsn = sentryDsn), Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform), ]); runApp(const StreamChatSampleApp()); }, reportError, ); }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/widgets/channel_list.dart
import 'dart:async'; import 'package:example/utils/localizations.dart'; import 'package:example/routes/routes.dart'; import 'package:example/widgets/search_text_field.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:go_router/go_router.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import 'package:flutter_slidable/flutter_slidable.dart'; import '../pages/chat_info_screen.dart'; import '../pages/group_info_screen.dart'; class ChannelList extends StatefulWidget { const ChannelList({super.key}); @override State<ChannelList> createState() => _ChannelList(); } class _ChannelList extends State<ChannelList> { final ScrollController _scrollController = ScrollController(); late final StreamMessageSearchListController _messageSearchListController = StreamMessageSearchListController( client: StreamChat.of(context).client, filter: Filter.in_('members', [StreamChat.of(context).currentUser!.id]), limit: 5, searchQuery: '', sort: [ const SortOption( 'created_at', direction: SortOption.ASC, ), ], ); late final TextEditingController _controller = TextEditingController() ..addListener(_channelQueryListener); bool _isSearchActive = false; Timer? _debounce; void _channelQueryListener() { if (_debounce?.isActive ?? false) _debounce!.cancel(); _debounce = Timer(const Duration(milliseconds: 350), () { if (mounted) { _messageSearchListController.searchQuery = _controller.text; setState(() { _isSearchActive = _controller.text.isNotEmpty; }); if (_isSearchActive) _messageSearchListController.doInitialLoad(); } }); } late final _channelListController = StreamChannelListController( client: StreamChat.of(context).client, filter: Filter.in_( 'members', [StreamChat.of(context).currentUser!.id], ), presence: true, limit: 30, ); @override void dispose() { _controller.removeListener(_channelQueryListener); _controller.dispose(); _scrollController.dispose(); _channelListController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { if (_isSearchActive) { _controller.clear(); setState(() => _isSearchActive = false); return false; } return true; }, child: NotificationListener<ScrollUpdateNotification>( onNotification: (ScrollNotification scrollInfo) { if (_scrollController.position.userScrollDirection == ScrollDirection.reverse) { FocusScope.of(context).unfocus(); } return true; }, child: NestedScrollView( controller: _scrollController, floatHeaderSlivers: false, headerSliverBuilder: (_, __) => [ SliverToBoxAdapter( child: SearchTextField( controller: _controller, showCloseButton: _isSearchActive, hintText: AppLocalizations.of(context).search, ), ), ], body: _isSearchActive ? StreamMessageSearchListView( controller: _messageSearchListController, emptyBuilder: (_) { return LayoutBuilder( builder: (context, viewportConstraints) { return SingleChildScrollView( physics: const AlwaysScrollableScrollPhysics(), child: ConstrainedBox( constraints: BoxConstraints( minHeight: viewportConstraints.maxHeight, ), child: Center( child: Column( children: [ Padding( padding: const EdgeInsets.all(24), child: StreamSvgIcon.search( size: 96, color: Colors.grey, ), ), Text( AppLocalizations.of(context).noResults, ), ], ), ), ), ); }, ); }, itemBuilder: ( context, messageResponses, index, defaultWidget, ) { return defaultWidget.copyWith( onTap: () async { final messageResponse = messageResponses[index]; FocusScope.of(context).requestFocus(FocusNode()); final client = StreamChat.of(context).client; final router = GoRouter.of(context); final message = messageResponse.message; final channel = client.channel( messageResponse.channel!.type, id: messageResponse.channel!.id, ); if (channel.state == null) { await channel.watch(); } router.pushNamed( Routes.CHANNEL_PAGE.name, pathParameters: Routes.CHANNEL_PAGE.params(channel), queryParameters: Routes.CHANNEL_PAGE.queryParams(message), ); }, ); }, ) : SlidableAutoCloseBehavior( closeWhenOpened: true, child: RefreshIndicator( onRefresh: _channelListController.refresh, child: StreamChannelListView( controller: _channelListController, itemBuilder: (context, channels, index, defaultWidget) { final chatTheme = StreamChatTheme.of(context); final backgroundColor = chatTheme.colorTheme.inputBg; final channel = channels[index]; final canDeleteChannel = channel.ownCapabilities .contains(PermissionType.deleteChannel); return Slidable( groupTag: 'channels-actions', endActionPane: ActionPane( extentRatio: canDeleteChannel ? 0.40 : 0.20, motion: const BehindMotion(), children: [ CustomSlidableAction( backgroundColor: backgroundColor, onPressed: (_) { showChannelInfoModalBottomSheet( context: context, channel: channel, onViewInfoTap: () { Navigator.pop(context); Navigator.push( context, MaterialPageRoute( builder: (context) { final isOneToOne = channel.memberCount == 2 && channel.isDistinct; return StreamChannel( channel: channel, child: isOneToOne ? ChatInfoScreen( messageTheme: chatTheme .ownMessageTheme, user: channel .state!.members .where((m) => m.userId != channel .client .state .currentUser! .id) .first .user, ) : GroupInfoScreen( messageTheme: chatTheme .ownMessageTheme, ), ); }, ), ); }, ); }, child: const Icon(Icons.more_horiz), ), if (canDeleteChannel) CustomSlidableAction( backgroundColor: backgroundColor, child: StreamSvgIcon.delete( color: chatTheme.colorTheme.accentError, ), onPressed: (_) async { final res = await showConfirmationBottomSheet( context, title: 'Delete Conversation', question: 'Are you sure you want to delete this conversation?', okText: 'Delete', cancelText: 'Cancel', icon: StreamSvgIcon.delete( color: chatTheme.colorTheme.accentError, ), ); if (res == true) { await _channelListController .deleteChannel(channel); } }, ), ], ), child: defaultWidget, ); }, onChannelTap: (channel) { GoRouter.of(context).pushNamed( Routes.CHANNEL_PAGE.name, pathParameters: Routes.CHANNEL_PAGE.params(channel), ); }, emptyBuilder: (_) { return Center( child: Padding( padding: const EdgeInsets.all(8), child: StreamScrollViewEmptyWidget( emptyIcon: StreamSvgIcon.message( size: 148, color: StreamChatTheme.of(context) .colorTheme .disabled, ), emptyTitle: TextButton( onPressed: () { GoRouter.of(context) .pushNamed(Routes.NEW_CHAT.name); }, child: Text( 'Start a chat', style: StreamChatTheme.of(context) .textTheme .bodyBold .copyWith( color: StreamChatTheme.of(context) .colorTheme .accentPrimary, ), ), ), ), ), ); }, ), ), ), ), ), ); } }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/widgets/stream_version.dart
import 'package:example/utils/localizations.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:yaml/yaml.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class StreamVersion extends StatelessWidget { const StreamVersion({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.symmetric(vertical: 16), alignment: Alignment.bottomCenter, child: FutureBuilder<String>( future: rootBundle.loadString('pubspec.lock'), builder: (context, snapshot) { if (!snapshot.hasData) { return const SizedBox(); } final pubspec = snapshot.data!; final yaml = loadYaml(pubspec); final streamChatDep = yaml['packages']['stream_chat_flutter']['version']; return Text( '${AppLocalizations.of(context).streamSDK} v $streamChatDep', style: TextStyle( fontSize: 14, color: StreamChatTheme.of(context).colorTheme.disabled, ), ); }, ), ); } }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/widgets/chips_input_text_field.dart
import 'package:example/utils/localizations.dart'; import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; typedef ChipBuilder<T> = Widget Function(BuildContext context, T chip); typedef OnChipAdded<T> = void Function(T chip); typedef OnChipRemoved<T> = void Function(T chip); class ChipsInputTextField<T> extends StatefulWidget { final TextEditingController? controller; final FocusNode? focusNode; final ValueChanged<String>? onInputChanged; final ChipBuilder<T> chipBuilder; final OnChipAdded<T>? onChipAdded; final OnChipRemoved<T>? onChipRemoved; final String hint; const ChipsInputTextField({ Key? key, required this.chipBuilder, required this.controller, this.onInputChanged, this.focusNode, this.onChipAdded, this.onChipRemoved, this.hint = 'Type a name', }) : super(key: key); @override ChipInputTextFieldState<T> createState() => ChipInputTextFieldState<T>(); } class ChipInputTextFieldState<T> extends State<ChipsInputTextField<T>> { final _chips = <T>{}; bool _pauseItemAddition = false; void addItem(T item) { setState(() => _chips.add(item)); if (widget.onChipAdded != null) widget.onChipAdded!(item); } void removeItem(T item) { setState(() { _chips.remove(item); if (_chips.isEmpty) resumeItemAddition(); }); if (widget.onChipRemoved != null) widget.onChipRemoved!(item); } void pauseItemAddition() { if (!_pauseItemAddition) { setState(() => _pauseItemAddition = true); } widget.focusNode?.unfocus(); } void resumeItemAddition() { if (_pauseItemAddition) { setState(() => _pauseItemAddition = false); } widget.focusNode?.requestFocus(); } @override Widget build(BuildContext context) { return GestureDetector( onTap: _pauseItemAddition ? resumeItemAddition : null, child: Material( elevation: 1, color: StreamChatTheme.of(context).colorTheme.barsBg, child: Padding( padding: const EdgeInsets.fromLTRB(16, 16, 16, 16), child: Row( children: [ Padding( padding: const EdgeInsets.symmetric(vertical: 4.0), child: Text( '${AppLocalizations.of(context).to.toUpperCase()}:', style: StreamChatTheme.of(context) .textTheme .footnote .copyWith( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(.5)), ), ), const SizedBox(width: 12), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Wrap( spacing: 8.0, runSpacing: 4.0, children: _chips.map((item) { return widget.chipBuilder(context, item); }).toList(), ), if (!_pauseItemAddition) TextField( controller: widget.controller, onChanged: widget.onInputChanged, focusNode: widget.focusNode, decoration: InputDecoration( isDense: true, border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none, contentPadding: const EdgeInsets.only(top: 4.0), hintText: widget.hint, hintStyle: StreamChatTheme.of(context) .textTheme .body .copyWith( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(.5)), ), ), ], ), ), const SizedBox(width: 12), Align( alignment: Alignment.bottomCenter, child: IconButton( icon: _chips.isEmpty ? StreamSvgIcon.user( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5), size: 24, ) : StreamSvgIcon.userAdd( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5), size: 24, ), onPressed: resumeItemAddition, alignment: Alignment.topRight, visualDensity: VisualDensity.compact, padding: const EdgeInsets.all(0), splashRadius: 24, constraints: const BoxConstraints.tightFor( height: 24, width: 24, ), ), ), ], ), ), ), ); } }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/widgets/search_text_field.dart
import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class SearchTextField extends StatelessWidget { final TextEditingController? controller; final ValueChanged<String>? onChanged; final String hintText; final VoidCallback? onTap; final bool showCloseButton; const SearchTextField({ Key? key, required this.controller, this.onChanged, this.onTap, this.hintText = 'Search', this.showCloseButton = true, }) : super(key: key); @override Widget build(BuildContext context) { return Container( height: 36, decoration: BoxDecoration( color: StreamChatTheme.of(context).colorTheme.barsBg, border: Border.all( color: StreamChatTheme.of(context).colorTheme.borders, ), borderRadius: BorderRadius.circular(24), ), margin: const EdgeInsets.symmetric( vertical: 8, horizontal: 8, ), child: Row( children: [ Expanded( child: TextField( onTap: onTap, controller: controller, onChanged: onChanged, decoration: InputDecoration( prefixText: ' ', prefixIconConstraints: BoxConstraints.tight(const Size(40, 24)), prefixIcon: Padding( padding: const EdgeInsets.only( left: 8, right: 8, ), child: StreamSvgIcon.search( color: StreamChatTheme.of(context).colorTheme.textHighEmphasis, size: 24, ), ), hintText: hintText, hintStyle: StreamChatTheme.of(context).textTheme.body.copyWith( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(.5)), contentPadding: const EdgeInsets.all(0), border: OutlineInputBorder( borderSide: BorderSide.none, borderRadius: BorderRadius.circular(24), ), ), ), ), if (showCloseButton) Material( color: Colors.transparent, child: IconButton( padding: const EdgeInsets.all(0), icon: StreamSvgIcon.closeSmall( color: Colors.grey, ), splashRadius: 24, onPressed: () { if (controller!.text.isNotEmpty) { Future.microtask( () => [ controller!.clear(), if (onChanged != null) onChanged!(''), ], ); } }, ), ), ], ), ); } }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/routes/app_routes.dart
import 'package:collection/collection.dart'; import 'package:example/pages/advanced_options_page.dart'; import 'package:example/pages/channel_list_page.dart'; import 'package:example/pages/channel_page.dart'; import 'package:example/pages/chat_info_screen.dart'; import 'package:example/pages/group_chat_details_screen.dart'; import 'package:example/pages/group_info_screen.dart'; import 'package:example/pages/new_chat_screen.dart'; import 'package:example/pages/new_group_chat_screen.dart'; import 'package:example/pages/thread_page.dart'; import 'package:example/routes/routes.dart'; import 'package:example/state/new_group_chat_state.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import '../pages/choose_user_page.dart'; final appRoutes = [ GoRoute( name: Routes.CHANNEL_LIST_PAGE.name, path: Routes.CHANNEL_LIST_PAGE.path, builder: (BuildContext context, GoRouterState state) => const ChannelListPage(), routes: [ GoRoute( name: Routes.CHANNEL_PAGE.name, path: Routes.CHANNEL_PAGE.path, builder: (context, state) { final channel = StreamChat.of(context) .client .state .channels[state.pathParameters['cid']]; final messageId = state.uri.queryParameters['mid']; final parentId = state.uri.queryParameters['pid']; Message? parentMessage; if (parentId != null) { parentMessage = channel?.state!.messages .firstWhereOrNull((it) => it.id == parentId); } return StreamChannel( channel: channel!, initialMessageId: messageId, child: Builder( builder: (context) { return (parentMessage != null) ? ThreadPage(parent: parentMessage) : ChannelPage( highlightInitialMessage: messageId != null, ); }, ), ); }, routes: [ GoRoute( name: Routes.CHAT_INFO_SCREEN.name, path: Routes.CHAT_INFO_SCREEN.path, builder: (BuildContext context, GoRouterState state) { final channel = StreamChat.of(context) .client .state .channels[state.pathParameters['cid']]; return StreamChannel( channel: channel!, child: ChatInfoScreen( user: state.extra as User?, messageTheme: StreamChatTheme.of(context).ownMessageTheme, ), ); }, ), GoRoute( name: Routes.GROUP_INFO_SCREEN.name, path: Routes.GROUP_INFO_SCREEN.path, builder: (BuildContext context, GoRouterState state) { final channel = StreamChat.of(context) .client .state .channels[state.pathParameters['cid']]; return StreamChannel( channel: channel!, child: GroupInfoScreen( messageTheme: StreamChatTheme.of(context).ownMessageTheme, ), ); }, ), ], ), ], ), GoRoute( name: Routes.NEW_CHAT.name, path: Routes.NEW_CHAT.path, builder: (BuildContext context, GoRouterState state) { return const NewChatScreen(); }, ), GoRoute( name: Routes.NEW_GROUP_CHAT.name, path: Routes.NEW_GROUP_CHAT.path, builder: (BuildContext context, GoRouterState state) { return const NewGroupChatScreen(); }, ), GoRoute( name: Routes.NEW_GROUP_CHAT_DETAILS.name, path: Routes.NEW_GROUP_CHAT_DETAILS.path, builder: (BuildContext context, GoRouterState state) { final groupChatState = state.extra as NewGroupChatState; return GroupChatDetailsScreen(groupChatState: groupChatState); }, ), GoRoute( name: Routes.CHOOSE_USER.name, path: Routes.CHOOSE_USER.path, builder: (BuildContext context, GoRouterState state) => const ChooseUserPage(), ), GoRoute( name: Routes.ADVANCED_OPTIONS.name, path: Routes.ADVANCED_OPTIONS.path, builder: (BuildContext context, GoRouterState state) => const AdvancedOptionsPage(), ), ];
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/routes/routes.dart
// ignore_for_file: constant_identifier_names import 'package:stream_chat_flutter/stream_chat_flutter.dart'; /// Application routes abstract class Routes { static const RouteConfig CHOOSE_USER = RouteConfig(name: 'choose_user', path: '/users'); static const RouteConfig ADVANCED_OPTIONS = RouteConfig(name: 'advanced_options', path: '/options'); static const ChannelRouteConfig CHANNEL_PAGE = ChannelRouteConfig(name: 'channel_page', path: 'channel/:cid'); static const RouteConfig NEW_CHAT = RouteConfig(name: 'new_chat', path: '/new_chat'); static const RouteConfig NEW_GROUP_CHAT = RouteConfig(name: 'new_group_chat', path: '/new_group_chat'); static const RouteConfig NEW_GROUP_CHAT_DETAILS = RouteConfig( name: 'new_group_chat_details', path: '/new_group_chat_details'); static const ChannelRouteConfig CHAT_INFO_SCREEN = ChannelRouteConfig(name: 'chat_info_screen', path: 'chat_info_screen'); static const ChannelRouteConfig GROUP_INFO_SCREEN = ChannelRouteConfig(name: 'group_info_screen', path: 'group_info_screen'); static const RouteConfig CHANNEL_LIST_PAGE = RouteConfig(name: 'channel_list_page', path: '/channels'); } class RouteConfig { final String name; final String path; const RouteConfig({required this.name, required this.path}); } class ChannelRouteConfig extends RouteConfig { const ChannelRouteConfig({required super.name, required super.path}); Map<String, String> params(Channel channel) => {'cid': channel.cid!}; Map<String, String> queryParams(Message message) => { 'mid': message.id, if (message.parentId != null) 'pid': message.parentId! }; }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/pages/channel_list_page.dart
import 'dart:async'; import 'package:example/app.dart'; import 'package:example/pages/user_mentions_page.dart'; import 'package:example/routes/routes.dart'; import 'package:example/state/init_data.dart'; import 'package:example/utils/app_config.dart'; import 'package:example/utils/localizations.dart'; import 'package:example/widgets/channel_list.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_app_badger/flutter_app_badger.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:go_router/go_router.dart'; import 'package:provider/provider.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import 'package:streaming_shared_preferences/streaming_shared_preferences.dart'; class ChannelListPage extends StatefulWidget { const ChannelListPage({ Key? key, }) : super(key: key); @override State<ChannelListPage> createState() => _ChannelListPageState(); } class _ChannelListPageState extends State<ChannelListPage> { int _currentIndex = 0; bool _isSelected(int index) => _currentIndex == index; List<BottomNavigationBarItem> get _navBarItems { return <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Stack( clipBehavior: Clip.none, children: [ StreamSvgIcon.message( color: _isSelected(0) ? StreamChatTheme.of(context).colorTheme.textHighEmphasis : Colors.grey, ), const Positioned( top: -3, right: -16, child: StreamUnreadIndicator(), ), ], ), label: AppLocalizations.of(context).chats, ), BottomNavigationBarItem( icon: Stack( clipBehavior: Clip.none, children: [ StreamSvgIcon.mentions( color: _isSelected(1) ? StreamChatTheme.of(context).colorTheme.textHighEmphasis : Colors.grey, ), ], ), label: AppLocalizations.of(context).mentions, ), ]; } @override Widget build(BuildContext context) { final user = StreamChat.of(context).currentUser; if (user == null) { return const Offstage(); } return Scaffold( backgroundColor: StreamChatTheme.of(context).colorTheme.appBg, appBar: StreamChannelListHeader( onNewChatButtonTap: () { GoRouter.of(context).pushNamed(Routes.NEW_CHAT.name); }, preNavigationCallback: () => FocusScope.of(context).requestFocus(FocusNode()), ), drawer: LeftDrawer( user: user, ), drawerEdgeDragWidth: 50, bottomNavigationBar: BottomNavigationBar( backgroundColor: StreamChatTheme.of(context).colorTheme.barsBg, currentIndex: _currentIndex, items: _navBarItems, selectedLabelStyle: StreamChatTheme.of(context).textTheme.footnoteBold, unselectedLabelStyle: StreamChatTheme.of(context).textTheme.footnoteBold, type: BottomNavigationBarType.fixed, selectedItemColor: StreamChatTheme.of(context).colorTheme.textHighEmphasis, unselectedItemColor: Colors.grey, onTap: (index) { setState(() => _currentIndex = index); }, ), body: IndexedStack( index: _currentIndex, children: const [ ChannelList(), UserMentionsPage(), ], ), ); } StreamSubscription<int>? badgeListener; @override void initState() { if (!kIsWeb) { badgeListener = StreamChat.of(context) .client .state .totalUnreadCountStream .listen((count) { if (count > 0) { FlutterAppBadger.updateBadgeCount(count); } else { FlutterAppBadger.removeBadge(); } }); } super.initState(); } @override void dispose() { badgeListener?.cancel(); super.dispose(); } } class LeftDrawer extends StatelessWidget { const LeftDrawer({ Key? key, required this.user, }) : super(key: key); final User user; @override Widget build(BuildContext context) { return Drawer( child: Container( color: StreamChatTheme.of(context).colorTheme.barsBg, child: SafeArea( child: Padding( padding: EdgeInsets.only( top: MediaQuery.of(context).viewPadding.top + 8, ), child: Column( children: [ Padding( padding: const EdgeInsets.only( bottom: 20.0, left: 8, ), child: Row( children: [ StreamUserAvatar( user: user, showOnlineStatus: false, constraints: BoxConstraints.tight(const Size.fromRadius(20)), ), Padding( padding: const EdgeInsets.only(left: 16.0), child: Text( user.name, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), ], ), ), ListTile( leading: StreamSvgIcon.penWrite( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(.5), ), onTap: () { Navigator.of(context).pop(); GoRouter.of(context).pushNamed(Routes.NEW_CHAT.name); }, title: Text( AppLocalizations.of(context).newDirectMessage, style: const TextStyle( fontSize: 14.5, ), ), ), ListTile( leading: StreamSvgIcon.contacts( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(.5), ), onTap: () { Navigator.of(context).pop(); GoRouter.of(context).pushNamed(Routes.NEW_GROUP_CHAT.name); }, title: Text( AppLocalizations.of(context).newGroup, style: const TextStyle( fontSize: 14.5, ), ), ), Expanded( child: Container( alignment: Alignment.bottomCenter, child: ListTile( onTap: () async { final client = StreamChat.of(context).client; final router = GoRouter.of(context); final initNotifier = context.read<InitNotifier>(); if (!kIsWeb) { const secureStorage = FlutterSecureStorage(); await secureStorage.deleteAll(); } await client.disconnectUser(flushChatPersistence: true); await client.dispose(); initNotifier.initData = initNotifier.initData!.copyWith( client: buildStreamChatClient(kDefaultStreamApiKey)); router.goNamed(Routes.CHOOSE_USER.name); }, leading: StreamSvgIcon.user( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(.5), ), title: Text( AppLocalizations.of(context).signOut, style: const TextStyle( fontSize: 14.5, ), ), trailing: IconButton( icon: StreamSvgIcon.iconMoon( size: 24, ), color: StreamChatTheme.of(context) .colorTheme .textLowEmphasis, onPressed: () async { final theme = Theme.of(context); final sp = await StreamingSharedPreferences.instance; sp.setInt( 'theme', theme.brightness == Brightness.dark ? 1 : -1, ); }, ), ), ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/pages/channel_file_display_screen.dart
import 'package:example/utils/localizations.dart'; import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import 'package:video_player/video_player.dart'; class ChannelFileDisplayScreen extends StatefulWidget { final StreamMessageThemeData messageTheme; const ChannelFileDisplayScreen({ Key? key, required this.messageTheme, }) : super(key: key); @override State<ChannelFileDisplayScreen> createState() => _ChannelFileDisplayScreenState(); } class _ChannelFileDisplayScreenState extends State<ChannelFileDisplayScreen> { final Map<String?, VideoPlayerController?> controllerCache = {}; late final controller = StreamMessageSearchListController( client: StreamChat.of(context).client, filter: Filter.in_( 'cid', [StreamChannel.of(context).channel.cid!], ), messageFilter: Filter.in_( 'attachments.type', const ['file'], ), sort: [ const SortOption( 'created_at', direction: SortOption.ASC, ), ], limit: 20, ); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: StreamChatTheme.of(context).colorTheme.barsBg, appBar: AppBar( elevation: 1, centerTitle: true, title: Text( AppLocalizations.of(context).files, style: TextStyle( color: StreamChatTheme.of(context).colorTheme.textHighEmphasis, fontSize: 16.0, ), ), leading: const StreamBackButton(), backgroundColor: StreamChatTheme.of(context).colorTheme.barsBg, ), body: ValueListenableBuilder( valueListenable: controller, builder: ( BuildContext context, PagedValue<String, GetMessageResponse> value, Widget? child, ) { return value.when( (items, nextPageKey, error) { if (items.isEmpty) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ StreamSvgIcon.files( size: 136.0, color: StreamChatTheme.of(context).colorTheme.disabled, ), const SizedBox(height: 16.0), Text( AppLocalizations.of(context).noFiles, style: TextStyle( fontSize: 14.0, color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis, ), ), const SizedBox(height: 8.0), Text( AppLocalizations.of(context).filesAppearHere, textAlign: TextAlign.center, style: TextStyle( fontSize: 14.0, color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5), ), ), ], ), ); } final media = <Attachment, Message>{}; for (var item in items) { item.message.attachments .where((e) => e.type == 'file') .forEach((e) { media[e] = item.message; }); } return LazyLoadScrollView( onEndOfPage: () async { if (nextPageKey != null) { controller.loadMore(nextPageKey); } }, child: ListView.builder( itemBuilder: (context, position) { return Padding( padding: const EdgeInsets.all(1.0), child: Padding( padding: const EdgeInsets.all(8.0), child: StreamFileAttachment( message: media.values.toList()[position], attachment: media.keys.toList()[position], ), ), ); }, itemCount: media.length, ), ); }, loading: () => const Center( child: CircularProgressIndicator(), ), error: (_) => const Offstage(), ); }, ), ); } @override void dispose() { controller.dispose(); super.dispose(); } @override void initState() { controller.doInitialLoad(); super.initState(); } }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/pages/new_group_chat_screen.dart
import 'dart:async'; import 'package:example/state/new_group_chat_state.dart'; import 'package:example/utils/localizations.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import '../routes/routes.dart'; import '../widgets/search_text_field.dart'; class NewGroupChatScreen extends StatefulWidget { const NewGroupChatScreen({super.key}); @override State<NewGroupChatScreen> createState() => _NewGroupChatScreenState(); } class _NewGroupChatScreenState extends State<NewGroupChatScreen> { late final TextEditingController _controller = TextEditingController() ..addListener(_userNameListener); String _userNameQuery = ''; final groupChatState = NewGroupChatState(); bool _isSearchActive = false; Timer? _debounce; late final userListController = StreamUserListController( client: StreamChat.of(context).client, sort: [ const SortOption( 'name', direction: 1, ), ], limit: 25, filter: Filter.and([ Filter.notEqual('id', StreamChat.of(context).currentUser!.id), ]), ); void _userNameListener() { if (_debounce?.isActive ?? false) _debounce!.cancel(); _debounce = Timer(const Duration(milliseconds: 350), () { if (mounted) { setState(() { _userNameQuery = _controller.text; _isSearchActive = _userNameQuery.isNotEmpty; }); userListController.filter = Filter.and([ if (_userNameQuery.isNotEmpty) Filter.autoComplete('name', _userNameQuery), Filter.notEqual('id', StreamChat.of(context).currentUser!.id), ]); userListController.doInitialLoad(); } }); } @override void dispose() { _controller.clear(); _controller.removeListener(_userNameListener); _controller.dispose(); userListController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: groupChatState, builder: (context, child) { final state = groupChatState; return Scaffold( backgroundColor: StreamChatTheme.of(context).colorTheme.appBg, appBar: AppBar( elevation: 1, backgroundColor: StreamChatTheme.of(context).colorTheme.barsBg, leading: const StreamBackButton(), title: Text( AppLocalizations.of(context).addGroupMembers, style: TextStyle( color: StreamChatTheme.of(context).colorTheme.textHighEmphasis, fontSize: 16, ), ), centerTitle: true, actions: [ if (state.users.isNotEmpty) IconButton( icon: StreamSvgIcon.arrowRight( color: StreamChatTheme.of(context).colorTheme.accentPrimary, ), onPressed: () async { GoRouter.of(context).pushNamed( Routes.NEW_GROUP_CHAT_DETAILS.name, extra: state, ); }, ) ], ), body: StreamConnectionStatusBuilder( statusBuilder: (context, status) { String statusString = ''; bool showStatus = true; switch (status) { case ConnectionStatus.connected: statusString = AppLocalizations.of(context).connected; showStatus = false; break; case ConnectionStatus.connecting: statusString = AppLocalizations.of(context).reconnecting; break; case ConnectionStatus.disconnected: statusString = AppLocalizations.of(context).disconnected; break; } return StreamInfoTile( showMessage: showStatus, tileAnchor: Alignment.topCenter, childAnchor: Alignment.topCenter, message: statusString, child: NestedScrollView( floatHeaderSlivers: true, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverToBoxAdapter( child: SearchTextField( controller: _controller, hintText: AppLocalizations.of(context).search, ), ), if (state.users.isNotEmpty) SliverToBoxAdapter( child: SizedBox( height: 104, child: ListView.separated( scrollDirection: Axis.horizontal, itemCount: state.users.length, padding: const EdgeInsets.all(8), separatorBuilder: (_, __) => const SizedBox(width: 16), itemBuilder: (_, index) { final user = state.users.elementAt(index); return Column( children: [ Stack( children: [ StreamUserAvatar( onlineIndicatorAlignment: const Alignment(0.9, 0.9), user: user, showOnlineStatus: true, borderRadius: BorderRadius.circular(32), constraints: const BoxConstraints.tightFor( height: 64, width: 64, ), ), Positioned( top: -4, right: -4, child: GestureDetector( onTap: () { groupChatState.removeUser(user); }, child: Container( decoration: BoxDecoration( color: StreamChatTheme.of(context) .colorTheme .appBg, shape: BoxShape.circle, border: Border.all( color: StreamChatTheme.of( context) .colorTheme .appBg, ), ), child: StreamSvgIcon.close( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis, size: 24, ), ), ), ) ], ), const SizedBox(height: 4), Text( user.name.split(' ')[0], style: const TextStyle( fontWeight: FontWeight.bold, fontSize: 12, ), ), ], ); }, ), ), ), SliverPersistentHeader( pinned: true, delegate: _HeaderDelegate( height: 32, child: Container( width: double.maxFinite, decoration: BoxDecoration( gradient: StreamChatTheme.of(context) .colorTheme .bgGradient, ), child: Padding( padding: const EdgeInsets.symmetric( vertical: 8, horizontal: 8, ), child: Text( _isSearchActive ? '${AppLocalizations.of(context).matchesFor} "$_userNameQuery"' : AppLocalizations.of(context).onThePlatorm, style: TextStyle( color: StreamChatTheme.of(context) .colorTheme .textLowEmphasis, ), ), ), ), ), ), ]; }, body: GestureDetector( behavior: HitTestBehavior.opaque, onPanDown: (_) => FocusScope.of(context).unfocus(), child: StreamUserListView( controller: userListController, itemBuilder: (context, items, index, defaultWidget) { return defaultWidget.copyWith( selected: state.users.contains(items[index]), ); }, onUserTap: groupChatState.addOrRemoveUser, emptyBuilder: (_) { return LayoutBuilder( builder: (context, viewportConstraints) { return SingleChildScrollView( physics: const AlwaysScrollableScrollPhysics(), child: ConstrainedBox( constraints: BoxConstraints( minHeight: viewportConstraints.maxHeight, ), child: Center( child: Column( children: [ Padding( padding: const EdgeInsets.all(24), child: StreamSvgIcon.search( size: 96, color: StreamChatTheme.of(context) .colorTheme .textLowEmphasis, ), ), Text( AppLocalizations.of(context) .noUserMatchesTheseKeywords, style: StreamChatTheme.of(context) .textTheme .footnote .copyWith( color: StreamChatTheme.of(context) .colorTheme .textLowEmphasis, ), ), ], ), ), ), ); }, ); }, ), ), ), ); }, ), ); }, ); } } class _HeaderDelegate extends SliverPersistentHeaderDelegate { final Widget child; final double height; const _HeaderDelegate({ required this.child, required this.height, }); @override Widget build( BuildContext context, double shrinkOffset, bool overlapsContent) { return Container( color: StreamChatTheme.of(context).colorTheme.barsBg, child: child, ); } @override double get maxExtent => height; @override double get minExtent => height; @override bool shouldRebuild(_HeaderDelegate oldDelegate) => true; }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/pages/thread_page.dart
import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class ThreadPage extends StatefulWidget { final Message parent; final int? initialScrollIndex; final double? initialAlignment; const ThreadPage({ Key? key, required this.parent, this.initialScrollIndex, this.initialAlignment, }) : super(key: key); @override State<ThreadPage> createState() => _ThreadPageState(); } class _ThreadPageState extends State<ThreadPage> { final FocusNode _focusNode = FocusNode(); late StreamMessageInputController _messageInputController; @override void initState() { super.initState(); _messageInputController = StreamMessageInputController( message: Message(parentId: widget.parent.id), ); } @override void dispose() { _focusNode.dispose(); super.dispose(); } void _reply(Message message) { _messageInputController.quotedMessage = message; WidgetsBinding.instance.addPostFrameCallback((timeStamp) { _focusNode.requestFocus(); }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: StreamChatTheme.of(context).colorTheme.appBg, appBar: StreamThreadHeader( parent: widget.parent, ), body: Column( children: <Widget>[ Expanded( child: StreamMessageListView( parentMessage: widget.parent, initialScrollIndex: widget.initialScrollIndex, initialAlignment: widget.initialAlignment, onMessageSwiped: _reply, messageFilter: defaultFilter, showScrollToBottom: false, highlightInitialMessage: true, messageBuilder: (context, details, messages, defaultMessage) { return defaultMessage.copyWith( onReplyTap: _reply, bottomRowBuilderWithDefaultWidget: ( context, message, defaultWidget, ) { return defaultWidget.copyWith( deletedBottomRowBuilder: (context, message) { return const StreamVisibleFootnote(); }, ); }, ); }, ), ), if (widget.parent.type != 'deleted') StreamMessageInput( focusNode: _focusNode, messageInputController: _messageInputController, ), ], ), ); } bool defaultFilter(Message m) { final currentUser = StreamChat.of(context).currentUser; final isMyMessage = m.user?.id == currentUser?.id; final isDeletedOrShadowed = m.isDeleted == true || m.shadowed == true; if (isDeletedOrShadowed && !isMyMessage) return false; return true; } }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/pages/group_info_screen.dart
import 'dart:async'; import 'package:collection/collection.dart' show IterableExtension; import 'package:example/pages/channel_file_display_screen.dart'; import 'package:example/routes/routes.dart'; import 'package:example/utils/localizations.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import 'channel_media_display_screen.dart'; import 'pinned_messages_screen.dart'; class GroupInfoScreen extends StatefulWidget { final StreamMessageThemeData messageTheme; const GroupInfoScreen({ Key? key, required this.messageTheme, }) : super(key: key); @override State<GroupInfoScreen> createState() => _GroupInfoScreenState(); } class _GroupInfoScreenState extends State<GroupInfoScreen> { late final TextEditingController _nameController = TextEditingController.fromValue( TextEditingValue(text: (channel.extraData['name'] as String?) ?? ''), ); late final TextEditingController _searchController = TextEditingController() ..addListener(_userNameListener); String _userNameQuery = ''; Timer? _debounce; Function? modalSetStateCallback; final FocusNode _focusNode = FocusNode(); bool listExpanded = false; late ValueNotifier<bool?> mutedBool = ValueNotifier(channel.isMuted); late final channel = StreamChannel.of(context).channel; late StreamUserListController _userListController; void _userNameListener() { if (_searchController.text == _userNameQuery) { return; } if (_debounce?.isActive ?? false) _debounce!.cancel(); _debounce = Timer(const Duration(milliseconds: 350), () { if (mounted) { _userNameQuery = _searchController.text; _userListController.filter = Filter.and( [ if (_searchController.text.isNotEmpty) Filter.autoComplete('name', _userNameQuery), Filter.notIn('id', [ StreamChat.of(context).currentUser!.id, ...channel.state!.members .map<String?>(((e) => e.userId)) .whereType<String>(), ]), ], ); _userListController.doInitialLoad(); } }); } @override void initState() { super.initState(); _nameController.addListener(() { setState(() {}); }); mutedBool = ValueNotifier(channel.isMuted); } @override void didChangeDependencies() { _userListController = StreamUserListController( client: StreamChat.of(context).client, limit: 25, filter: Filter.and( [ if (_searchController.text.isNotEmpty) Filter.autoComplete('name', _userNameQuery), Filter.notIn('id', [ StreamChat.of(context).currentUser!.id, ...channel.state!.members .map<String?>(((e) => e.userId)) .whereType<String>(), ]), ], ), sort: [ const SortOption( 'name', direction: 1, ), ], ); super.didChangeDependencies(); } @override void dispose() { _nameController.dispose(); _searchController.dispose(); _userListController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return StreamBuilder<List<Member>>( stream: channel.state!.membersStream, builder: (context, snapshot) { if (!snapshot.hasData) { return Container( color: StreamChatTheme.of(context).colorTheme.disabled, child: const Center(child: CircularProgressIndicator()), ); } return Scaffold( backgroundColor: StreamChatTheme.of(context).colorTheme.appBg, appBar: AppBar( elevation: 1.0, toolbarHeight: 56.0, backgroundColor: StreamChatTheme.of(context).colorTheme.barsBg, leading: const StreamBackButton(), title: Column( children: [ StreamBuilder<ChannelState>( stream: channel.state?.channelStateStream, builder: (context, state) { if (!state.hasData) { return Text( AppLocalizations.of(context).loading, style: TextStyle( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis, fontSize: 16, ), maxLines: 1, overflow: TextOverflow.ellipsis, ); } return Text( _getChannelName( 2 * MediaQuery.of(context).size.width / 3, members: snapshot.data, extraData: state.data!.channel!.extraData, maxFontSize: 16.0, )!, style: TextStyle( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis, fontSize: 16, ), maxLines: 1, overflow: TextOverflow.ellipsis, ); }), const SizedBox( height: 3.0, ), Text( '${channel.memberCount} ${AppLocalizations.of(context).members}, ${snapshot.data?.where((e) => e.user!.online).length ?? 0} ${AppLocalizations.of(context).online}', style: TextStyle( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5), fontSize: 12.0, ), ), ], ), centerTitle: true, actions: [ if (channel.ownCapabilities .contains(PermissionType.updateChannelMembers)) StreamNeumorphicButton( child: InkWell( onTap: () { _buildAddUserModal(context); }, child: Padding( padding: const EdgeInsets.all(8.0), child: StreamSvgIcon.userAdd( color: StreamChatTheme.of(context) .colorTheme .accentPrimary), ), ), ), ], ), body: ListView( children: [ _buildMembers(snapshot.data!), Container( height: 8.0, color: StreamChatTheme.of(context).colorTheme.disabled, ), if (channel.ownCapabilities .contains(PermissionType.updateChannel)) _buildNameTile(), _buildOptionListTiles(), ], ), ); }); } Widget _buildMembers(List<Member> members) { final groupMembers = members ..sort((prev, curr) { if (curr.userId == channel.createdBy?.id) return 1; return 0; }); int groupMembersLength; if (listExpanded) { groupMembersLength = groupMembers.length; } else { groupMembersLength = groupMembers.length > 6 ? 6 : groupMembers.length; } return Column( children: [ ListView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemCount: groupMembersLength, itemBuilder: (context, index) { final member = groupMembers[index]; return Material( color: StreamChatTheme.of(context).colorTheme.appBg, child: InkWell( onTap: () { final userMember = groupMembers.firstWhereOrNull( (e) => e.user!.id == StreamChat.of(context).currentUser!.id, ); _showUserInfoModal( member.user, userMember?.userId == channel.createdBy?.id); }, child: SizedBox( height: 65.0, child: Column( children: [ Row( children: [ Padding( padding: const EdgeInsets.symmetric( horizontal: 8.0, vertical: 12.0, ), child: StreamUserAvatar( user: member.user!, constraints: const BoxConstraints.tightFor( height: 40.0, width: 40.0, ), ), ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( member.user!.name, style: const TextStyle( fontWeight: FontWeight.bold), ), const SizedBox( height: 1.0, ), Text( _getLastSeen(member.user!), style: TextStyle( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5)), ), ], ), ), Padding( padding: const EdgeInsets.all(8.0), child: Text( member.userId == channel.createdBy?.id ? AppLocalizations.of(context).owner : '', style: TextStyle( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5)), ), ), ], ), Container( height: 1.0, color: StreamChatTheme.of(context).colorTheme.disabled, ), ], ), ), ), ); }, ), if (groupMembersLength != groupMembers.length) InkWell( onTap: () { setState(() { listExpanded = true; }); }, child: Material( color: StreamChatTheme.of(context).colorTheme.appBg, child: SizedBox( height: 65.0, child: Column( children: [ Expanded( child: Row( children: [ Padding( padding: const EdgeInsets.symmetric( horizontal: 21.0, vertical: 12.0), child: StreamSvgIcon.down( color: StreamChatTheme.of(context) .colorTheme .textLowEmphasis, ), ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( '${members.length - groupMembersLength} ${AppLocalizations.of(context).more}', style: TextStyle( color: StreamChatTheme.of(context) .colorTheme .textLowEmphasis), ), ], ), ), ], ), ), Container( height: 1.0, color: StreamChatTheme.of(context).colorTheme.disabled, ), ], ), ), ), ), ], ); } Widget _buildNameTile() { final channelName = (channel.extraData['name'] as String?) ?? ''; return Material( color: StreamChatTheme.of(context).colorTheme.appBg, child: Container( height: 56.0, alignment: Alignment.center, child: Row( children: [ Padding( padding: const EdgeInsets.all(7.0), child: Text( AppLocalizations.of(context).name.toUpperCase(), style: StreamChatTheme.of(context).textTheme.footnote.copyWith( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5)), ), ), const SizedBox( width: 7.0, ), Expanded( child: TextField( enabled: channel.ownCapabilities .contains(PermissionType.updateChannel), focusNode: _focusNode, controller: _nameController, cursorColor: StreamChatTheme.of(context).colorTheme.textHighEmphasis, decoration: InputDecoration.collapsed( hintText: AppLocalizations.of(context).addAGroupName, hintStyle: StreamChatTheme.of(context) .textTheme .bodyBold .copyWith( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5))), style: const TextStyle( fontWeight: FontWeight.bold, height: 0.82, ), ), ), if (channelName != _nameController.text.trim()) Row( mainAxisSize: MainAxisSize.min, children: [ InkWell( child: StreamSvgIcon.closeSmall(), onTap: () { setState(() { _nameController.text = _getChannelName( 2 * MediaQuery.of(context).size.width / 3, members: channel.state!.members, extraData: channel.extraData, maxFontSize: 16.0, )!; _focusNode.unfocus(); }); }, ), Padding( padding: const EdgeInsets.only(right: 16.0, left: 8.0), child: InkWell( child: StreamSvgIcon.check( color: StreamChatTheme.of(context) .colorTheme .accentPrimary, size: 24.0, ), onTap: () { try { channel.update({ 'name': _nameController.text.trim(), }); } catch (_) { setState(() { _nameController.text = channelName; _focusNode.unfocus(); }); } }, ), ), ], ), ], ), ), ); } Widget _buildOptionListTiles() { return Column( children: [ if (channel.ownCapabilities.contains(PermissionType.muteChannel)) StreamBuilder<bool>( stream: channel.isMutedStream, builder: (context, snapshot) { mutedBool.value = snapshot.data; return StreamOptionListTile( tileColor: StreamChatTheme.of(context).colorTheme.appBg, separatorColor: StreamChatTheme.of(context).colorTheme.disabled, title: AppLocalizations.of(context).muteGroup, titleTextStyle: StreamChatTheme.of(context).textTheme.body, leading: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: StreamSvgIcon.mute( size: 24.0, color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5), ), ), trailing: snapshot.data == null ? const CircularProgressIndicator() : ValueListenableBuilder<bool?>( valueListenable: mutedBool, builder: (context, value, _) { return CupertinoSwitch( value: value!, onChanged: (val) { mutedBool.value = val; if (snapshot.data!) { channel.unmute(); } else { channel.mute(); } }, ); }), onTap: () {}, ); }), StreamOptionListTile( title: AppLocalizations.of(context).pinnedMessages, tileColor: StreamChatTheme.of(context).colorTheme.appBg, titleTextStyle: StreamChatTheme.of(context).textTheme.body, leading: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: StreamSvgIcon.pin( size: 24.0, color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5), ), ), trailing: StreamSvgIcon.right( color: StreamChatTheme.of(context).colorTheme.textLowEmphasis, ), onTap: () { final channel = StreamChannel.of(context).channel; Navigator.push( context, MaterialPageRoute( builder: (context) => StreamChannel( channel: channel, child: const PinnedMessagesScreen(), ), ), ); }, ), StreamOptionListTile( tileColor: StreamChatTheme.of(context).colorTheme.appBg, separatorColor: StreamChatTheme.of(context).colorTheme.disabled, title: AppLocalizations.of(context).photosAndVideos, titleTextStyle: StreamChatTheme.of(context).textTheme.body, leading: Padding( padding: const EdgeInsets.symmetric(horizontal: 12.0), child: StreamSvgIcon.pictures( size: 32.0, color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5), ), ), trailing: StreamSvgIcon.right( color: StreamChatTheme.of(context).colorTheme.textLowEmphasis, ), onTap: () { final channel = StreamChannel.of(context).channel; Navigator.push( context, MaterialPageRoute( builder: (context) => StreamChannel( channel: channel, child: ChannelMediaDisplayScreen( messageTheme: widget.messageTheme, ), ), ), ); }, ), StreamOptionListTile( tileColor: StreamChatTheme.of(context).colorTheme.appBg, separatorColor: StreamChatTheme.of(context).colorTheme.disabled, title: AppLocalizations.of(context).files, titleTextStyle: StreamChatTheme.of(context).textTheme.body, leading: Padding( padding: const EdgeInsets.symmetric(horizontal: 12.0), child: StreamSvgIcon.files( size: 32.0, color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5), ), ), trailing: StreamSvgIcon.right( color: StreamChatTheme.of(context).colorTheme.textLowEmphasis, ), onTap: () { final channel = StreamChannel.of(context).channel; Navigator.push( context, MaterialPageRoute( builder: (context) => StreamChannel( channel: channel, child: ChannelFileDisplayScreen( messageTheme: widget.messageTheme, ), ), ), ); }, ), if (!channel.isDistinct && channel.ownCapabilities.contains(PermissionType.leaveChannel)) StreamOptionListTile( tileColor: StreamChatTheme.of(context).colorTheme.appBg, separatorColor: StreamChatTheme.of(context).colorTheme.disabled, title: AppLocalizations.of(context).leaveGroup, titleTextStyle: StreamChatTheme.of(context).textTheme.body, leading: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: StreamSvgIcon.userRemove( size: 24.0, color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5), ), ), trailing: const SizedBox( height: 24.0, width: 24.0, ), onTap: () async { final streamChannel = StreamChannel.of(context); final streamChat = StreamChat.of(context); final router = GoRouter.of(context); final res = await showConfirmationBottomSheet( context, title: AppLocalizations.of(context).leaveConversation, okText: AppLocalizations.of(context).leave.toUpperCase(), question: AppLocalizations.of(context).leaveConversationAreYouSure, cancelText: AppLocalizations.of(context).cancel.toUpperCase(), icon: StreamSvgIcon.userRemove( color: StreamChatTheme.of(context).colorTheme.accentError, ), ); if (res == true) { final channel = streamChannel.channel; await channel.removeMembers([streamChat.currentUser!.id]); router.pop(); } }, ), ], ); } void _buildAddUserModal(context) { showDialog( useRootNavigator: false, context: context, barrierColor: StreamChatTheme.of(context).colorTheme.overlay, builder: (context) { return Padding( padding: const EdgeInsets.only(top: 16.0, left: 8.0, right: 8.0), child: Material( borderRadius: const BorderRadius.only( topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0), ), clipBehavior: Clip.antiAlias, child: Scaffold( body: Column( children: [ Padding( padding: const EdgeInsets.all(16), child: _buildTextInputSection(), ), Expanded( child: StreamUserGridView( controller: _userListController, onUserTap: (user) async { _searchController.clear(); final navigator = Navigator.of(context); await channel.addMembers([user.id]); navigator.pop(); setState(() {}); }, emptyBuilder: (_) { return LayoutBuilder( builder: (context, viewportConstraints) { return SingleChildScrollView( physics: const AlwaysScrollableScrollPhysics(), child: ConstrainedBox( constraints: BoxConstraints( minHeight: viewportConstraints.maxHeight, ), child: Center( child: Column( children: [ Padding( padding: const EdgeInsets.all(24), child: StreamSvgIcon.search( size: 96, color: StreamChatTheme.of(context) .colorTheme .textLowEmphasis, ), ), Text(AppLocalizations.of(context) .noUserMatchesTheseKeywords), ], ), ), ), ); }, ); }, ), ), ], ), ), ), ); }, ).whenComplete(() { _searchController.clear(); }); } Widget _buildTextInputSection() { final theme = StreamChatTheme.of(context); return Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded( child: SizedBox( height: 36, child: TextField( controller: _searchController, cursorColor: theme.colorTheme.textHighEmphasis, autofocus: true, decoration: InputDecoration( hintText: AppLocalizations.of(context).search, hintStyle: theme.textTheme.body.copyWith( color: theme.colorTheme.textLowEmphasis, ), prefixIconConstraints: BoxConstraints.tight(const Size(40, 24)), prefixIcon: StreamSvgIcon.search( color: theme.colorTheme.textHighEmphasis, size: 24, ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(24.0), borderSide: BorderSide( color: theme.colorTheme.borders, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(24.0), borderSide: BorderSide( color: theme.colorTheme.borders, )), contentPadding: const EdgeInsets.all(0), ), ), ), ), const SizedBox(width: 16.0), IconButton( icon: StreamSvgIcon.closeSmall( color: theme.colorTheme.textLowEmphasis, ), constraints: const BoxConstraints.tightFor( height: 24, width: 24, ), padding: EdgeInsets.zero, splashRadius: 24, onPressed: () => Navigator.pop(context), ) ], ), ], ); } void _showUserInfoModal(User? user, bool isUserAdmin) { final color = StreamChatTheme.of(context).colorTheme.barsBg; showModalBottomSheet( useRootNavigator: false, context: context, clipBehavior: Clip.antiAlias, isScrollControlled: true, backgroundColor: color, builder: (context) { return SafeArea( child: StreamChannel( channel: channel, child: Material( color: color, child: Column( mainAxisSize: MainAxisSize.min, children: [ const SizedBox( height: 24.0, ), Center( child: Text( user!.name, style: const TextStyle( fontSize: 16.0, fontWeight: FontWeight.bold, ), ), ), const SizedBox( height: 5.0, ), _buildConnectedTitleState(user)!, Center( child: Padding( padding: const EdgeInsets.all(16.0), child: StreamUserAvatar( user: user, constraints: const BoxConstraints.tightFor( height: 64.0, width: 64.0, ), borderRadius: BorderRadius.circular(32.0), ), ), ), if (StreamChat.of(context).currentUser!.id != user.id) _buildModalListTile( context, StreamSvgIcon.user( color: StreamChatTheme.of(context) .colorTheme .textLowEmphasis, size: 24.0, ), AppLocalizations.of(context).viewInfo, () async { final client = StreamChat.of(context).client; final router = GoRouter.of(context); final c = client.channel('messaging', extraData: { 'members': [ user.id, StreamChat.of(context).currentUser!.id, ], }); await c.watch(); router.pushNamed( Routes.CHAT_INFO_SCREEN.name, pathParameters: Routes.CHAT_INFO_SCREEN.params(c), extra: user, ); }, ), if (StreamChat.of(context).currentUser!.id != user.id) _buildModalListTile( context, StreamSvgIcon.message( color: StreamChatTheme.of(context) .colorTheme .textLowEmphasis, size: 24.0, ), AppLocalizations.of(context).message, () async { final client = StreamChat.of(context).client; final router = GoRouter.of(context); final c = client.channel('messaging', extraData: { 'members': [ user.id, StreamChat.of(context).currentUser!.id, ], }); await c.watch(); router.pushNamed( Routes.CHANNEL_PAGE.name, pathParameters: Routes.CHANNEL_PAGE.params(c), ); }, ), if (!channel.isDistinct && StreamChat.of(context).currentUser!.id != user.id && isUserAdmin) _buildModalListTile( context, StreamSvgIcon.userRemove( color: StreamChatTheme.of(context) .colorTheme .accentError, size: 24.0, ), AppLocalizations.of(context).removeFromGroup, () async { final router = GoRouter.of(context); final res = await showConfirmationBottomSheet( context, title: AppLocalizations.of(context).removeMember, okText: AppLocalizations.of(context).remove.toUpperCase(), question: AppLocalizations.of(context).removeMemberAreYouSure, cancelText: AppLocalizations.of(context).cancel.toUpperCase(), ); if (res == true) { await channel.removeMembers([user.id]); } router.pop(); }, color: StreamChatTheme.of(context).colorTheme.accentError), _buildModalListTile( context, StreamSvgIcon.closeSmall( color: StreamChatTheme.of(context) .colorTheme .textLowEmphasis, size: 24.0, ), AppLocalizations.of(context).cancel, () { Navigator.pop(context); }, ), ], ), ), ), ); }, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0), ), ), ); } Widget? _buildConnectedTitleState(User? user) { late Text alternativeWidget; final otherMember = user; if (otherMember != null) { if (otherMember.online) { alternativeWidget = Text( AppLocalizations.of(context).online, style: TextStyle( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5)), ); } else { alternativeWidget = Text( '${AppLocalizations.of(context).lastSeen} ${Jiffy.parseFromDateTime(otherMember.lastActive!).fromNow()}', style: TextStyle( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5)), ); } } return alternativeWidget; } Widget _buildModalListTile( BuildContext context, Widget leading, String title, VoidCallback onTap, {Color? color}) { color ??= StreamChatTheme.of(context).colorTheme.textHighEmphasis; return Material( color: StreamChatTheme.of(context).colorTheme.barsBg, child: InkWell( onTap: onTap, child: Column( children: [ Container( height: 1.0, color: StreamChatTheme.of(context).colorTheme.disabled, ), SizedBox( height: 64.0, child: Row( children: [ Padding( padding: const EdgeInsets.all(16.0), child: leading, ), Expanded( child: Text( title, style: TextStyle(color: color, fontWeight: FontWeight.bold), ), ) ], ), ), ], ), ), ); } String? _getChannelName( double width, { List<Member>? members, required Map extraData, double? maxFontSize, }) { String? title; final client = StreamChat.of(context); if (extraData['name'] == null) { final otherMembers = members!.where((member) => member.user!.id != client.currentUser!.id); if (otherMembers.isNotEmpty) { final maxWidth = width; final maxChars = maxWidth / maxFontSize!; var currentChars = 0; final currentMembers = <Member>[]; for (final element in otherMembers) { final newLength = currentChars + element.user!.name.length; if (newLength < maxChars) { currentChars = newLength; currentMembers.add(element); } } final exceedingMembers = otherMembers.length - currentMembers.length; title = '${currentMembers.map((e) => e.user!.name).join(', ')} ${exceedingMembers > 0 ? '+ $exceedingMembers' : ''}'; } else { title = AppLocalizations.of(context).noTitle; } } else { title = extraData['name']; } return title; } String _getLastSeen(User user) { if (user.online) { return AppLocalizations.of(context).online; } else { return '${AppLocalizations.of(context).lastSeen} ${Jiffy.parseFromDateTime(user.lastActive!).fromNow()}'; } } }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/pages/choose_user_page.dart
import 'package:example/state/init_data.dart'; import 'package:example/utils/app_config.dart'; import 'package:example/utils/localizations.dart'; import 'package:example/widgets/stream_version.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; import 'package:provider/provider.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import '../routes/routes.dart'; const kStreamApiKey = 'STREAM_API_KEY'; const kStreamUserId = 'STREAM_USER_ID'; const kStreamToken = 'STREAM_TOKEN'; class ChooseUserPage extends StatelessWidget { const ChooseUserPage({super.key}); @override Widget build(BuildContext context) { final users = defaultUsers; return Scaffold( backgroundColor: StreamChatTheme.of(context).colorTheme.appBg, body: SafeArea( child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.only( top: 34, bottom: 20, ), child: Center( child: SvgPicture.asset( 'assets/logo.svg', height: 40, colorFilter: ColorFilter.mode( StreamChatTheme.of(context).colorTheme.accentPrimary, BlendMode.srcIn, ), ), ), ), Padding( padding: const EdgeInsets.only(bottom: 13.0), child: Text( AppLocalizations.of(context).welcomeToStreamChat, style: StreamChatTheme.of(context).textTheme.title, ), ), Text( '${AppLocalizations.of(context).selectUserToTryFlutterSDK}:', style: StreamChatTheme.of(context).textTheme.body, ), Expanded( child: Padding( padding: const EdgeInsets.only(top: 32), child: ListView.separated( separatorBuilder: (context, i) { return Container( height: 1, color: StreamChatTheme.of(context).colorTheme.borders, ); }, itemCount: users.length + 1, itemBuilder: (context, i) { return [ ...users.entries.map((entry) { final token = entry.key; final user = entry.value; return ListTile( visualDensity: VisualDensity.compact, onTap: () async { showDialog( barrierDismissible: false, context: context, barrierColor: StreamChatTheme.of(context) .colorTheme .overlay, builder: (context) => Center( child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(16), color: StreamChatTheme.of(context) .colorTheme .barsBg, ), height: 100, width: 100, child: const Center( child: CircularProgressIndicator(), ), ), ), ); final client = context.read<InitNotifier>().initData!.client; final router = GoRouter.of(context); await client.connectUser( user, token, ); if (!kIsWeb) { const secureStorage = FlutterSecureStorage(); secureStorage.write( key: kStreamApiKey, value: kDefaultStreamApiKey, ); secureStorage.write( key: kStreamUserId, value: user.id, ); secureStorage.write( key: kStreamToken, value: token, ); } // Pop the progress dialog. router.pop(); router.replaceNamed(Routes.CHANNEL_LIST_PAGE.name); }, leading: StreamUserAvatar( user: user, constraints: BoxConstraints.tight( const Size.fromRadius(20), ), ), title: Text( user.name, style: StreamChatTheme.of(context).textTheme.bodyBold, ), subtitle: Text( AppLocalizations.of(context).streamTestAccount, style: StreamChatTheme.of(context) .textTheme .footnote .copyWith( color: StreamChatTheme.of(context) .colorTheme .textLowEmphasis, ), ), trailing: StreamSvgIcon.arrowRight( color: StreamChatTheme.of(context) .colorTheme .accentPrimary, ), ); }), ListTile( onTap: () => GoRouter.of(context) .pushNamed(Routes.ADVANCED_OPTIONS.name), leading: CircleAvatar( backgroundColor: StreamChatTheme.of(context).colorTheme.borders, child: StreamSvgIcon.settings( color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis, ), ), title: Text( AppLocalizations.of(context).advancedOptions, style: StreamChatTheme.of(context).textTheme.bodyBold, ), subtitle: Text( AppLocalizations.of(context).customSettings, style: StreamChatTheme.of(context) .textTheme .footnote .copyWith( color: StreamChatTheme.of(context) .colorTheme .textLowEmphasis, ), ), trailing: SvgPicture.asset( 'assets/icon_arrow_right.svg', height: 24, width: 24, clipBehavior: Clip.none, ), ), ][i]; }, ), ), ), const StreamVersion(), ], ), ), ); } }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/pages/advanced_options_page.dart
import 'package:example/app.dart'; import 'package:example/state/init_data.dart'; import 'package:example/utils/localizations.dart'; import 'package:example/routes/routes.dart'; import 'package:example/widgets/stream_version.dart'; import 'package:flutter/material.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:go_router/go_router.dart'; import 'package:provider/provider.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import 'package:example/pages/choose_user_page.dart'; class AdvancedOptionsPage extends StatefulWidget { const AdvancedOptionsPage({super.key}); @override State<AdvancedOptionsPage> createState() => _AdvancedOptionsPageState(); } class _AdvancedOptionsPageState extends State<AdvancedOptionsPage> { final _formKey = GlobalKey<FormState>(); final TextEditingController _apiKeyController = TextEditingController(); String? _apiKeyError; final TextEditingController _userIdController = TextEditingController(); String? _userIdError; final TextEditingController _userTokenController = TextEditingController(); String? _userTokenError; final TextEditingController _usernameController = TextEditingController(); bool loading = false; @override void dispose() { _apiKeyController.dispose(); _userIdController.dispose(); _userTokenController.dispose(); _usernameController.dispose(); super.dispose(); } Future<void> _login() async { if (loading) { return; } if (_formKey.currentState!.validate()) { final apiKey = _apiKeyController.text; final userId = _userIdController.text; final userToken = _userTokenController.text; final username = _usernameController.text; loading = true; showDialog( barrierDismissible: false, context: context, barrierColor: StreamChatTheme.of(context).colorTheme.overlay, builder: (context) => Center( child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(16), color: StreamChatTheme.of(context).colorTheme.barsBg, ), height: 100, width: 100, child: const Center( child: CircularProgressIndicator(), ), ), ), ); final client = buildStreamChatClient(apiKey); final router = GoRouter.of(context); final initNotifier = context.read<InitNotifier>(); try { await client.connectUser( User( id: userId, extraData: { 'name': username, }, ), userToken, ); const secureStorage = FlutterSecureStorage(); await Future.wait([ secureStorage.write( key: kStreamApiKey, value: apiKey, ), secureStorage.write( key: kStreamUserId, value: userId, ), secureStorage.write( key: kStreamToken, value: userToken, ), ]); } catch (e) { debugPrint(e.toString()); var errorText = AppLocalizations.of(context).errorConnecting; if (e is Map) { errorText = e['message'] ?? errorText; } Navigator.of(context).pop(); setState(() { _apiKeyError = errorText.toUpperCase(); }); loading = false; return; } loading = false; initNotifier.initData = initNotifier.initData!.copyWith(client: client); router.goNamed(Routes.CHOOSE_USER.name); } } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: StreamChatTheme.of(context).colorTheme.appBg, appBar: AppBar( backgroundColor: StreamChatTheme.of(context).colorTheme.barsBg, elevation: 1, centerTitle: true, title: Text( AppLocalizations.of(context).advancedOptions, style: StreamChatTheme.of(context).textTheme.headlineBold.copyWith( color: StreamChatTheme.of(context).colorTheme.textHighEmphasis), ), leading: IconButton( icon: StreamSvgIcon.left( color: StreamChatTheme.of(context).colorTheme.textHighEmphasis, ), onPressed: () { Navigator.pop(context); }, ), ), body: Builder( builder: (context) { return Padding( padding: const EdgeInsets.fromLTRB(16, 16, 16, 0), child: Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ TextFormField( controller: _apiKeyController, onChanged: (_) { if (_apiKeyError != null) { setState(() { _apiKeyError = null; }); } }, validator: (value) { if (value!.isEmpty) { setState(() { _apiKeyError = AppLocalizations.of(context) .apiKeyError .toUpperCase(); }); return _apiKeyError; } return null; }, style: TextStyle( fontSize: 14, color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis, ), decoration: InputDecoration( errorStyle: const TextStyle(height: 0, fontSize: 0), labelStyle: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, color: _apiKeyError != null ? StreamChatTheme.of(context).colorTheme.accentError : StreamChatTheme.of(context) .colorTheme .textLowEmphasis, ), border: UnderlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none, ), fillColor: StreamChatTheme.of(context).colorTheme.inputBg, filled: true, labelText: _apiKeyError != null ? '${AppLocalizations.of(context).chatApiKey.toUpperCase()}: $_apiKeyError' : AppLocalizations.of(context).chatApiKey, ), textInputAction: TextInputAction.next, ), const SizedBox(height: 8), TextFormField( controller: _userIdController, onChanged: (_) { if (_userIdError != null) { setState(() { _userIdError = null; }); } }, validator: (value) { if (value!.isEmpty) { setState(() { _userIdError = AppLocalizations.of(context) .userIdError .toUpperCase(); }); return _userIdError; } return null; }, style: TextStyle( fontSize: 14, color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis, ), textInputAction: TextInputAction.next, decoration: InputDecoration( errorStyle: const TextStyle(height: 0, fontSize: 0), labelStyle: TextStyle( fontWeight: FontWeight.bold, fontSize: 14, color: _userIdError != null ? StreamChatTheme.of(context).colorTheme.accentError : StreamChatTheme.of(context) .colorTheme .textLowEmphasis, ), border: UnderlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none, ), fillColor: StreamChatTheme.of(context).colorTheme.inputBg, filled: true, labelText: _userIdError != null ? '${AppLocalizations.of(context).userId.toUpperCase()}: $_userIdError' : AppLocalizations.of(context).userId, ), ), const SizedBox(height: 8), TextFormField( onChanged: (_) { if (_userTokenError != null) { setState(() { _userTokenError = null; }); } }, controller: _userTokenController, validator: (value) { if (value!.isEmpty) { setState(() { _userTokenError = AppLocalizations.of(context) .userTokenError .toUpperCase(); }); return _userTokenError; } return null; }, style: TextStyle( fontSize: 14, color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis, ), textInputAction: TextInputAction.next, decoration: InputDecoration( errorStyle: const TextStyle(height: 0, fontSize: 0), labelStyle: TextStyle( fontWeight: FontWeight.bold, fontSize: 14, color: _userTokenError != null ? StreamChatTheme.of(context).colorTheme.accentError : StreamChatTheme.of(context) .colorTheme .textLowEmphasis, ), border: UnderlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none, ), fillColor: StreamChatTheme.of(context).colorTheme.inputBg, filled: true, labelText: _userTokenError != null ? '${AppLocalizations.of(context).userToken.toUpperCase()}: $_userTokenError' : AppLocalizations.of(context).userToken, ), ), const SizedBox(height: 8), TextFormField( controller: _usernameController, textInputAction: TextInputAction.done, decoration: InputDecoration( labelStyle: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, color: StreamChatTheme.of(context) .colorTheme .textLowEmphasis, ), border: UnderlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none, ), fillColor: StreamChatTheme.of(context).colorTheme.inputBg, filled: true, labelText: AppLocalizations.of(context).usernameOptional, ), ), const Spacer(), ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>( Theme.of(context).brightness == Brightness.light ? StreamChatTheme.of(context) .colorTheme .accentPrimary : Colors.white), elevation: MaterialStateProperty.all<double>(0), padding: MaterialStateProperty.all<EdgeInsets>( const EdgeInsets.symmetric(vertical: 16)), shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(26), ), ), ), onPressed: _login, child: Text( AppLocalizations.of(context).login, style: TextStyle( fontSize: 16, color: Theme.of(context).brightness != Brightness.light ? StreamChatTheme.of(context) .colorTheme .accentPrimary : Colors.white, ), ), ), const StreamVersion(), ], ), ), ); }, ), ); } }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/pages/pinned_messages_screen.dart
import 'package:example/utils/localizations.dart'; import 'package:example/routes/routes.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class PinnedMessagesScreen extends StatefulWidget { const PinnedMessagesScreen({super.key}); @override State<PinnedMessagesScreen> createState() => _PinnedMessagesScreenState(); } class _PinnedMessagesScreenState extends State<PinnedMessagesScreen> { late final controller = StreamMessageSearchListController( client: StreamChat.of(context).client, filter: Filter.in_( 'cid', [StreamChannel.of(context).channel.cid!], ), messageFilter: Filter.equal( 'pinned', true, ), sort: [ const SortOption( 'created_at', direction: SortOption.ASC, ), ], limit: 20, ); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: StreamChatTheme.of(context).colorTheme.barsBg, appBar: AppBar( elevation: 1, centerTitle: true, title: Text( AppLocalizations.of(context).pinnedMessages, style: TextStyle( color: StreamChatTheme.of(context).colorTheme.textHighEmphasis, fontSize: 16.0, ), ), leading: const StreamBackButton(), backgroundColor: StreamChatTheme.of(context).colorTheme.barsBg, ), body: StreamMessageSearchListView( controller: controller, emptyBuilder: (_) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ StreamSvgIcon.pin( size: 136.0, color: StreamChatTheme.of(context).colorTheme.disabled, ), const SizedBox(height: 16.0), Text( AppLocalizations.of(context).noPinnedItems, style: TextStyle( fontSize: 17.0, color: StreamChatTheme.of(context).colorTheme.textHighEmphasis, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 8.0), RichText( textAlign: TextAlign.center, text: TextSpan(children: [ TextSpan( text: '${AppLocalizations.of(context).longPressMessage} ', style: TextStyle( fontSize: 14.0, color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5), ), ), TextSpan( text: AppLocalizations.of(context).pinToConversation, style: TextStyle( fontSize: 14.0, fontWeight: FontWeight.bold, color: StreamChatTheme.of(context) .colorTheme .textHighEmphasis .withOpacity(0.5), ), ), ]), ), ], ), ); }, onMessageTap: (messageResponse) async { final client = StreamChat.of(context).client; final router = GoRouter.of(context); final message = messageResponse.message; final channel = client.channel( messageResponse.channel!.type, id: messageResponse.channel!.id, ); if (channel.state == null) { await channel.watch(); } router.pushNamed( Routes.CHANNEL_PAGE.name, pathParameters: Routes.CHANNEL_PAGE.params(channel), queryParameters: Routes.CHANNEL_PAGE.queryParams(message), ); }, ), ); } @override void dispose() { controller.dispose(); super.dispose(); } }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/pages/channel_page.dart
import 'package:collection/collection.dart'; import 'package:example/pages/thread_page.dart'; import 'package:example/routes/routes.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class ChannelPage extends StatefulWidget { final int? initialScrollIndex; final double? initialAlignment; final bool highlightInitialMessage; const ChannelPage({ Key? key, this.initialScrollIndex, this.initialAlignment, this.highlightInitialMessage = false, }) : super(key: key); @override State<ChannelPage> createState() => _ChannelPageState(); } class _ChannelPageState extends State<ChannelPage> { FocusNode? _focusNode; final StreamMessageInputController _messageInputController = StreamMessageInputController(); @override void initState() { _focusNode = FocusNode(); super.initState(); } @override void dispose() { _focusNode!.dispose(); super.dispose(); } void _reply(Message message) { _messageInputController.quotedMessage = message; WidgetsBinding.instance.addPostFrameCallback((timeStamp) { _focusNode!.requestFocus(); }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: StreamChatTheme.of(context).colorTheme.appBg, appBar: StreamChannelHeader( showTypingIndicator: false, onBackPressed: () => GoRouter.of(context).pop(), onImageTap: () async { final channel = StreamChannel.of(context).channel; final router = GoRouter.of(context); if (channel.memberCount == 2 && channel.isDistinct) { final currentUser = StreamChat.of(context).currentUser; final otherUser = channel.state!.members.firstWhereOrNull( (element) => element.user!.id != currentUser!.id, ); if (otherUser != null) { router.pushNamed( Routes.CHAT_INFO_SCREEN.name, pathParameters: Routes.CHAT_INFO_SCREEN.params(channel), extra: otherUser.user, ); } } else { GoRouter.of(context).pushNamed( Routes.GROUP_INFO_SCREEN.name, pathParameters: Routes.GROUP_INFO_SCREEN.params(channel), ); } }, ), body: Column( children: <Widget>[ Expanded( child: Stack( children: <Widget>[ StreamMessageListView( initialScrollIndex: widget.initialScrollIndex, initialAlignment: widget.initialAlignment, highlightInitialMessage: widget.highlightInitialMessage, onMessageSwiped: _reply, messageFilter: defaultFilter, messageBuilder: (context, details, messages, defaultMessage) { final router = GoRouter.of(context); return defaultMessage.copyWith( onReplyTap: _reply, onShowMessage: (m, c) async { final client = StreamChat.of(context).client; final message = m; final channel = client.channel( c.type, id: c.id, ); if (channel.state == null) { await channel.watch(); } router.goNamed( Routes.CHANNEL_PAGE.name, pathParameters: Routes.CHANNEL_PAGE.params(channel), queryParameters: Routes.CHANNEL_PAGE.queryParams(message), ); }, bottomRowBuilderWithDefaultWidget: ( context, message, defaultWidget, ) { return defaultWidget.copyWith( deletedBottomRowBuilder: (context, message) { return const StreamVisibleFootnote(); }, ); }, ); }, threadBuilder: (_, parentMessage) { return ThreadPage(parent: parentMessage!); }, ), Positioned( bottom: 0, left: 0, right: 0, child: Container( alignment: Alignment.centerLeft, color: StreamChatTheme.of(context) .colorTheme .appBg .withOpacity(.9), child: StreamTypingIndicator( padding: const EdgeInsets.symmetric( horizontal: 8, vertical: 4, ), style: StreamChatTheme.of(context) .textTheme .footnote .copyWith( color: StreamChatTheme.of(context) .colorTheme .textLowEmphasis), ), ), ), ], ), ), StreamMessageInput( focusNode: _focusNode, messageInputController: _messageInputController, onQuotedMessageCleared: () { _messageInputController.clearQuotedMessage(); }, ), ], ), ); } bool defaultFilter(Message m) { final currentUser = StreamChat.of(context).currentUser; final isMyMessage = m.user?.id == currentUser?.id; final isDeletedOrShadowed = m.isDeleted == true || m.shadowed == true; if (isDeletedOrShadowed && !isMyMessage) return false; return true; } }
0
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/pages/splash_screen.dart
import 'package:flutter/material.dart'; import 'package:lottie/lottie.dart'; mixin SplashScreenStateMixin<T extends StatefulWidget> on State<T> implements TickerProvider { late final _animationController = AnimationController( vsync: this, duration: const Duration( milliseconds: 1000, ), ); late final _scaleAnimationController = AnimationController( vsync: this, value: 0, duration: const Duration( milliseconds: 500, ), ); late final _circleAnimation = Tween( begin: 0.0, end: 1000.0, ).animate(CurvedAnimation( parent: _animationController, curve: Curves.easeInOut, )); late final _colorAnimation = ColorTween( begin: const Color(0xff005FFF), end: Colors.transparent, ).animate(CurvedAnimation( parent: _animationController, curve: Curves.easeInOut, )); late final _scaleAnimation = Tween( begin: 1.0, end: 1.5, ).animate(CurvedAnimation( parent: _scaleAnimationController, curve: Curves.easeInOutCubic, )); bool animationCompleted = false; void forwardAnimations() { _scaleAnimationController.forward().whenComplete(() { _animationController.forward(); }); } void _onAnimationComplete(AnimationStatus status) { if (status == AnimationStatus.completed) { setState(() { animationCompleted = true; }); } } @override void initState() { super.initState(); _animationController.addStatusListener(_onAnimationComplete); } @override void dispose() { _animationController.removeStatusListener(_onAnimationComplete); _animationController.dispose(); _scaleAnimationController.dispose(); super.dispose(); } Widget buildAnimation() => Stack( clipBehavior: Clip.none, alignment: Alignment.center, children: [ AnimatedBuilder( animation: _scaleAnimation, builder: (context, child) => Transform.scale(scale: _scaleAnimation.value, child: child), child: AnimatedBuilder( animation: _colorAnimation, builder: (context, child) { return DecoratedBox( decoration: BoxDecoration(color: _colorAnimation.value), child: Center( child: !_animationController.isAnimating ? child : const SizedBox(), ), ); }, child: RepaintBoundary( child: Lottie.asset( 'assets/floating_boat.json', alignment: Alignment.center, ), ), ), ), AnimatedBuilder( animation: _circleAnimation, builder: (context, snapshot) { return Transform.scale( scale: _circleAnimation.value, child: Container( width: 1.0, height: 1.0, decoration: BoxDecoration( color: Colors.white .withOpacity(1 - _animationController.value), shape: BoxShape.circle, ), ), ); }, ), ], ); }
0