repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/smart-home-app/lib/src/screens
mirrored_repositories/smart-home-app/lib/src/screens/splash_screen/splash_screen.dart
import 'package:flutter/material.dart'; import 'package:domus/config/size_config.dart'; import 'components/body.dart'; class SplashScreen extends StatelessWidget { static String routeName = '/splash-screen'; const SplashScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { SizeConfig().init(context); return const Scaffold( body: Body(), ); } }
0
mirrored_repositories/smart-home-app/lib/src/screens/splash_screen
mirrored_repositories/smart-home-app/lib/src/screens/splash_screen/components/body.dart
import 'package:domus/config/size_config.dart'; import 'package:domus/src/screens/login_screen/login_screen.dart'; import 'package:flutter/material.dart'; class Body extends StatelessWidget { const Body({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.symmetric( horizontal: 14, vertical: 14, ), decoration: const BoxDecoration( color: Color(0xFF464646), ), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ SizedBox( height: getProportionateScreenHeight(20), ), Material( child: Image.asset('assets/images/splash_img.png'), color: Colors.transparent, ), Text( 'Sweet & Smart Home', style: Theme.of(context).textTheme.headline1!.copyWith( color: Colors.white, ), ), Text( 'Smart Home can change\nway you live in the future', style: Theme.of(context).textTheme.headline3!.copyWith( color: const Color(0xFFBDBDBD), ), ), ElevatedButton( onPressed: () { Navigator.of(context).pushReplacementNamed(LoginScreen.routeName); }, child: Text( 'Get Started', style: Theme.of(context).textTheme.headline2, ), style: ElevatedButton.styleFrom( elevation: 0, padding: EdgeInsets.symmetric( horizontal: getProportionateScreenWidth(70), vertical: getProportionateScreenHeight(15), ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), // <-- Radius ), ), ) ], ), ); } }
0
mirrored_repositories/smart-home-app/lib/src/screens
mirrored_repositories/smart-home-app/lib/src/screens/menu_page/menu_screen.dart
import 'package:flutter/material.dart'; import 'package:domus/src/screens/menu_page/components/body.dart'; class Menu extends StatelessWidget { static String routeName = '/menu-screen'; const Menu({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const Drawer( child: Scaffold( backgroundColor: Color(0xFFF2F2F2), body: Body(), ), ); } }
0
mirrored_repositories/smart-home-app/lib/src/screens/menu_page
mirrored_repositories/smart-home-app/lib/src/screens/menu_page/components/menu_list.dart
import 'package:domus/src/screens/menu_page/components/list_tile.dart'; import 'package:domus/src/screens/stats_screen/stats_screen.dart'; import 'package:domus/src/screens/savings_screen/savings_screen.dart'; import 'package:flutter/material.dart'; import 'package:domus/config/size_config.dart'; class MenuList extends StatelessWidget { const MenuList({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Column( children: [ //MenuListItem is custom tile in list_tile file MenuListItems( iconPath: 'assets/icons/menu_icons/stats.svg', itemName: 'Stats', function: () => Navigator.of(context).pushNamed( StatsScreen.routeName, ), ), SizedBox( height: getProportionateScreenHeight(10), ), MenuListItems( iconPath: 'assets/icons/menu_icons/devices.svg', itemName: 'Devices', function: () {}, ), SizedBox( height: getProportionateScreenHeight(10), ), MenuListItems( iconPath: 'assets/icons/menu_icons/savings.svg', itemName: 'Savings', function: () { Navigator.of(context).pushNamed(SavingsScreen.routeName); }, ), SizedBox( height: getProportionateScreenHeight(10), ), MenuListItems( iconPath: 'assets/icons/menu_icons/settings.svg', itemName: 'Settings', function: () {}, ), SizedBox( height: getProportionateScreenHeight(10), ), MenuListItems( iconPath: 'assets/icons/menu_icons/notifications.svg', itemName: 'Notification', function: () {}, ), SizedBox( height: getProportionateScreenHeight(10), ), MenuListItems( iconPath: 'assets/icons/menu_icons/faq.svg', itemName: 'FAQ', function: () {}, ), ], ); } }
0
mirrored_repositories/smart-home-app/lib/src/screens/menu_page
mirrored_repositories/smart-home-app/lib/src/screens/menu_page/components/list_tile.dart
import 'package:flutter/material.dart'; import 'package:domus/config/size_config.dart'; import 'package:flutter_svg/svg.dart'; class MenuListItems extends StatelessWidget { final String iconPath; final String itemName; final VoidCallback function; const MenuListItems({ Key? key, required this.iconPath, required this.itemName, required this.function, }) : super(key: key); @override Widget build(BuildContext context) { return InkWell( onTap: function, child: Padding( padding: const EdgeInsets.all(15.0), child: Row( children: [ SvgPicture.asset(iconPath), SizedBox( width: getProportionateScreenWidth(25), ), Text( itemName, style: const TextStyle( fontSize: 24, fontWeight: FontWeight.w300, ), ), ], ), ), ); } }
0
mirrored_repositories/smart-home-app/lib/src/screens/menu_page
mirrored_repositories/smart-home-app/lib/src/screens/menu_page/components/body.dart
import 'package:flutter/material.dart'; import 'package:domus/config/size_config.dart'; import 'package:domus/src/screens/menu_page/components/menu_list.dart'; class Body extends StatelessWidget { const Body({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.only( left: getProportionateScreenWidth(20), right: getProportionateScreenWidth(20), bottom: getProportionateScreenHeight(12), ), child: Column( children: [ SizedBox( height: getProportionateScreenHeight(50), ), Padding( padding: const EdgeInsets.only(left: 7, right: 7), child: Column( children: [ Row( children: [ const Text( 'Menu', style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold), ), const Spacer(), InkWell( onTap: () { Navigator.of(context).pop(); }, child: const Icon( Icons.close, size: 35, ), ), ], ), SizedBox( height: getProportionateScreenHeight(80), ), const MenuList(), ], ), ), ], ) ); } }
0
mirrored_repositories/smart-home-app/lib
mirrored_repositories/smart-home-app/lib/constant/constant.dart
import 'package:domus/src/models/color_model.dart'; import 'package:flutter/material.dart'; ///Constants for custom dialog widget class Constants { Constants._(); static const double padding = 20; static const double avatarRadius = 45; static List<Color> dotColors1 = [ const Color(0xFF9659D4), const Color(0xFF6EADFC), const Color(0xFFFF427D), const Color(0xFF61D1EB), const Color(0xFFFF4C4B), ]; static List<ColorModel> colors = [ ColorModel( color: const Color(0xFF9659D4), image: 'assets/images/purple.png', index: 0), ColorModel( color: const Color(0xFF6EADFC), image: 'assets/images/blue.png', index: 1), ColorModel( color: const Color(0xFFFF427D), image: 'assets/images/pink.png', index: 2), ColorModel( color: const Color(0xFF61D1EB), image: 'assets/images/sky_blue.png', index: 3), ColorModel( color: const Color(0xFFFF4C4B), image: 'assets/images/orange.png', index: 4), ]; static List<Color> dotColors2 = [ const Color(0xFFEFF0FB), const Color(0xFFFCAE39), const Color(0xFF6FB86D), const Color(0xFF7054FF), const Color(0xFFFFF35C), ]; }
0
mirrored_repositories/smart-home-app/lib
mirrored_repositories/smart-home-app/lib/provider/base_model.dart
import 'package:domus/enum/view_state.dart'; import 'package:domus/service/navigation_service.dart'; import 'package:flutter/material.dart'; import 'getit.dart'; class BaseModel extends ChangeNotifier { final navigationService = getIt<NavigationService>(); ViewState _state = ViewState.idle; ViewState get state => _state; void setState(ViewState viewState) { _state = viewState; notifyListeners(); } }
0
mirrored_repositories/smart-home-app/lib
mirrored_repositories/smart-home-app/lib/provider/base_view.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'base_model.dart'; import 'getit.dart'; class BaseView<T extends BaseModel> extends StatefulWidget { final Widget Function(BuildContext context, T model, Widget? child) builder; final Function(T)? onModelReady; final Function(T)? onModelDisposed; final Widget? child; const BaseView({ Key? key, required this.builder, this.onModelReady, this.child, this.onModelDisposed, }) : super(key: key); @override _BaseViewState<T> createState() => _BaseViewState<T>(); } class _BaseViewState<T extends BaseModel> extends State<BaseView<T>> { T model = getIt<T>(); @override void initState() { if (widget.onModelReady != null) { widget.onModelReady!(model); } super.initState(); } @override void dispose() { super.dispose(); if (widget.onModelDisposed != null) { widget.onModelDisposed!(model); } } @override Widget build(BuildContext context) { return ChangeNotifierProvider.value( value: model, child: Consumer<T>( builder: widget.builder, child: widget.child, ), ); } }
0
mirrored_repositories/smart-home-app/lib
mirrored_repositories/smart-home-app/lib/provider/getit.dart
import 'package:domus/service/navigation_service.dart'; import 'package:domus/view/home_screen_view_model.dart'; import 'package:domus/view/smart_ac_view_model.dart'; import 'package:domus/view/smart_light_view_model.dart'; import 'package:domus/view/smart_speaker_view_model.dart'; import 'package:domus/view/smart_fan_view_model.dart'; import 'package:domus/view/smart_tv_view_model.dart'; import 'package:get_it/get_it.dart'; GetIt getIt = GetIt.instance; void setupLocator() { getIt.registerLazySingleton(() => NavigationService()); getIt.registerFactory(() => HomeScreenViewModel()); getIt.registerFactory(() => SmartLightViewModel()); getIt.registerFactory(() => SmartACViewModel()); getIt.registerFactory(() => SmartSpeakerViewModel()); getIt.registerFactory(() => SmartFanViewModel()); getIt.registerFactory(() => SmartTvViewModel()); }
0
mirrored_repositories/smart-home-app/lib
mirrored_repositories/smart-home-app/lib/enum/view_state.dart
enum ViewState { idle, busy }
0
mirrored_repositories/smart-home-app
mirrored_repositories/smart-home-app/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:domus/provider/getit.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:domus/main.dart'; void main() { testWidgets('My test', (WidgetTester tester) async { setupLocator(); // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); }); }
0
mirrored_repositories/Animated_Menu_in_Flutter
mirrored_repositories/Animated_Menu_in_Flutter/lib/main.dart
import 'package:animated_radial_menu/animated_radial_menu.dart'; import 'package:flutter/material.dart'; void main() => runApp(MaterialApp( home: RadialMenuExample(), )); class RadialMenuExample extends StatelessWidget { const RadialMenuExample({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.black87, appBar: AppBar( backgroundColor: Colors.black45, title: Text("Animated Radial Menu"), centerTitle: true, ), body: RadialMenu(children: [ RadialButton( icon: Icon(Icons.ac_unit), buttonColor: Colors.teal, onPress: () => Navigator.push( context, MaterialPageRoute(builder: (_) => TargetScreen()))), RadialButton( icon: Icon(Icons.camera_alt), buttonColor: Colors.green, onPress: () => Navigator.push( context, MaterialPageRoute(builder: (_) => TargetScreen()))), RadialButton( icon: Icon(Icons.map), buttonColor: Colors.orange, onPress: () => Navigator.push( context, MaterialPageRoute(builder: (_) => TargetScreen()))), RadialButton( icon: Icon(Icons.access_alarm), buttonColor: Colors.indigo, onPress: () => Navigator.push( context, MaterialPageRoute(builder: (_) => TargetScreen()))), RadialButton( icon: Icon(Icons.watch), buttonColor: Colors.pink, onPress: () => Navigator.push( context, MaterialPageRoute(builder: (_) => TargetScreen()))), ] ), ); } } class TargetScreen extends StatelessWidget { const TargetScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Target Screen")), ); } }
0
mirrored_repositories/Animated_Menu_in_Flutter
mirrored_repositories/Animated_Menu_in_Flutter/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:radial_animation/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/flutter_signin_screen_ui
mirrored_repositories/flutter_signin_screen_ui/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:sign_ui/core/app_theme.dart'; import 'screens/sign_screen.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return ScreenUtilInit( designSize: const Size(1080, 2340), minTextAdapt: true, splitScreenMode: true, builder: (context, child) => MaterialApp( debugShowCheckedModeBanner: false, title: 'Material App', theme: AppTheme.light, home: const SignScreen(), ), ); } }
0
mirrored_repositories/flutter_signin_screen_ui/lib
mirrored_repositories/flutter_signin_screen_ui/lib/widgets/rounded_icon_button.dart
import 'package:flutter/material.dart'; import 'package:flutter_hex_color/flutter_hex_color.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; class RoundedIconButton extends GestureDetector { RoundedIconButton({ Key? key, VoidCallback? onTap, required String text, }) : super( key: key, onTap: onTap, child: Container( width: double.infinity, height: 150.h, decoration: BoxDecoration( borderRadius: BorderRadius.circular(100).w, color: HexColor('#333333'), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: const EdgeInsets.only(left: 70).r, child: Text( text, style: TextStyle( fontSize: 40.sp, color: HexColor('#FFFFFF'), ), ), ), Container( alignment: Alignment.center, width: 132.w, height: 132.h, decoration: BoxDecoration( shape: BoxShape.circle, color: HexColor('#F9BD15'), ), child: Icon( Icons.arrow_forward_ios, size: 56.sp, color: HexColor('#FFFFFF'), ), ), ], ), ), ); }
0
mirrored_repositories/flutter_signin_screen_ui/lib
mirrored_repositories/flutter_signin_screen_ui/lib/widgets/custom_input_decoration.dart
import 'package:flutter/material.dart'; import 'package:flutter_hex_color/flutter_hex_color.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; InputDecoration customInputDecoration() { return InputDecoration( hintStyle: TextStyle( fontSize: 42.sp, color: HexColor('#333333'), ), contentPadding: const EdgeInsets.symmetric(horizontal: 47, vertical: 49).r, ); }
0
mirrored_repositories/flutter_signin_screen_ui/lib
mirrored_repositories/flutter_signin_screen_ui/lib/core/app_theme.dart
import 'package:flutter/material.dart'; import 'package:flutter_hex_color/flutter_hex_color.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:google_fonts/google_fonts.dart'; class AppTheme { const AppTheme._(); static final ThemeData light = ThemeData( fontFamily: GoogleFonts.inter().fontFamily, scaffoldBackgroundColor: HexColor('#FFFFFF'), inputDecorationTheme: InputDecorationTheme( filled: true, fillColor: HexColor('#F5F5F5'), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(40).w, borderSide: const BorderSide( width: 0, color: Colors.transparent, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(40).w, borderSide: const BorderSide( width: 0, color: Colors.transparent, ), ), errorBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(40).w, borderSide: const BorderSide(), ), hintStyle: TextStyle( color: HexColor('#333333'), fontSize: 42.sp, ), contentPadding: const EdgeInsets.symmetric( horizontal: 47, vertical: 49, ).r, ), ); }
0
mirrored_repositories/flutter_signin_screen_ui/lib
mirrored_repositories/flutter_signin_screen_ui/lib/screens/sign_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_hex_color/flutter_hex_color.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:sign_ui/widgets/custom_input_decoration.dart'; import '../widgets/rounded_icon_button.dart'; class SignScreen extends HookWidget { const SignScreen({super.key}); @override Widget build(BuildContext context) { final height = MediaQuery.of(context).viewPadding.top; final controller = useTabController(initialLength: 2); final currentIndex = useState(0); final visiblePassword = useState(true); void switchForm(int value) { currentIndex.value = value; } return Scaffold( body: SafeArea( child: SingleChildScrollView( padding: EdgeInsets.symmetric( horizontal: 72, vertical: (146 - height), ).r, reverse: true, physics: const BouncingScrollPhysics(), child: Form( child: Column( children: [ _headerTitle(), SizedBox(height: 80.h), _imageSection(), SizedBox(height: 127.h), _tabBarSection( controller: controller, onTap: (value) => switchForm(value)), SizedBox(height: 80.h), [ _loginSection(visiblePassword), _signUpSection(visiblePassword), ][currentIndex.value], ], ), ), ), ), ); } Widget _loginSection(ValueNotifier<bool> visible) => Column( children: [ TextFormField( cursorColor: HexColor('#F9BD15'), decoration: customInputDecoration().copyWith(hintText: '郵箱/手機號'), ), SizedBox(height: 70.h), TextFormField( cursorColor: HexColor('#F9BD15'), obscureText: visible.value, keyboardType: TextInputType.visiblePassword, decoration: customInputDecoration().copyWith( hintText: '密碼:', suffixIcon: IconButton( splashColor: Colors.transparent, onPressed: () => visible.value = !visible.value, icon: Icon( visible.value ? Icons.visibility_off : Icons.visibility, color: visible.value ? HexColor('#A0A7BA') : HexColor('#F9BD15'), ), ), ), ), SizedBox(height: 44.h), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Container( alignment: Alignment.center, margin: const EdgeInsets.only(right: 16).r, width: 56.w, height: 56.h, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10).w, color: HexColor('#F9BD15'), ), child: Icon( Icons.check, color: Colors.white, size: 50.sp, ), ), Text( '自动登录', textAlign: TextAlign.center, style: TextStyle( color: HexColor('#A0A7BA'), fontSize: 40.sp, ), ), ], ), Text( '忘记密码?', style: TextStyle(color: HexColor('#A0A7BA'), fontSize: 40.sp), ), ], ), SizedBox(height: 130.h), RoundedIconButton(text: '登錄'), ], ); Widget _signUpSection(ValueNotifier<bool> visible) => Column( children: [ TextFormField( cursorColor: HexColor('#F9BD15'), decoration: customInputDecoration().copyWith(hintText: '郵箱/手機號'), ), SizedBox(height: 70.h), TextFormField( cursorColor: HexColor('#F9BD15'), obscureText: visible.value, keyboardType: TextInputType.visiblePassword, decoration: customInputDecoration().copyWith( hintText: '密碼:', suffixIcon: IconButton( splashColor: Colors.transparent, onPressed: () => visible.value = !visible.value, icon: Icon( visible.value ? Icons.visibility_off : Icons.visibility, color: visible.value ? HexColor('#A0A7BA') : HexColor('#F9BD15'), ), ), ), ), SizedBox(height: 70.h), TextFormField( cursorColor: HexColor('#F9BD15'), obscureText: visible.value, keyboardType: TextInputType.visiblePassword, decoration: customInputDecoration().copyWith( hintText: '確認密碼:', suffixIcon: IconButton( splashColor: Colors.transparent, onPressed: () => visible.value = !visible.value, icon: Icon( visible.value ? Icons.visibility_off : Icons.visibility, color: visible.value ? HexColor('#A0A7BA') : HexColor('#F9BD15'), ), ), ), ), SizedBox(height: 200.h), RoundedIconButton(text: '注冊'), ], ); TabBar _tabBarSection({ required TabController controller, required Function(int value) onTap, }) { return TabBar( onTap: onTap, splashFactory: NoSplash.splashFactory, labelPadding: const EdgeInsets.only(bottom: 24).r, physics: const NeverScrollableScrollPhysics(), indicatorColor: HexColor('#F9BD15'), indicatorWeight: 2, controller: controller, labelColor: HexColor('#F9BD15'), unselectedLabelColor: HexColor('#333333'), labelStyle: TextStyle( fontSize: 46.sp, fontWeight: FontWeight.w700, ), tabs: const [ Text('登錄'), Text('注冊'), ], ); } Container _imageSection() { return Container( padding: const EdgeInsets.only(top: 215, right: 105, left: 94).r, alignment: Alignment.bottomCenter, width: double.infinity, height: 851.h, decoration: BoxDecoration( color: HexColor('#F5F5F5'), borderRadius: BorderRadius.circular(100).w, ), child: Image.asset( 'assets/images/Group.png', fit: BoxFit.cover, ), ); } Text _headerTitle() { return Text( '😄歡迎回來😄', style: TextStyle( fontSize: 70.sp, color: HexColor('#333333'), ), ); } }
0
mirrored_repositories/flutter_signin_screen_ui
mirrored_repositories/flutter_signin_screen_ui/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility in the flutter_test package. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:sign_ui/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories
mirrored_repositories/chat_room/exp.dart
import 'package:pointycastle/api.dart' as crypto; import 'package:rsa_encrypt/rsa_encrypt.dart'; void main() async { //Future to hold our KeyPair Future<crypto.AsymmetricKeyPair> futureKeyPair; //to store the KeyPair once we get data from our future crypto.AsymmetricKeyPair keyPair; Future<crypto.AsymmetricKeyPair<crypto.PublicKey, crypto.PrivateKey>> getKeyPair() { var helper = RsaKeyHelper(); var a = helper.computeRSAKeyPair(helper.getSecureRandom()); return a; } futureKeyPair = getKeyPair(); keyPair = await futureKeyPair; var encryption = encrypt('bhautiik', keyPair.publicKey); print('<><><<<${encryption.runtimeType}'); var decryption = decrypt(encryption, keyPair.privateKey); print(decryption); }
0
mirrored_repositories/chat_room
mirrored_repositories/chat_room/lib/main.dart
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'screens/chat_screen.dart'; import 'screens/login_screen.dart'; import 'screens/registration_screen.dart'; import 'screens/welcome_screen.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); runApp(MyApp()); } class MyApp extends StatelessWidget { final Future<FirebaseApp> _initialization = Firebase.initializeApp(); @override Widget build(BuildContext context) { return FutureBuilder( future: _initialization, builder: (context, snapshot) { if (snapshot.hasError) { return Container( color: Colors.red, ); } if (snapshot.connectionState == ConnectionState.done) { return MaterialApp( initialRoute: WelcomeScreen.id, routes: { ChatScreen.id: (context) => ChatScreen(), LoginScreen.id: (context) => LoginScreen(), WelcomeScreen.id: (context) => WelcomeScreen(), RegistrationScreen.id: (context) => RegistrationScreen(), }, ); } return Container( color: Colors.lightBlueAccent, ); }, ); } }
0
mirrored_repositories/chat_room
mirrored_repositories/chat_room/lib/constents.dart
import 'package:flutter/material.dart'; const kTextFieldDecoration = InputDecoration( hintText: 'Value', border: OutlineInputBorder( borderRadius: BorderRadius.all( Radius.circular(30), ), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.blueAccent, width: 1.0), borderRadius: BorderRadius.all( Radius.circular(30), ), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide( color: Colors.blueAccent, width: 2.0, ), borderRadius: BorderRadius.all( Radius.circular(32), ), ), filled: true, );
0
mirrored_repositories/chat_room/lib
mirrored_repositories/chat_room/lib/component/rsa_encrypt_tool.dart
import 'package:flutter/cupertino.dart'; import 'package:pointycastle/api.dart' as crypto; import 'package:rsa_encrypt/rsa_encrypt.dart'; class EncryptAndDecrypt { static Future<String> encryptMessage( {String plainText, String encryptedText, @required bool doEncrypt}) async { Future<crypto.AsymmetricKeyPair> futureKeyPair; //to store the KeyPair once we get data from our future crypto.AsymmetricKeyPair keyPair; Future<crypto.AsymmetricKeyPair<crypto.PublicKey, crypto.PrivateKey>> getKeyPair() { var helper = RsaKeyHelper(); return helper.computeRSAKeyPair(helper.getSecureRandom()); } futureKeyPair = getKeyPair(); keyPair = await futureKeyPair; var encryptedMessage = encrypt(plainText, keyPair.publicKey); var decryptedMessage = decrypt(encryptedText, keyPair.privateKey); if (doEncrypt) { return encryptedMessage; } if (!doEncrypt) { return decryptedMessage; } return 'Somthing Went Wrong with encryption'; } static Future<String> decryptMessage(String message) async { Future<crypto.AsymmetricKeyPair> futureKeyPair; //to store the KeyPair once we get data from our future crypto.AsymmetricKeyPair keyPair; Future<crypto.AsymmetricKeyPair<crypto.PublicKey, crypto.PrivateKey>> getKeyPair() { var helper = RsaKeyHelper(); return helper.computeRSAKeyPair(helper.getSecureRandom()); } futureKeyPair = getKeyPair(); keyPair = await futureKeyPair; String decryptedMessage = decrypt(message, keyPair.privateKey); return decryptedMessage; } }
0
mirrored_repositories/chat_room/lib
mirrored_repositories/chat_room/lib/component/components.dart
import 'package:flutter/material.dart'; import 'package:sign_button/sign_button.dart'; import '../constents.dart'; import '../screens/chat_screen.dart'; import '../screens/login_screen.dart'; import '../screens/registration_screen.dart'; import '../screens/welcome_screen.dart'; /// This Components can be use in App to implement some features in the App /// RoundedButton is a Button Skeleton widget Of the Login And Register Button /// it's take Arguments as Color(Color),buttonText(String),onPressed(Function)And googleButton(bool) /// and create a Button Widget according to it's given Argument class RoundedButton extends StatelessWidget { const RoundedButton({ this.color, this.buttonText, this.onPressed, this.googleButton, Key key, }) : super(key: key); final Color color; final buttonText; final Function onPressed; final bool googleButton; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(8.0), child: !googleButton ? Material( elevation: 5.0, borderRadius: BorderRadius.all( Radius.circular(30), ), color: color, child: MaterialButton( onPressed: onPressed, minWidth: 250.0, child: Text(buttonText), ), ) : SignInButton( buttonType: ButtonType.google, onPressed: onPressed, buttonSize: ButtonSize.medium, ), ); } } /// this is Button Class /// this class have a different methods for different Types of Button /// Each method returns Rounded Button According to given attributes /// like loginButton RegisterButton and Google SignIn Button class Buttons { final Function onPressed; Buttons({this.onPressed}); /// Login Button for All Screens /// RoundedButton loginButton() { return RoundedButton( color: Colors.lightBlueAccent, buttonText: 'Login', onPressed: onPressed, googleButton: false, ); } RoundedButton registerButton() { return RoundedButton( buttonText: 'Register', color: Colors.lightBlue, onPressed: onPressed, googleButton: false, ); } RoundedButton googleSignIn() { return RoundedButton( googleButton: true, color: Colors.blue, buttonText: 'SignIn With Google', onPressed: onPressed, ); } } /// this is a ScaffoldAppBar Class /// this class contain different AppBar for different Screen class ScaffoldAppBar { final String appbarID; ScaffoldAppBar({@required this.appbarID}); AppBar appBar({Function onPressed}) { if (appbarID == WelcomeScreen.id) { return AppBar( title: Text('Welcome to ChatRoom'), ); } if (appbarID == LoginScreen.id) { return AppBar( title: Text('ChatRoom Login'), ); } if (appbarID == RegistrationScreen.id) { return AppBar( title: Text('ChatRoom Register'), ); } if (appbarID == ChatScreen.id) { return AppBar( actions: [FlatButton(onPressed: onPressed, child: Text('SignOut'))], title: Text('ChatRoom ChatField'), ); } return AppBar( title: Text('ChatRoom'), ); } } /// this is InputTextFields class or Widget /// the class contain Two TextField Widgets /// TextFields are used for take input from the user and Store value to the variable class InputTextFields extends StatelessWidget { final onChangedEmail; final onChangedPass; InputTextFields( {@required this.onChangedEmail, @required this.onChangedPass}); @override Widget build(BuildContext context) { return Container( child: Column( children: [ Padding( padding: const EdgeInsets.all(8.0), child: TextField( keyboardType: TextInputType.emailAddress, textAlign: TextAlign.center, decoration: kTextFieldDecoration.copyWith(hintText: 'Enter Your Email'), onChanged: onChangedEmail, ), ), Padding( padding: const EdgeInsets.all(8.0), child: TextField( obscureText: true, textAlign: TextAlign.center, decoration: kTextFieldDecoration.copyWith( hintText: 'Enter Your Password'), onChanged: onChangedPass, ), ), ], ), ); } } /// this is the LogoBox Widget /// it's contain logo(Image from assets) /// the image is a child of it's parent Widget Container /// the container it's self child of hero widget /// the Hero Widget is responsible for animate logo in Different Screens class LogoBox extends StatelessWidget { final double height; LogoBox({this.height}); @override Widget build(BuildContext context) { return Hero( tag: 'logo', child: Container( margin: EdgeInsets.all(20), height: height, child: Image.asset('assets/images/logo.png'), ), ); } }
0
mirrored_repositories/chat_room/lib
mirrored_repositories/chat_room/lib/screens/registration_screen.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:modal_progress_hud/modal_progress_hud.dart'; import '../component/components.dart'; import 'chat_screen.dart'; class RegistrationScreen extends StatelessWidget { static const String id = 'registrationScreen'; @override Widget build(BuildContext context) { return Scaffold( appBar: ScaffoldAppBar(appbarID: id).appBar(), /// Registration Screen AppBar body: RegistrationBody(), /// Registration Screen Body ); } } class RegistrationBody extends StatefulWidget { @override _RegistrationBodyState createState() => _RegistrationBodyState(); } class _RegistrationBodyState extends State<RegistrationBody> { FirebaseAuth _auth = FirebaseAuth.instance; /// Firebase Authentication Instance bool inSyncCall = false; String email; String password; @override Widget build(BuildContext context) { return ModalProgressHUD( /// Loading Indicator shows when Button Pushed inAsyncCall: inSyncCall, child: Container( /// Whole Body is fitted in this Container color: Colors.black12, child: ListView( // mainAxisAlignment: MainAxisAlignment.center, children: [ LogoBox( /// App Logo Shows height: 200, ), InputTextFields( /// Text Fields Are Take user's input and Store value in variable onChangedEmail: (value) => email = value, onChangedPass: (value) => password = value), Buttons(onPressed: createNewUser).registerButton(), Divider(height: 20), Center( child: Text('OR'), ), /// /// Bellow Button is Google SignIn Button /// Buttons(onPressed: () async { setState(() { inSyncCall = true; }); UserCredential creadential = await signInWithGoogle(); if (creadential.user.email != null) { Navigator.pushNamed( context, ChatScreen.id, ); } setState(() { inSyncCall = false; }); }).googleSignIn(), ], ), ), ); } /// following method is Create new user With Email And Password void createNewUser() async { setState(() { inSyncCall = true; }); try { UserCredential userCredential = await _auth .createUserWithEmailAndPassword(email: email, password: password); userCredential != null ? Navigator.pushNamed(context, ChatScreen.id) : print('Usercraed NULL'); } catch (e) { } setState(() { inSyncCall = false; }); } /// following Method is SignIn with Google and return UserCredential Future<UserCredential> signInWithGoogle() async { // 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 GoogleAuthCredential credential; credential = GoogleAuthProvider.credential( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); // Once signed in, return the UserCredential return await FirebaseAuth.instance.signInWithCredential(credential); } }
0
mirrored_repositories/chat_room/lib
mirrored_repositories/chat_room/lib/screens/welcome_screen.dart
import 'package:flutter/material.dart'; import 'package:modal_progress_hud/modal_progress_hud.dart'; import '../component/components.dart'; import '../screens/login_screen.dart'; import '../screens/registration_screen.dart'; class WelcomeScreen extends StatelessWidget { static const String id = 'WelcomeScreen'; @override Widget build(BuildContext context) { return Scaffold( appBar: ScaffoldAppBar(appbarID: WelcomeScreen.id).appBar(), body: WelcomeScreenBody(), ); } } class WelcomeScreenBody extends StatefulWidget { @override _WelcomeScreenBodyState createState() => _WelcomeScreenBodyState(); } class _WelcomeScreenBodyState extends State<WelcomeScreenBody> with SingleTickerProviderStateMixin { bool inSyncCall = false; AnimationController controller; AnimationController controllerText; double textAnimationValue; double mainContainerColor; AnimationStatus animationStatus; @override void initState() { animation(); super.initState(); } @override Widget build(BuildContext context) { return ModalProgressHUD( /// loading indicator show when button pressed inAsyncCall: inSyncCall, child: Container( color: Colors.black12.withOpacity(mainContainerColor ?? 1), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Padding( padding: const EdgeInsets.all(15.0), child: Row( /// This row Shows App's Logo and text children: [ LogoBox( height: animationStatus != AnimationStatus.dismissed ? (mainContainerColor ?? 1) * 100 : 50), SizedBox( width: 10, ), Expanded( child: Text( 'ChatRoom', style: TextStyle(fontSize: textAnimationValue), ), ), ], ), ), Container( margin: EdgeInsets.all(15), child: Text( 'You can register or Login your self', style: TextStyle(color: Colors.grey), ), ), /// Log in Button push screen to Login Screen Buttons(onPressed: () { Navigator.pushNamed(context, LoginScreen.id); }).loginButton(), /// Register Button Push Screen to Registration Screen Buttons( onPressed: () { Navigator.pushNamed(context, RegistrationScreen.id); }, ).registerButton(), ], ), ), ); } void animation() { controller = AnimationController( lowerBound: 0.2, vsync: this, duration: Duration(seconds: 2), reverseDuration: Duration(seconds: 2), ); controller.forward(); controller.addListener(() { setState(() { mainContainerColor = controller.value; }); }); controller.addStatusListener( (status) { if (status == AnimationStatus.completed) { controller.reverse(); controller.addListener(() { setState(() { mainContainerColor = controller.value; }); }); } }, ); controller.addStatusListener((status) { if (status == AnimationStatus.dismissed) { if (status == AnimationStatus.dismissed) { animationStatus = status; } } }); } }
0
mirrored_repositories/chat_room/lib
mirrored_repositories/chat_room/lib/screens/chat_screen.dart
import 'package:chat_room/component/components.dart'; import 'package:chat_room/constents.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; /// this is the ChatScreen /// the ChatScreen Displays Text Messages to the screen /// the text messages are Stored in Firebase Collection /// user also send message to the collection class ChatScreen extends StatelessWidget { static const String id = 'chatScreen'; @override Widget build(BuildContext context) { /// signOut method for user signOut /// and pop the back of the Screen signOut() { FirebaseAuth.instance.signOut(); Navigator.pop(context); } return Scaffold( /// this is ChatScreenAppBar AppBar Comes from ScaffoldAppBar class ScaffoldAppBar declared in Components.dart file appBar: ScaffoldAppBar(appbarID: id).appBar(onPressed: signOut), /// this is ChatScreen body ChatBody is declared bellow body: ChatBody(), ); } } /// ChatBody// class ChatBody extends StatefulWidget { @override _ChatBodyState createState() => _ChatBodyState(); } class _ChatBodyState extends State<ChatBody> { TextEditingController controller = TextEditingController(); /// this is Collection Reference of our message database in Firebase Firestore CollectionReference messages = FirebaseFirestore.instance.collection('messages'); String messageText; @override Widget build(BuildContext context) { /// << getUserName >> method return current name of the user String userName = getUserName(); /// this line ordered message list according to 'dateTime' field in collection var snapshots = messages .where('dateTime') .orderBy('dateTime', descending: false) .snapshots(); return Container( /// this Container Contain whole body of the screen color: Colors.black12, child: Column( children: [ Expanded( child: Container( child: StreamBuilder<QuerySnapshot>( /// StreamBuilder takes a Future and prossed its value /// and build a new widget /// the future value are used in new build widgets /// in this case the Text message And name of the Sender are future value coming form firebase stream: snapshots, builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (snapshot.hasError) { return Text('Somthing went wrong'); } if (snapshot.connectionState == ConnectionState.waiting) { return Text('Waiting'); } var maessages = snapshot.data.docs.reversed; return Material( color: Colors.black12, child: Padding( padding: const EdgeInsets.all(8.0), child: ListView( reverse: true, // crossAxisAlignment: CrossAxisAlignment.stretch, children: maessages.map((DocumentSnapshot document) { String messageText = document.data()['messageText']; String sender = document.data()['sender']; bool itsMe = false; itsMe = sender == userName ?? true; return Column( crossAxisAlignment: itsMe ? CrossAxisAlignment.end : CrossAxisAlignment.start, children: [ Text( '$sender', style: TextStyle(color: Colors.grey, fontSize: 12), ), // SizedBox( // height: 10, // ), MessageBubble( messageText: messageText, itsMe: itsMe, ), ], ); }).toList(), ), ), ); }, )), ), Container( /// this container Contain TextField and FlatButton /// TextField for take input and store value to variable /// and Button use for send new message in database color: Colors.black12, child: Row( children: [ Expanded( child: TextField( controller: controller, onChanged: (value) => messageText = value, decoration: kTextFieldDecoration.copyWith(hintText: 'Messages'), ), ), FlatButton( onPressed: () { sendMessage(userName); }, child: Text( 'Send', style: TextStyle(fontSize: 20, color: Colors.blue), ), ), ], ), ), Container( height: 5, color: Colors.black12, ) ], ), ); } /// this method return current user's User name String getUserName() { FirebaseAuth _auth = FirebaseAuth.instance; var userName = _auth.currentUser.email; print('<<<<<<<$userName>>>'); return userName; } /// this method send new message to the database Future<void> sendMessage(String sender) { int dateTime = Timestamp.now().microsecondsSinceEpoch; return messages.add({ 'messageText': messageText, 'sender': sender, 'dateTime': dateTime }).then((value) { print('message Added'); controller.clear(); }).catchError( (onError) => print('Field to add message: $onError'), ); } } /// MessageBubble /// MessageBubble is a WidGet for laying out message in the bubble /// the whole widget is for laying out message style in Screen class MessageBubble extends StatelessWidget { const MessageBubble({ Key key, @required this.messageText, @required this.itsMe, }) : super(key: key); final String messageText; final bool itsMe; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(8.0), child: Material( borderRadius: itsMe ? BorderRadius.only( topLeft: Radius.circular(30.0), bottomLeft: Radius.circular(30.0), bottomRight: Radius.circular(30.0), ) : BorderRadius.only( bottomLeft: Radius.circular(30.0), bottomRight: Radius.circular(30.0), topRight: Radius.circular(30.0), ), elevation: 5.0, color: itsMe ? Colors.lightBlueAccent : Colors.white, child: Padding( padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 20), child: Text( '$messageText', style: TextStyle( color: itsMe ? Colors.white : Colors.black54, fontSize: 15.0, ), ), ), ), ); } }
0
mirrored_repositories/chat_room/lib
mirrored_repositories/chat_room/lib/screens/login_screen.dart
import 'package:chat_room/component/components.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:modal_progress_hud/modal_progress_hud.dart'; import 'chat_screen.dart'; class LoginScreen extends StatelessWidget { static const String id = 'LoginScreen'; @override Widget build(BuildContext context) { return Scaffold( /// this is Login Screen AppBar it's Come from Custom Created Class appBar: ScaffoldAppBar(appbarID: LoginScreen.id).appBar(), /// this is Login Screen Body>> object is declared bellow body: LoginScreenBody(), ); } } class LoginScreenBody extends StatefulWidget { @override _LoginScreenBodyState createState() => _LoginScreenBodyState(); } class _LoginScreenBodyState extends State<LoginScreenBody> { String email; String password; bool inSyncCall = false; FirebaseAuth _auth = FirebaseAuth.instance; @override Widget build(BuildContext context) { print(doesUserSignOut()); return ModalProgressHUD( /// Loading Indicator Show When Button Pressed inAsyncCall: inSyncCall, child: Container( /// Container Contain Whole Body of Screen color: Colors.black12, child: ListView( children: [ LogoBox( height: 200, ), InputTextFields( /// Text Fields Are Take Input And Store Value In Variable onChangedEmail: (value) => email = value, onChangedPass: (value) => password = value, ), /// User Login Button Login With Email And Password <<userLogin>> method is declared bellow /// When Button Pressed Screen Goes to ChatScreen Buttons(onPressed: userLogin).loginButton(), Divider(height: 20), Center( child: Text('OR'), ), /// this is Google SignIn Button When Button Pressed and /// User verification done Screen Goes to ChatScreen Buttons(onPressed: () async { setState(() { inSyncCall = true; }); UserCredential creadential = await signInWithGoogle(); if (creadential.user.email != null) { Navigator.pushNamed( context, ChatScreen.id, ); } setState(() { inSyncCall = false; }); }).googleSignIn() ], ), ), ); } /// declaration of << userLogIn >> method void userLogin() async { setState(() { inSyncCall = true; }); try { UserCredential userCredential = await _auth.signInWithEmailAndPassword( email: email, password: password); userCredential != null ? Navigator.pushNamed(context, ChatScreen.id) : print('userCred null'); } catch (e) { print(e); } setState(() { inSyncCall = false; }); } /// Declaration of << signInWithGoogle >> method /// this method return UserCredential when It's get Called Future<UserCredential> signInWithGoogle() async { // 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 GoogleAuthCredential credential; credential = GoogleAuthProvider.credential( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); // Once signed in, return the UserCredential return await FirebaseAuth.instance.signInWithCredential(credential); } bool doesUserSignOut() { bool userState = false; userState = _auth.currentUser == null ?? true; return userState; } }
0
mirrored_repositories/chat_room
mirrored_repositories/chat_room/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:chat_room/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/chat_ui_stream_iii_example
mirrored_repositories/chat_ui_stream_iii_example/lib/app_routes.dart
class AppRoutes { static const auth = '/auth'; static const home = '/home'; static const participants = '/participants'; static const createRoom = '/createRoom'; static const people = '/people'; }
0
mirrored_repositories/chat_ui_stream_iii_example
mirrored_repositories/chat_ui_stream_iii_example/lib/chats_page.dart
import 'package:chat_ui_stream_iii_example/widget/active_users_row_widget.dart'; import 'package:chat_ui_stream_iii_example/widget/chats_widget.dart'; import 'package:flutter/material.dart'; class ChatsPage extends StatelessWidget { @override Widget build(BuildContext context) => Column( children: [ const SizedBox(height: 12), Container( height: 100, child: ActiveUsersRowWidget(), ), Divider(), Expanded(child: ChatsWidget()), ], ); }
0
mirrored_repositories/chat_ui_stream_iii_example
mirrored_repositories/chat_ui_stream_iii_example/lib/main.dart
import 'package:chat_ui_stream_iii_example/api/stream_api.dart'; import 'package:chat_ui_stream_iii_example/api/stream_user_api.dart'; import 'package:chat_ui_stream_iii_example/app_routes.dart'; import 'package:chat_ui_stream_iii_example/page/auth_page.dart'; import 'package:chat_ui_stream_iii_example/page/createroom/create_room_arguments.dart'; import 'package:chat_ui_stream_iii_example/page/createroom/create_room_page.dart'; import 'package:chat_ui_stream_iii_example/page/home/home_page.dart'; import 'package:chat_ui_stream_iii_example/page/home/home_page_mobile.dart'; import 'package:chat_ui_stream_iii_example/page/participants_page.dart'; import 'package:chat_ui_stream_iii_example/provider/channel_provider.dart'; import 'package:chat_ui_stream_iii_example/provider/google_signin_provider.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; /// Run web app: flutter run -d chrome --web-port 5000 Future main() async { WidgetsFlutterBinding.ensureInitialized(); await SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, ]); await Firebase.initializeApp(); runApp(MyApp()); } class MyApp extends StatelessWidget { static final navigatorKey = GlobalKey<NavigatorState>(); static final String title = 'Facebook Messenger'; @override Widget build(BuildContext context) => MultiProvider( providers: [ ChangeNotifierProvider(create: (context) => GoogleSignInProvider()), ChangeNotifierProvider(create: (context) => ChannelProvider()), ], builder: (context, _) => StreamChat( streamChatThemeData: StreamChatThemeData(), client: StreamApi.client, child: ChannelsBloc( child: MaterialApp( navigatorKey: navigatorKey, debugShowCheckedModeBanner: false, title: title, theme: ThemeData( primaryColor: Colors.white, ), initialRoute: getInitialRoute(), onGenerateRoute: (route) => getRoute(route), ), ), ), ); String getInitialRoute() => AppRoutes.auth; Route getRoute(RouteSettings settings) { switch (settings.name) { case AppRoutes.auth: return buildRoute(AuthPage(), settings: settings); case AppRoutes.home: return buildRoute(HomePage(tabIndex: 0), settings: settings); case AppRoutes.people: return buildRoute(HomePage(tabIndex: 1), settings: settings); case AppRoutes.participants: return buildRoute(ParticipantsPage(), settings: settings); case AppRoutes.createRoom: final CreateRoomArguments args = settings.arguments; return buildRoute( CreateRoomPage(participants: args.members), settings: settings, ); default: return null; } } MaterialPageRoute buildRoute(Widget child, {RouteSettings settings}) => MaterialPageRoute(settings: settings, builder: (context) => child); }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/page/camera_page.dart
import 'dart:async'; import 'dart:io'; import 'dart:math'; import 'dart:typed_data'; import 'package:camerawesome/camerawesome_plugin.dart'; import 'package:camerawesome/models/flashmodes.dart'; import 'package:camerawesome/models/orientations.dart'; import 'package:chat_ui_stream_iii_example/page/photo_preview_page.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:image/image.dart' as imgUtils; import 'package:path_provider/path_provider.dart'; // https://github.com/Apparence-io/camera_awesome/blob/master/example/lib/main.dart class CameraPage extends StatefulWidget { final bool randomPhotoName; CameraPage({this.randomPhotoName = true}); @override _CameraPageState createState() => _CameraPageState(); } class _CameraPageState extends State<CameraPage> with TickerProviderStateMixin { bool _focus = false; ValueNotifier<CameraFlashes> _switchFlash = ValueNotifier(CameraFlashes.NONE); ValueNotifier<double> _zoomNotifier = ValueNotifier(0); ValueNotifier<Size> _photoSize = ValueNotifier(null); ValueNotifier<Sensors> _sensor = ValueNotifier(Sensors.BACK); ValueNotifier<CameraOrientations> _orientation = ValueNotifier(CameraOrientations.PORTRAIT_UP); /// use this to call a take picture PictureController _pictureController = new PictureController(); AnimationController _iconsAnimationController; Timer _previewDismissTimer; Stream<Uint8List> previewStream; @override void initState() { super.initState(); _iconsAnimationController = AnimationController( vsync: this, duration: Duration(milliseconds: 300), ); } @override void dispose() { _iconsAnimationController.dispose(); _photoSize.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: Stack( fit: StackFit.expand, children: <Widget>[ buildFullscreenCamera(), _buildInterface(), ], ), ); } Widget _buildInterface() { return Stack( children: <Widget>[ SafeArea( bottom: false, child: TopBarWidget( photoSize: _photoSize, switchFlash: _switchFlash, orientation: _orientation, rotationController: _iconsAnimationController, onFlashTap: () { switch (_switchFlash.value) { case CameraFlashes.NONE: _switchFlash.value = CameraFlashes.ON; break; case CameraFlashes.ON: _switchFlash.value = CameraFlashes.AUTO; break; case CameraFlashes.AUTO: _switchFlash.value = CameraFlashes.ALWAYS; break; case CameraFlashes.ALWAYS: _switchFlash.value = CameraFlashes.NONE; break; } setState(() {}); }, onChangeSensorTap: () { this._focus = !_focus; if (_sensor.value == Sensors.FRONT) { _sensor.value = Sensors.BACK; } else { _sensor.value = Sensors.FRONT; } }, onResolutionTap: () {}, onFullscreenTap: () {}), ), BottomBarWidget( onZoomInTap: () { if (_zoomNotifier.value <= 0.9) { _zoomNotifier.value += 0.1; } setState(() {}); }, onZoomOutTap: () { if (_zoomNotifier.value >= 0.1) { _zoomNotifier.value -= 0.1; } setState(() {}); }, onCaptureModeSwitchChange: () {}, onCaptureTap: _takePhoto, rotationController: _iconsAnimationController, orientation: _orientation, ), ], ); } _takePhoto() async { final Directory extDir = await getTemporaryDirectory(); final testDir = await Directory('${extDir.path}/test').create(recursive: true); final String filePath = widget.randomPhotoName ? '${testDir.path}/${DateTime.now().millisecondsSinceEpoch}.jpg' : '${testDir.path}/photo_test.jpg'; await _pictureController.takePicture(filePath); // lets just make our phone vibrate HapticFeedback.mediumImpact(); setState(() {}); final file = File(filePath); final img = imgUtils.decodeImage(file.readAsBytesSync()); print("==> img.width : ${img.width} | img.height : ${img.height}"); Navigator.of(context).pushReplacement(MaterialPageRoute( builder: (context) => PhotoPreviewPage(imageFile: file), )); } _onOrientationChange(CameraOrientations newOrientation) { _orientation.value = newOrientation; if (_previewDismissTimer != null) { _previewDismissTimer.cancel(); } } _onPermissionsResult(bool granted) { if (!granted) { AlertDialog alert = AlertDialog( title: Text('Error'), content: Text( 'It seems you doesn\'t authorized some permissions. Please check on your settings and try again.'), actions: [ FlatButton( child: Text('OK'), onPressed: () => Navigator.of(context).pop(), ), ], ); // show the dialog showDialog( context: context, builder: (BuildContext context) { return alert; }, ); } else { setState(() {}); print("granted"); } } Widget buildFullscreenCamera() { return Positioned( top: 0, left: 0, bottom: 0, right: 0, child: Center( child: CameraAwesome( onPermissionsResult: _onPermissionsResult, selectDefaultSize: (availableSizes) { return availableSizes[0]; }, photoSize: _photoSize, sensor: _sensor, switchFlashMode: _switchFlash, zoom: _zoomNotifier, onOrientationChanged: _onOrientationChange, onCameraStarted: () {}, ), ), ); } } class OrientationUtils { static CameraOrientations convertRadianToOrientation(double radians) { CameraOrientations orientation; if (radians == -pi / 2) { orientation = CameraOrientations.LANDSCAPE_LEFT; } else if (radians == pi / 2) { orientation = CameraOrientations.LANDSCAPE_RIGHT; } else if (radians == 0.0) { orientation = CameraOrientations.PORTRAIT_UP; } else if (radians == pi) { orientation = CameraOrientations.PORTRAIT_DOWN; } return orientation; } static double convertOrientationToRadian(CameraOrientations orientation) { switch (orientation) { case CameraOrientations.LANDSCAPE_LEFT: return -pi / 2; case CameraOrientations.LANDSCAPE_RIGHT: return pi / 2; case CameraOrientations.PORTRAIT_UP: return 0; case CameraOrientations.PORTRAIT_DOWN: return pi; default: return 0; } } static bool isPortraitMode(CameraOrientations orientation) => orientation == CameraOrientations.PORTRAIT_DOWN || orientation == CameraOrientations.PORTRAIT_UP; } class BottomBarWidget extends StatelessWidget { final AnimationController rotationController; final ValueNotifier<CameraOrientations> orientation; final Function onZoomInTap; final Function onZoomOutTap; final Function onCaptureTap; final Function onCaptureModeSwitchChange; const BottomBarWidget({ Key key, @required this.rotationController, @required this.orientation, @required this.onZoomOutTap, @required this.onZoomInTap, @required this.onCaptureTap, @required this.onCaptureModeSwitchChange, }) : super(key: key); @override Widget build(BuildContext context) { return Positioned( bottom: 0, left: 0, right: 0, child: SizedBox( height: 200, child: Stack( children: [ Container(color: Colors.black12), Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ OptionButton( icon: Icons.zoom_out, rotationController: rotationController, orientation: orientation, onTapCallback: () => onZoomOutTap?.call(), ), CameraButton(onTap: () => onCaptureTap?.call()), OptionButton( icon: Icons.zoom_in, rotationController: rotationController, orientation: orientation, onTapCallback: () => onZoomInTap?.call(), ), ], ), ], ), ], ), ), ); } } class OptionButton extends StatefulWidget { final IconData icon; final Function onTapCallback; final AnimationController rotationController; final ValueNotifier<CameraOrientations> orientation; final bool isEnabled; const OptionButton({ Key key, this.icon, this.onTapCallback, this.rotationController, this.orientation, this.isEnabled = true, }) : super(key: key); @override _OptionButtonState createState() => _OptionButtonState(); } class _OptionButtonState extends State<OptionButton> with SingleTickerProviderStateMixin { double _angle = 0.0; CameraOrientations _oldOrientation = CameraOrientations.PORTRAIT_UP; @override void initState() { super.initState(); Tween(begin: 0.0, end: 1.0) .chain(CurveTween(curve: Curves.ease)) .animate(widget.rotationController) ..addStatusListener((status) { if (status == AnimationStatus.completed) { _oldOrientation = OrientationUtils.convertRadianToOrientation(_angle); } }); widget.orientation.addListener(() { _angle = OrientationUtils.convertOrientationToRadian(widget.orientation.value); if (widget.orientation.value == CameraOrientations.PORTRAIT_UP) { widget.rotationController.reverse(); } else if (_oldOrientation == CameraOrientations.LANDSCAPE_LEFT || _oldOrientation == CameraOrientations.LANDSCAPE_RIGHT) { widget.rotationController.reset(); if ((widget.orientation.value == CameraOrientations.LANDSCAPE_LEFT || widget.orientation.value == CameraOrientations.LANDSCAPE_RIGHT)) { widget.rotationController.forward(); } else if ((widget.orientation.value == CameraOrientations.PORTRAIT_DOWN)) { if (_oldOrientation == CameraOrientations.LANDSCAPE_RIGHT) { widget.rotationController.forward(from: 0.5); } else { widget.rotationController.reverse(from: 0.5); } } } else if (widget.orientation.value == CameraOrientations.PORTRAIT_DOWN) { widget.rotationController.reverse(from: 0.5); } else { widget.rotationController.forward(); } }); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: widget.rotationController, builder: (context, child) { double newAngle; if (_oldOrientation == CameraOrientations.LANDSCAPE_LEFT) { if (widget.orientation.value == CameraOrientations.PORTRAIT_UP) { newAngle = -widget.rotationController.value; } } if (_oldOrientation == CameraOrientations.LANDSCAPE_RIGHT) { if (widget.orientation.value == CameraOrientations.PORTRAIT_UP) { newAngle = widget.rotationController.value; } } if (_oldOrientation == CameraOrientations.PORTRAIT_DOWN) { if (widget.orientation.value == CameraOrientations.PORTRAIT_UP) { newAngle = widget.rotationController.value * -pi; } } return IgnorePointer( ignoring: !widget.isEnabled, child: Opacity( opacity: widget.isEnabled ? 1.0 : 0.3, child: Transform.rotate( angle: newAngle ?? widget.rotationController.value * _angle, child: ClipOval( child: Material( color: Color(0xFF4F6AFF), child: InkWell( child: SizedBox( width: 48, height: 48, child: Icon( widget.icon, color: Colors.white, size: 24.0, ), ), onTap: () { if (widget.onTapCallback != null) { // Trigger short vibration HapticFeedback.selectionClick(); widget.onTapCallback(); } }, ), ), ), ), ), ); }, ); } } class TopBarWidget extends StatelessWidget { final ValueNotifier<Size> photoSize; final AnimationController rotationController; final ValueNotifier<CameraOrientations> orientation; final ValueNotifier<CameraFlashes> switchFlash; final Function onFullscreenTap; final Function onResolutionTap; final Function onChangeSensorTap; final Function onFlashTap; const TopBarWidget({ Key key, @required this.photoSize, @required this.orientation, @required this.rotationController, @required this.switchFlash, @required this.onFullscreenTap, @required this.onFlashTap, @required this.onChangeSensorTap, @required this.onResolutionTap, }) : super(key: key); @override Widget build(BuildContext context) => Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 16), child: Column( children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ Padding( padding: const EdgeInsets.only(right: 24), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ IgnorePointer( ignoring: false, child: Opacity( opacity: 1.0, child: ValueListenableBuilder( valueListenable: photoSize, builder: (context, value, child) => FlatButton( key: ValueKey("resolutionButton"), onPressed: () { HapticFeedback.selectionClick(); onResolutionTap?.call(); }, child: Text( '${value?.width?.toInt()} / ${value?.height?.toInt()}', key: ValueKey("resolutionTxt"), style: TextStyle(color: Colors.white), ), ), ), ), ), ], ), ), OptionButton( icon: Icons.switch_camera, rotationController: rotationController, orientation: orientation, onTapCallback: () => onChangeSensorTap?.call(), ), SizedBox(width: 20.0), OptionButton( rotationController: rotationController, icon: _getFlashIcon(), orientation: orientation, onTapCallback: () => onFlashTap?.call(), ), ], ), SizedBox(height: 20.0), ], ), ); IconData _getFlashIcon() { switch (switchFlash.value) { case CameraFlashes.NONE: return Icons.flash_off; case CameraFlashes.ON: return Icons.flash_on; case CameraFlashes.AUTO: return Icons.flash_auto; case CameraFlashes.ALWAYS: return Icons.highlight; default: return Icons.flash_off; } } } class CameraButton extends StatefulWidget { final Function onTap; const CameraButton({ @required this.onTap, }); @override _CameraButtonState createState() => _CameraButtonState(); } class _CameraButtonState extends State<CameraButton> with SingleTickerProviderStateMixin { AnimationController _animationController; double _scale; Duration _duration = Duration(milliseconds: 100); @override void initState() { super.initState(); _animationController = AnimationController( vsync: this, duration: _duration, lowerBound: 0.0, upperBound: 0.1, )..addListener(() => setState(() {})); } @override void dispose() { _animationController?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { _scale = 1 - _animationController.value; return GestureDetector( onTapDown: _onTapDown, onTapUp: _onTapUp, onTapCancel: _onTapCancel, child: Container( key: ValueKey('cameraButton' + 'Photo'), height: 80, width: 80, child: Transform.scale( scale: _scale, child: CustomPaint( painter: CameraButtonPainter(), ), ), ), ); } _onTapDown(TapDownDetails details) => _animationController.forward(); _onTapUp(TapUpDetails details) { Future.delayed(_duration, () { _animationController.reverse(); }); this.widget.onTap?.call(); } _onTapCancel() => _animationController.reverse(); } class CameraButtonPainter extends CustomPainter { final bool isRecording; CameraButtonPainter({ this.isRecording = false, }); @override void paint(Canvas canvas, Size size) { var bgPainter = Paint() ..style = PaintingStyle.fill ..isAntiAlias = true; var radius = size.width / 2; var center = Offset(size.width / 2, size.height / 2); bgPainter.color = Colors.white.withOpacity(.5); canvas.drawCircle(center, radius, bgPainter); bgPainter.color = Colors.white; canvas.drawCircle(center, radius - 8, bgPainter); } @override bool shouldRepaint(CustomPainter oldDelegate) => false; }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/page/participants_page.dart
import 'package:chat_ui_stream_iii_example/api/stream_user_api.dart'; import 'package:chat_ui_stream_iii_example/app_routes.dart'; import 'package:chat_ui_stream_iii_example/page/createroom/create_room_arguments.dart'; import 'package:chat_ui_stream_iii_example/page/createroom/create_room_page.dart'; import 'package:chat_ui_stream_iii_example/widget/profile_image_widget.dart'; import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart' hide User; import 'package:chat_ui_stream_iii_example/model/user.dart'; class ParticipantsPage extends StatefulWidget { @override _ParticipantsPageState createState() => _ParticipantsPageState(); } class _ParticipantsPageState extends State<ParticipantsPage> { Future<List<User>> allUsers; List<User> selectedUsers = []; @override void initState() { super.initState(); allUsers = StreamUserApi.getAllUsers(); } @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: Text('Add Participants'), actions: [ TextButton( child: Text('CREATE'), onPressed: selectedUsers.isEmpty ? null : () { Navigator.pushNamed( context, AppRoutes.createRoom, arguments: CreateRoomArguments(members: selectedUsers), ); }, ), const SizedBox(width: 8), ], ), body: FutureBuilder<List<User>>( future: allUsers, builder: (context, snapshot) { switch (snapshot.connectionState) { case ConnectionState.waiting: return Center(child: CircularProgressIndicator()); default: if (snapshot.hasError) { return Center(child: Text('Something Went Wrong Try later')); } else { final users = snapshot.data .where((User user) => user.idUser != StreamChat.of(context).user.id) .toList(); return buildUsers(users); } } }, ), ); Widget buildUsers(List<User> users) => ListView.builder( itemCount: users.length, itemBuilder: (context, index) { final user = users[index]; return CheckboxListTile( value: selectedUsers.contains(user), onChanged: (isAdded) => setState(() => isAdded ? selectedUsers.add(user) : selectedUsers.remove(user)), title: Row( children: [ ProfileImageWidget(imageUrl: user.imageUrl), const SizedBox(width: 16), Expanded( child: Text( user.name, style: TextStyle(fontWeight: FontWeight.bold), maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ], ), ); }, ); }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/page/profile_page.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../provider/google_signin_provider.dart'; class ProfilePage extends StatelessWidget { @override Widget build(BuildContext context) { final user = FirebaseAuth.instance.currentUser; return Scaffold( appBar: AppBar( title: Text( 'Profile', style: TextStyle( color: Colors.black, fontSize: 22, fontWeight: FontWeight.bold, ), ), ), body: Center( child: Padding( padding: const EdgeInsets.all(8), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CircleAvatar( backgroundImage: NetworkImage(user.photoURL), radius: 50, ), SizedBox(height: 20), Text( user.displayName, style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), SizedBox(height: 20), ElevatedButton( child: Text('Logout'), onPressed: () { final provider = Provider.of<GoogleSignInProvider>(context, listen: false); provider.logout(); Navigator.of(context).pop(); }, ) ], ), ), ), ); } }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/page/story_view_page.dart
import 'package:chat_ui_stream_iii_example/model/user_story.dart'; import 'package:chat_ui_stream_iii_example/widget/story_delegate_widget.dart'; import 'package:flutter/material.dart'; class StoryViewPage extends StatefulWidget { final List<UserStory> stories; final UserStory userStory; const StoryViewPage({ Key key, @required this.stories, @required this.userStory, }) : super(key: key); @override _StoryViewPageState createState() => _StoryViewPageState(); } class _StoryViewPageState extends State<StoryViewPage> { PageController pageController; @override void initState() { super.initState(); final index = widget.stories.indexOf(widget.userStory); pageController = PageController(initialPage: index); } @override void dispose() { pageController.dispose(); super.dispose(); } @override Widget build(BuildContext context) => PageView( controller: pageController, children: widget.stories .map((user) => StoryDelegateWidget( userStory: user, allStories: widget.stories, pageController: pageController, )) .toList(), ); }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/page/photo_preview_page.dart
import 'dart:io'; import 'package:chat_ui_stream_iii_example/api/stream_story_api.dart'; import 'package:chat_ui_stream_iii_example/model/story.dart'; import 'package:flutter/material.dart'; import '../app_routes.dart'; class PhotoPreviewPage extends StatelessWidget { final File imageFile; const PhotoPreviewPage({ Key key, @required this.imageFile, }) : super(key: key); @override Widget build(BuildContext context) => Scaffold( extendBodyBehindAppBar: true, appBar: AppBar( iconTheme: IconThemeData(color: Colors.white), backgroundColor: Colors.transparent, elevation: 0, ), body: Stack( fit: StackFit.expand, children: [ Image.file(imageFile, fit: BoxFit.cover), Positioned( bottom: 10, right: 10, child: Column( children: [ IconButton( icon: Icon(Icons.send), color: Colors.white, iconSize: 30, onPressed: () => uploadStory(context), ), Text( 'Add to Story', style: TextStyle(color: Colors.white), ) ], ), ), ], ), ); void uploadStory(BuildContext context) async { showDialog( context: context, builder: (context) => Center(child: CircularProgressIndicator()), ); final story = Story(time: DateTime.now(), imageUrl: 'NOOP'); await StreamStoryApi.addStory(story, imageFile); // hide dialog Navigator.pop(context); Navigator.of(context).pushNamedAndRemoveUntil( AppRoutes.people, ModalRoute.withName('/'), ); } }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/page/people_page.dart
import 'package:chat_ui_stream_iii_example/widget/stories_grid_widget.dart'; import 'package:flutter/material.dart'; class PeoplePage extends StatelessWidget { @override Widget build(BuildContext context) { return DefaultTabController( length: 1, child: Column( children: [ const SizedBox(height: 12), TabBar( indicatorPadding: EdgeInsets.symmetric(horizontal: 8), tabs: [ Tab( child: Text( 'STORIES', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), ), ), ], ), Expanded( child: TabBarView( children: [ StoriesGridWidget(), ], ), ) ], ), ); } }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/page/auth_page.dart
import 'package:chat_ui_stream_iii_example/provider/google_signin_provider.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:provider/provider.dart'; class AuthPage extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: Text('Facebook Messenger'), ), body: Center(child: buildSignIn(context)), ); Widget buildSignIn(BuildContext context) => OutlinedButton.icon( style: OutlinedButton.styleFrom( primary: Colors.black, shape: StadiumBorder(), padding: EdgeInsets.all(20), ), label: Text( 'Sign In With Google', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20), ), icon: FaIcon(FontAwesomeIcons.google, color: Colors.red), onPressed: () { final provider = Provider.of<GoogleSignInProvider>(context, listen: false); provider.login(); }, ); }
0
mirrored_repositories/chat_ui_stream_iii_example/lib/page
mirrored_repositories/chat_ui_stream_iii_example/lib/page/chat/chat_page_mobile.dart
import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class ChatPageMobile extends StatefulWidget { final Channel channel; const ChatPageMobile({ @required this.channel, }); @override _ChatPageMobileState createState() => _ChatPageMobileState(); } class _ChatPageMobileState extends State<ChatPageMobile> { @override Widget build(BuildContext context) => StreamChannel( channel: widget.channel, child: Scaffold( appBar: buildAppBar(), body: Column( children: [ Expanded(child: MessageListView()), MessageInput(), ], ), ), ); Widget buildAppBar() { final channelName = widget.channel.extraData['name']; return AppBar( backgroundColor: Colors.white, title: Text(channelName), actions: [ IconButton( onPressed: () {}, icon: Icon(Icons.phone), ), IconButton( onPressed: () {}, icon: Icon(Icons.videocam), ), const SizedBox(width: 8), ], ); } }
0
mirrored_repositories/chat_ui_stream_iii_example/lib/page
mirrored_repositories/chat_ui_stream_iii_example/lib/page/home/home_page.dart
import 'package:chat_ui_stream_iii_example/page/home/home_page_desktop.dart'; import 'package:chat_ui_stream_iii_example/page/home/home_page_mobile.dart'; import 'package:flutter/material.dart'; import 'package:responsive_builder/responsive_builder.dart'; class HomePage extends StatelessWidget { final int tabIndex; const HomePage({ Key key, @required this.tabIndex, }) : super(key: key); @override Widget build(BuildContext context) => ResponsiveBuilder( builder: (context, sizingInfo) => sizingInfo.isDesktop ? HomePageDesktop() : HomePageMobile(tabIndex: tabIndex), ); }
0
mirrored_repositories/chat_ui_stream_iii_example/lib/page
mirrored_repositories/chat_ui_stream_iii_example/lib/page/home/home_page_mobile.dart
import 'package:chat_ui_stream_iii_example/chats_page.dart'; import 'package:chat_ui_stream_iii_example/page/people_page.dart'; import 'package:chat_ui_stream_iii_example/widget/user_image_widget.dart'; import 'package:flutter/material.dart'; class HomePageMobile extends StatefulWidget { final int tabIndex; const HomePageMobile({ Key key, this.tabIndex = 0, }) : super(key: key); @override _HomePageMobileState createState() => _HomePageMobileState(); } class _HomePageMobileState extends State<HomePageMobile> { int tabIndex; @override void initState() { super.initState(); tabIndex = widget.tabIndex; } @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: Text('Chats'), centerTitle: true, leading: UserImageWidget(), actions: [ IconButton(icon: Icon(Icons.edit), onPressed: () {}), SizedBox(width: 8), ], ), body: IndexedStack( index: tabIndex, children: [ ChatsPage(), PeoplePage(), ], ), bottomNavigationBar: BottomNavigationBar( currentIndex: tabIndex, selectedItemColor: Colors.black, unselectedItemColor: Colors.black38, onTap: (index) => setState(() => tabIndex = index), items: [ BottomNavigationBarItem( icon: Icon(Icons.chat), label: 'Chats', ), BottomNavigationBarItem( icon: Icon(Icons.people), label: 'People', ), ], ), ); }
0
mirrored_repositories/chat_ui_stream_iii_example/lib/page
mirrored_repositories/chat_ui_stream_iii_example/lib/page/home/home_page_desktop.dart
import 'package:chat_ui_stream_iii_example/chats_page.dart'; import 'package:chat_ui_stream_iii_example/page/chat/chat_page_mobile.dart'; import 'package:chat_ui_stream_iii_example/provider/channel_provider.dart'; import 'package:chat_ui_stream_iii_example/widget/user_image_widget.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class HomePageDesktop extends StatelessWidget { @override Widget build(BuildContext context) { final selectedChannel = Provider.of<ChannelProvider>(context).selectedChannel; return Scaffold( body: Row( children: [ Expanded(child: buildChats(context)), VerticalDivider(indent: 0, endIndent: 0, thickness: 0.5, width: 0.5), Expanded(flex: 3, child: buildChat(selectedChannel)) ], ), ); } Widget buildChats(BuildContext context) => Column( children: [ AppBar( leading: UserImageWidget(), title: Text('Chats'), actions: [ CircleAvatar( backgroundColor: Colors.grey.shade200, child: Icon(Icons.edit, size: 20, color: Colors.black), ), SizedBox(width: 8), ], ), Expanded(child: ChatsPage()), ], ); Widget buildChat(Channel selectedChannel) { if (selectedChannel == null) { return Center( child: Text( 'Select A Chat', style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); } return ChatPageMobile(channel: selectedChannel); } }
0
mirrored_repositories/chat_ui_stream_iii_example/lib/page
mirrored_repositories/chat_ui_stream_iii_example/lib/page/createroom/create_room_page.dart
import 'dart:io'; import 'package:chat_ui_stream_iii_example/api/stream_channel_api.dart'; import 'package:chat_ui_stream_iii_example/app_routes.dart'; import 'package:chat_ui_stream_iii_example/model/user.dart'; import 'package:chat_ui_stream_iii_example/page/home/home_page_mobile.dart'; import 'package:chat_ui_stream_iii_example/widget/profile_image_widget.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; class CreateRoomPage extends StatefulWidget { final List<User> participants; const CreateRoomPage({ Key key, @required this.participants, }) : super(key: key); @override _CreateRoomPageState createState() => _CreateRoomPageState(); } class _CreateRoomPageState extends State<CreateRoomPage> { String name = ''; File imageFile; @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: Text('Create Room'), actions: [ IconButton( icon: Icon(Icons.done), onPressed: () async { final idParticipants = widget.participants .map((participant) => participant.idUser) .toList(); await StreamChannelApi.createChannel( context, name: name, imageFile: imageFile, idMembers: idParticipants, ); Navigator.pushNamedAndRemoveUntil( context, AppRoutes.home, ModalRoute.withName('/'), ); }, ), const SizedBox(width: 8), ], ), body: ListView( padding: EdgeInsets.all(24), children: [ GestureDetector( onTap: () async { final pickedFile = await ImagePicker().getImage(source: ImageSource.gallery); if (pickedFile == null) return; setState(() { imageFile = File(pickedFile.path); }); }, child: buildImage(context), ), const SizedBox(height: 48), buildTextField(), const SizedBox(height: 12), Text( 'Participants', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24), ), const SizedBox(height: 12), buildMembers(), ], ), ); Widget buildImage(BuildContext context) { if (imageFile == null) { return CircleAvatar( radius: 64, backgroundColor: Theme.of(context).accentColor, child: Icon(Icons.add, color: Colors.white, size: 64), ); } else { return CircleAvatar( radius: 64, backgroundColor: Theme.of(context).accentColor, child: ClipOval( child: Image.file(imageFile, fit: BoxFit.cover, width: 128, height: 128), ), ); } } Widget buildTextField() => TextFormField( decoration: InputDecoration( labelText: 'Channel Name', labelStyle: TextStyle(color: Colors.black), border: OutlineInputBorder(), focusedBorder: OutlineInputBorder(), ), maxLength: 30, onChanged: (value) => setState(() => name = value), ); Widget buildMembers() => Column( children: widget.participants .map((member) => ListTile( contentPadding: EdgeInsets.zero, leading: ProfileImageWidget(imageUrl: member.imageUrl), title: Text( member.name, style: TextStyle(fontWeight: FontWeight.bold), maxLines: 1, overflow: TextOverflow.ellipsis, ), )) .toList(), ); }
0
mirrored_repositories/chat_ui_stream_iii_example/lib/page
mirrored_repositories/chat_ui_stream_iii_example/lib/page/createroom/create_room_arguments.dart
import 'package:chat_ui_stream_iii_example/model/user.dart'; import 'package:meta/meta.dart'; class CreateRoomArguments { final List<User> members; const CreateRoomArguments({ @required this.members, }); }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/model/user_story.dart
import 'package:chat_ui_stream_iii_example/model/story.dart'; import 'package:flutter/cupertino.dart'; class UserStory { final List<Story> stories; final String userName; final String userImageUrl; const UserStory({ @required this.stories, @required this.userName, @required this.userImageUrl, }); UserStory copy({ List<Story> stories, String userName, String userImageUrl, }) => UserStory( stories: stories ?? this.stories, userName: userName ?? this.userName, userImageUrl: userImageUrl ?? this.userImageUrl, ); static UserStory fromJson(Map<String, dynamic> json) => UserStory( stories: json['stories'], userName: json['userName'], userImageUrl: json['userImageUrl'], ); Map<String, dynamic> toJson() => { 'stories': stories, 'userName': userName, 'userImageUrl': userImageUrl, }; }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/model/story.dart
import 'package:chat_ui_stream_iii_example/utils/utils.dart'; import 'package:flutter/foundation.dart'; class Story { final String imageUrl; final DateTime time; const Story({ @required this.imageUrl, @required this.time, }); Story copy({ String imageUrl, DateTime time, }) => Story( imageUrl: imageUrl ?? this.imageUrl, time: time ?? this.time, ); static Story fromJson(Map<String, dynamic> json) => Story( imageUrl: json['imageUrl'], time: Utils.toDateTime(json['time']), ); Map<String, dynamic> toJson() => { 'imageUrl': imageUrl, 'time': Utils.fromDateTimeToJson(time), }; }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/model/user.dart
import 'package:meta/meta.dart'; class User { final String idUser; final String name; final String imageUrl; final bool isOnline; const User({ @required this.idUser, @required this.name, @required this.imageUrl, this.isOnline = false, }); User copy({ String idUser, String name, String imageUrl, bool isOnline, }) => User( idUser: idUser ?? this.idUser, name: name ?? this.name, imageUrl: imageUrl ?? this.imageUrl, isOnline: isOnline ?? this.isOnline, ); static User fromJson(Map<String, dynamic> json) => User( idUser: json['idUser'], name: json['name'], imageUrl: json['imageUrl'], isOnline: json['isOnline'], ); Map<String, dynamic> toJson() => { 'idUser': idUser, 'name': name, 'imageUrl': imageUrl, 'isOnline': isOnline, }; int get hashCode => idUser.hashCode ^ name.hashCode ^ imageUrl.hashCode; bool operator ==(other) => other is User && other.name == name && other.imageUrl == imageUrl && other.idUser == idUser; }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/widget/story_delegate_widget.dart
import 'package:chat_ui_stream_iii_example/model/user_story.dart'; import 'package:flutter/material.dart'; import 'package:story_view/controller/story_controller.dart'; import 'package:story_view/story_view.dart'; import 'package:story_view/widgets/story_view.dart'; import 'package:timeago/timeago.dart' as timeago; class StoryDelegateWidget extends StatefulWidget { final UserStory userStory; final List<UserStory> allStories; final PageController pageController; const StoryDelegateWidget({ @required this.userStory, @required this.pageController, @required this.allStories, }); @override _StoryDelegateWidgetState createState() => _StoryDelegateWidgetState(); } class _StoryDelegateWidgetState extends State<StoryDelegateWidget> { final controller = StoryController(); List<StoryItem> storyItems = []; String when = ''; @override void initState() { super.initState(); addStoryItems(); when = timeago.format(widget.userStory.stories[0].time); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) => Stack( children: <Widget>[ Material( type: MaterialType.transparency, child: StoryView( storyItems: storyItems, controller: controller, onComplete: handleCompleted, onVerticalSwipeComplete: (direction) { if (direction == Direction.down) { Navigator.pop(context); } }, onStoryShow: (storyItem) { final index = storyItems.indexOf(storyItem); if (index > 0) { setState(() { when = timeago.format(widget.userStory.stories[index].time); }); } }, ), ), Container( padding: EdgeInsets.only(top: 48, left: 16, right: 16), child: ProfileWidget( userName: widget.userStory.userName, userImage: widget.userStory.userImageUrl, when: when, ), ) ], ); void addStoryItems() { widget.userStory.stories.forEach((story) { storyItems.add(StoryItem.pageImage( url: story.imageUrl, controller: controller, caption: '', duration: Duration(milliseconds: (10 * 1000).toInt()), )); }); } void handleCompleted() { widget.pageController .nextPage(duration: Duration(milliseconds: 300), curve: Curves.easeIn); final currentIndex = widget.allStories.indexOf(widget.userStory); final isLastPage = widget.allStories.length - 1 == currentIndex; if (isLastPage) { Navigator.of(context).pop(); } } } class ProfileWidget extends StatelessWidget { final String userName; final String userImage; final String when; const ProfileWidget({ Key key, @required this.userName, @required this.when, @required this.userImage, }) : super(key: key); @override Widget build(BuildContext context) => Material( type: MaterialType.transparency, child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ CircleAvatar( radius: 24, backgroundImage: NetworkImage(userImage), ), SizedBox(width: 16), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( userName, style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white, ), ), Text( when, style: TextStyle(color: Colors.white38), ) ], ), ) ], ), ); }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/widget/chats_widget.dart
import 'package:chat_ui_stream_iii_example/widget/channel_list_widget.dart'; import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class ChatsWidget extends StatelessWidget { @override Widget build(BuildContext context) { final idUser = StreamChat.of(context).user.id; return ChannelListView( filter: { 'members': { '\$in': [idUser], } }, sort: [SortOption('last_message_at')], pagination: PaginationParams(limit: 20), channelPreviewBuilder: (context, channel) => ChannelListWidget(channel: channel), ); } }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/widget/story_card_widget.dart
import 'package:chat_ui_stream_iii_example/model/user_story.dart'; import 'package:chat_ui_stream_iii_example/page/camera_page.dart'; import 'package:chat_ui_stream_iii_example/page/story_view_page.dart'; import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class AddStoryCardWidget extends StatelessWidget { @override Widget build(BuildContext context) => StoryCardWidget( title: '', urlImage: '', onClicked: () => Navigator.of(context).push( MaterialPageRoute(builder: (context) => CameraPage()), ), ); } class UserStoryCardWidget extends StatelessWidget { final UserStory story; const UserStoryCardWidget({ Key key, @required this.story, }) : super(key: key); @override Widget build(BuildContext context) => StoryCardWidget( title: story.userName, urlImage: story.stories.first.imageUrl, urlAvatar: story.userImageUrl, onClicked: () { if (story.stories.isEmpty) return; Navigator.of(context).push(MaterialPageRoute( builder: (context) => StoryViewPage( stories: [story], userStory: story, ), )); }, ); } class StoryCardWidget extends StatelessWidget { final String title; final String urlImage; final String urlAvatar; final VoidCallback onClicked; const StoryCardWidget({ Key key, @required this.title, @required this.urlImage, @required this.onClicked, this.urlAvatar, }) : super(key: key); @override Widget build(BuildContext context) { final isSelfUser = urlAvatar == null; return GestureDetector( onTap: onClicked, child: Container( padding: EdgeInsets.all(12), decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.circular(12), image: isSelfUser ? null : DecorationImage( image: NetworkImage(urlImage), fit: BoxFit.cover, ), ), child: isSelfUser ? buildAdd() : Stack( children: [ buildAvatar(), Positioned( bottom: 0, child: Text( title, style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, ), ), ) ], ), ), ); } Widget buildAvatar() => CircleAvatar( radius: 18, backgroundColor: Colors.blue, child: CircleAvatar( radius: 16, backgroundImage: NetworkImage(urlAvatar), ), ); Widget buildAdd() => Center( child: Icon(Icons.add, size: 72, color: Colors.white), ); }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/widget/profile_image_widget.dart
import 'package:flutter/material.dart'; class ProfileImageWidget extends StatelessWidget { final String imageUrl; final double radius; const ProfileImageWidget({ Key key, @required this.imageUrl, this.radius = 20, }) : super(key: key); @override Widget build(BuildContext context) => CircleAvatar( radius: radius, backgroundImage: NetworkImage(imageUrl), ); }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/widget/channel_list_widget.dart
import 'package:chat_ui_stream_iii_example/page/chat/chat_page_mobile.dart'; import 'package:chat_ui_stream_iii_example/widget/profile_image_widget.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import 'package:responsive_builder/responsive_builder.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import '../provider/channel_provider.dart'; class ChannelListWidget extends StatelessWidget { final Channel channel; const ChannelListWidget({ Key key, @required this.channel, }) : super(key: key); @override Widget build(BuildContext context) { final name = channel.extraData['name']; final urlImage = channel.extraData['image']; final hasMessage = channel.state.messages.isNotEmpty; final lastMessage = hasMessage ? channel.state.messages.last.text : ''; final lastMessageAt = _formatDateTime(channel.lastMessageAt); return buildChannel( context, channel: channel, name: name, urlImage: urlImage, lastMessage: lastMessage, lastMessageAt: lastMessageAt, ); } Widget buildChannel( BuildContext context, { @required Channel channel, @required String name, @required String urlImage, @required String lastMessage, @required String lastMessageAt, }) => ListTile( onTap: () { final isMobile = getDeviceType(MediaQuery.of(context).size) == DeviceScreenType.mobile; final provider = Provider.of<ChannelProvider>(context, listen: false); if (isMobile) { Navigator.of(context).push(MaterialPageRoute( builder: (context) => ChatPageMobile(channel: channel), )); } else { provider.setChannel(channel); } }, leading: ProfileImageWidget(imageUrl: urlImage), title: Text( name, style: TextStyle(fontWeight: FontWeight.bold), ), subtitle: Row( children: [ Expanded(child: Text(lastMessage)), Text(lastMessageAt), ], ), ); String _formatDateTime(DateTime lastMessageAt) { if (lastMessageAt == null) return ''; final isRecently = lastMessageAt.difference(DateTime.now()).inDays == 0; final dateFormat = isRecently ? DateFormat.jm() : DateFormat.MMMd(); return dateFormat.format(lastMessageAt); } }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/widget/active_users_row_widget.dart
import 'package:chat_ui_stream_iii_example/app_routes.dart'; import 'package:flutter/material.dart'; import '../api/stream_channel_api.dart'; import '../api/stream_user_api.dart'; import '../model/user.dart'; import '../page/chat/chat_page_mobile.dart'; import 'profile_image_widget.dart'; class ActiveUsersRowWidget extends StatelessWidget { @override Widget build(BuildContext context) => FutureBuilder<List<User>>( future: StreamUserApi.getAllUsers(), builder: (context, snapshot) { switch (snapshot.connectionState) { case ConnectionState.waiting: return Center(child: CircularProgressIndicator()); default: if (snapshot.hasError) { return Center(child: Text('Something Went Wrong Try later')); } else { final users = snapshot.data; return buildActiveUsers(context, users); } } }, ); Widget buildActiveUsers(BuildContext context, List<User> users) => ListView.builder( scrollDirection: Axis.horizontal, itemCount: users.length + 1, itemBuilder: (context, index) { if (index == 0) { return buildCreateRoom(context); } else { final user = users[index - 1]; return buildActiveUser(context, user); } }, ); Widget buildActiveUser(BuildContext context, User user) => Container( width: 75, padding: const EdgeInsets.all(4), child: GestureDetector( onTap: () async { final currentChannel = await StreamChannelApi.searchChannel( idUser: user.idUser, username: user.name, ); if (currentChannel == null) { final channel = await StreamChannelApi.createChannelWithUsers( context, name: user.name, urlImage: user.imageUrl, idMembers: [user.idUser], ); Navigator.of(context).push(MaterialPageRoute( builder: (context) => ChatPageMobile(channel: channel), )); } else { Navigator.of(context).push(MaterialPageRoute( builder: (context) => ChatPageMobile(channel: currentChannel), )); } }, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ ProfileImageWidget( imageUrl: user.imageUrl, radius: 25, ), Text( user.name, maxLines: 2, textAlign: TextAlign.center, ) ], ), ), ); Widget buildCreateRoom(BuildContext context) => GestureDetector( onTap: () => Navigator.pushNamed(context, AppRoutes.participants), child: Container( width: 75, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ CircleAvatar( backgroundColor: Colors.grey.shade100, child: Icon(Icons.video_call, size: 28, color: Colors.black), radius: 25, ), Text( 'Create\nRoom', style: TextStyle(fontSize: 14), ), ], ), ), ); }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/widget/user_image_widget.dart
import 'package:chat_ui_stream_iii_example/page/profile_page.dart'; import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class UserImageWidget extends StatelessWidget { @override Widget build(BuildContext context) { final user = StreamChat.of(context).user; final urlImage = user.extraData['image']; return GestureDetector( onTap: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => ProfilePage(), )), child: Container( padding: const EdgeInsets.all(12), child: CircleAvatar( backgroundImage: NetworkImage(urlImage), ), ), ); } }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/widget/stories_grid_widget.dart
import 'package:chat_ui_stream_iii_example/api/stream_story_api.dart'; import 'package:chat_ui_stream_iii_example/model/user_story.dart'; import 'package:chat_ui_stream_iii_example/widget/story_card_widget.dart'; import 'package:flutter/material.dart'; class StoriesGridWidget extends StatelessWidget { @override Widget build(BuildContext context) { return FutureBuilder<List<UserStory>>( future: StreamStoryApi.getStories(), builder: (context, snapshot) { final double padding = 10; switch (snapshot.connectionState) { case ConnectionState.waiting: return Center(child: CircularProgressIndicator()); default: if (snapshot.hasError) { return Center(child: Text('Something Went Wrong Try later')); } else { final stories = snapshot.data; return GridView.builder( itemCount: stories.length + 1, padding: EdgeInsets.all(padding), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: padding, mainAxisSpacing: padding, childAspectRatio: 3 / 4, ), itemBuilder: (context, index) { if (index == 0) { return AddStoryCardWidget(); } else { final story = stories[index - 1]; return UserStoryCardWidget(story: story); } }, ); } } }, ); } }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/api/stream_channel_api.dart
import 'dart:io'; import 'package:chat_ui_stream_iii_example/api/firebase_google_api.dart'; import 'package:chat_ui_stream_iii_example/api/stream_api.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart' hide Channel; import 'package:meta/meta.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import 'package:uuid/uuid.dart'; class StreamChannelApi { static Future<Channel> searchChannel({ @required String idUser, @required String username, }) async { final idSelfUser = FirebaseAuth.instance.currentUser.uid; final filter = { 'name': '$username', "members": { "\$in": [idUser, idSelfUser], } }; final channels = await StreamApi.client.queryChannels(filter: filter); return channels.isEmpty ? null : channels.first; } static Future<Channel> createChannel( BuildContext context, { @required String name, @required File imageFile, List<String> idMembers = const [], }) async { final idChannel = Uuid().v4(); final urlImage = await FirebaseGoogleApi.uploadImage('images/$idChannel', imageFile); return createChannelWithUsers( context, name: name, urlImage: urlImage, idMembers: idMembers, idChannel: idChannel, ); } static Future<Channel> createChannelWithUsers( BuildContext context, { @required String name, @required String urlImage, List<String> idMembers = const [], String idChannel, }) async { final id = idChannel ?? Uuid().v4(); final idSelfUser = StreamChat.of(context).user.id; final channel = StreamApi.client.channel( 'messaging', id: id, extraData: { 'name': name, 'image': urlImage, 'members': idMembers..add(idSelfUser), }, ); await channel.create(); await channel.watch(); return channel; } }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/api/stream_user_api.dart
import 'dart:convert'; import 'package:chat_ui_stream_iii_example/api/stream_api.dart'; import 'package:firebase_auth/firebase_auth.dart' hide User; import 'package:flutter/foundation.dart'; import 'package:foundation/model/user_token.dart'; import 'package:foundation/request/authentication_request.dart'; import 'package:foundation/request/authentication_response.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import 'package:chat_ui_stream_iii_example/model/user.dart' as model; import 'package:http/http.dart' as http; import 'firebase_google_api.dart'; class StreamUserApi { static Future<List<model.User>> getAllUsers({bool includeMe = false}) async { final sort = SortOption('last_message_at'); final response = await StreamApi.client.queryUsers(sort: [sort]); final defaultImage = 'https://images.unsplash.com/photo-1580907114587-148483e7bd5f?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80'; final allUsers = response.users .map((user) => model.User( idUser: user.id, name: user.name, imageUrl: user.extraData['image'] ?? defaultImage, isOnline: user.online, )) .toList(); return allUsers; } static Future createUser({ @required String idUser, @required String username, @required String urlImage, }) async { final userToken = await _generateUserToken(idUser: idUser); final user = User( id: idUser, extraData: { 'name': username, 'image': urlImage, }, ); await StreamApi.client.setUser(user, userToken.token); } static Future login({@required String idUser}) async { final userToken = await _generateUserToken(idUser: idUser); final user = User(id: idUser); await StreamApi.client.setUser(user, userToken.token); } static Future<UserToken> _generateUserToken({ @required String idUser, }) async { const urlAuthentication = 'https://us-central1-stream-chat-test-c4556.cloudfunctions.net/createToken'; final headers = <String, String>{ 'Content-Type': 'application/json', }; final request = AuthenticationRequest(idUser: idUser); final json = jsonEncode(request.toJson()); final response = await http.post(urlAuthentication, headers: headers, body: json); if (response.statusCode == 200) { final data = jsonDecode(response.body); final reviewResponse = AuthenticationResponse.fromJson(data); if (reviewResponse.error.isNotEmpty) { throw UnimplementedError( 'Error: generateToken ${reviewResponse.error}'); } else { return reviewResponse.userToken; } } else { throw UnimplementedError('Error: generateToken'); } } static Future logout() async { await FirebaseGoogleApi.logout(); await FirebaseAuth.instance.signOut(); await StreamApi.client.disconnect( clearUser: true, flushOfflineStorage: true, ); } }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/api/stream_api.dart
import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class StreamApi { static const apiKey = '8vntah2jsw8x'; static final client = Client(apiKey, logLevel: Level.SEVERE); }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/api/stream_story_api.dart
import 'dart:convert'; import 'dart:io'; import 'package:chat_ui_stream_iii_example/model/story.dart'; import 'package:chat_ui_stream_iii_example/model/user_story.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import 'package:uuid/uuid.dart'; import 'firebase_google_api.dart'; import 'stream_api.dart'; class StreamStoryApi { static Future addStory(Story story, File imageFile) async { final user = StreamApi.client.state.user; final userJson = user.toJson(); // Upload image final idStory = Uuid().v4(); final urlImage = await FirebaseGoogleApi.uploadImage( 'user/${user.id}/stories/$idStory', imageFile); final newStory = story.copy(imageUrl: urlImage); // Add new stories final currentStories = userJson['stories'] ?? []; final stories = currentStories..add(newStory.toJson()); final newUserJson = userJson..addAll({'stories': stories}); final newUser = User.fromJson(newUserJson); await StreamApi.client.updateUser(newUser); } static Future<List<UserStory>> getStories() async { final sort = SortOption('last_message_at'); final response = await StreamApi.client.queryUsers(sort: [sort]); final allStories = response.users .where((user) => user.extraData['stories'] != null) .map<UserStory>((user) { final storiesJson = user.extraData['stories']; final stories = storiesJson.map<Story>((json) => Story.fromJson(json)).toList(); return UserStory( stories: stories, userName: user.name, userImageUrl: user.extraData['image'], ); }).toList(); return allStories; } }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/api/firebase_google_api.dart
import 'dart:io'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:google_sign_in/google_sign_in.dart'; class FirebaseGoogleApi { static final googleSignIn = GoogleSignIn(); static Future<bool> login() async { final googleUser = await googleSignIn.signIn(); if (googleUser == null) throw Exception('No user'); final googleAuth = await googleUser.authentication; final credential = GoogleAuthProvider.credential( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); final userCredential = await FirebaseAuth.instance.signInWithCredential(credential); return userCredential.additionalUserInfo.isNewUser; } static Future<String> uploadImage(String path, File file) async { final ref = FirebaseStorage.instance.ref(path); final uploadTask = ref.putFile(file); await uploadTask.whenComplete(() {}); return await ref.getDownloadURL(); } static Future logout() async { if (await googleSignIn.isSignedIn()) { await googleSignIn.signOut(); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/provider/google_signin_provider.dart
import 'package:chat_ui_stream_iii_example/api/firebase_google_api.dart'; import 'package:chat_ui_stream_iii_example/api/stream_api.dart'; import 'package:chat_ui_stream_iii_example/api/stream_user_api.dart'; import 'package:chat_ui_stream_iii_example/app_routes.dart'; import 'package:chat_ui_stream_iii_example/main.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class GoogleSignInProvider extends ChangeNotifier { bool _isSignedIn = false; GoogleSignInProvider() { _listenStatus(); } Future _listenStatus() async { final connectionStatus = StreamApi.client.wsConnectionStatus; connectionStatus.addListener(() { final navigator = MyApp.navigatorKey.currentState; final status = connectionStatus.value; switch (status) { case ConnectionStatus.connected: if (_isSignedIn) return; _isSignedIn = true; navigator.pushNamedAndRemoveUntil( AppRoutes.home, ModalRoute.withName('/'), ); break; case ConnectionStatus.disconnected: final isSignedInFirebase = FirebaseAuth.instance.currentUser != null; if (isSignedInFirebase) return; _isSignedIn = false; navigator.pushNamedAndRemoveUntil( AppRoutes.auth, ModalRoute.withName('/'), ); break; default: break; } }); } Future login() async { try { final isNewUser = await FirebaseGoogleApi.login(); final userFirebase = FirebaseAuth.instance.currentUser; if (isNewUser) { await StreamUserApi.createUser( idUser: userFirebase.uid, username: userFirebase.displayName, urlImage: userFirebase.photoURL, ); } else { await StreamUserApi.login(idUser: userFirebase.uid); } } catch (e) {} notifyListeners(); } void logout() async => StreamUserApi.logout(); }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/provider/channel_provider.dart
import 'package:flutter/foundation.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; /// For Web class ChannelProvider extends ChangeNotifier { Channel _selectedChannel; Channel get selectedChannel => _selectedChannel; void setChannel(Channel channel) { _selectedChannel = channel; notifyListeners(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/lib
mirrored_repositories/chat_ui_stream_iii_example/lib/utils/utils.dart
import 'dart:async'; import 'package:cloud_firestore/cloud_firestore.dart'; class Utils { static DateTime toDateTime(dynamic value) { if (value == null) return null; return DateTime.tryParse(value); } static dynamic fromDateTimeToJson(DateTime date) { if (date == null) return null; return date.toIso8601String(); } static List<Map<String, dynamic>> toJsonList<E>(json) => json == null ? [] : json .map<Map<String, dynamic>>((map) => Map<String, dynamic>.from(map)) .toList(); }
0
mirrored_repositories/chat_ui_stream_iii_example/foundation/lib
mirrored_repositories/chat_ui_stream_iii_example/foundation/lib/model/user_token.dart
import 'package:meta/meta.dart'; class UserToken { final String token; final String idUser; const UserToken({ @required this.token, @required this.idUser, }); UserToken copy({ String token, String idUser, }) => UserToken( token: token ?? this.token, idUser: idUser ?? this.idUser, ); static UserToken fromJson(Map<String, dynamic> json) => UserToken( token: json['token'], idUser: json['idUser'], ); Map<String, dynamic> toJson() => { 'token': token, 'idUser': idUser, }; }
0
mirrored_repositories/chat_ui_stream_iii_example/foundation/lib
mirrored_repositories/chat_ui_stream_iii_example/foundation/lib/request/authentication_request.dart
import 'package:meta/meta.dart'; class AuthenticationRequest { final String idUser; const AuthenticationRequest({ @required this.idUser, }); AuthenticationRequest copy({ String idUser, }) => AuthenticationRequest( idUser: idUser ?? this.idUser, ); static AuthenticationRequest fromJson(Map<String, dynamic> json) => AuthenticationRequest( idUser: json['idUser'], ); Map<String, dynamic> toJson() => { 'idUser': idUser, }; @override String toString() => 'AuthenticationRequest{idUser: $idUser}'; }
0
mirrored_repositories/chat_ui_stream_iii_example/foundation/lib
mirrored_repositories/chat_ui_stream_iii_example/foundation/lib/request/authentication_response.dart
import '../model/user_token.dart'; class AuthenticationResponse { final UserToken userToken; final String error; const AuthenticationResponse({ this.userToken, this.error = '', }); AuthenticationResponse copy({ bool userToken, String error, }) => AuthenticationResponse( userToken: userToken ?? this.userToken, error: error ?? this.error, ); static AuthenticationResponse fromJson(Map<String, dynamic> json) => AuthenticationResponse( userToken: json['userToken'] == null ? null : UserToken.fromJson(Map<String, dynamic>.from(json['userToken'])), error: json['error'], ); Map<String, dynamic> toJson() => { 'userToken': userToken == null ? null : userToken.toJson(), 'error': error, }; @override String toString() => 'AuthenticationResponse{userToken: $userToken, error: $error}'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/scratch_space/scratch_space.dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. export 'src/scratch_space.dart' show ScratchSpace, canonicalUriFor, EmptyOutputException;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/scratch_space
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/scratch_space/src/scratch_space.dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:build/build.dart'; import 'package:crypto/crypto.dart'; import 'package:path/path.dart' as p; import 'package:pedantic/pedantic.dart'; import 'package:pool/pool.dart'; import 'util.dart'; /// Pool for async file writes, we don't want to use too many file handles. final _descriptorPool = Pool(32); /// An on-disk temporary environment for running executables that don't have /// a standard Dart library API. class ScratchSpace { /// Whether or not this scratch space still exists. bool exists = true; /// The `packages` directory under the temp directory. final Directory packagesDir; /// The temp directory at the root of this [ScratchSpace]. final Directory tempDir; // Assets which have a file created but are still being written to. final _pendingWrites = <AssetId, Future<void>>{}; final _digests = <AssetId, Digest>{}; ScratchSpace._(this.tempDir) : packagesDir = Directory(p.join(tempDir.path, 'packages')); factory ScratchSpace() { var tempDir = Directory(Directory.systemTemp .createTempSync('scratch_space') .resolveSymbolicLinksSync()); return ScratchSpace._(tempDir); } /// Copies [id] from the tmp dir and writes it back using the [writer]. /// /// Note that [BuildStep] implements [AssetWriter] and that is typically /// what you will want to pass in. /// /// This must be called for all outputs which you want to be included as a /// part of the actual build (any other outputs will be deleted with the /// tmp dir and won't be available to other [Builder]s). /// /// If [requireContent] is true and the file is empty an /// [EmptyOutputException] is thrown. Future copyOutput(AssetId id, AssetWriter writer, {bool requireContent = false}) async { var file = fileFor(id); var bytes = await _descriptorPool.withResource(file.readAsBytes); if (requireContent && bytes.isEmpty) throw EmptyOutputException(id); await writer.writeAsBytes(id, bytes); } /// Deletes the temp directory for this environment. /// /// This class is no longer valid once the directory is deleted, you must /// create a new [ScratchSpace]. Future delete() async { if (!exists) { throw StateError( 'Tried to delete a ScratchSpace which was already deleted'); } exists = false; _digests.clear(); if (_pendingWrites.isNotEmpty) { try { await Future.wait(_pendingWrites.values); } catch (_) { // Ignore any errors, we are essentially just draining this queue // of pending writes but don't care about the result. } } return tempDir.delete(recursive: true); } /// Copies [assetIds] to [tempDir] if they don't exist, using [reader] to /// read assets and mark dependencies. /// /// Note that [BuildStep] implements [AssetReader] and that is typically /// what you will want to pass in. /// /// Any asset that is under a `lib` dir will be output under a `packages` /// directory corresponding to its package, and any other assets are output /// directly under the temp dir using their unmodified path. Future ensureAssets(Iterable<AssetId> assetIds, AssetReader reader) { if (!exists) { throw StateError('Tried to use a deleted ScratchSpace!'); } var futures = assetIds.map((id) async { var digest = await reader.digest(id); var existing = _digests[id]; if (digest == existing) { await _pendingWrites[id]; return; } _digests[id] = digest; try { await _pendingWrites.putIfAbsent( id, () => _descriptorPool.withResource(() async { var file = fileFor(id); if (await file.exists()) { await file.delete(); } await file.create(recursive: true); await file.writeAsBytes(await reader.readAsBytes(id)); })); } finally { unawaited(_pendingWrites.remove(id)); } }).toList(); return Future.wait(futures); } /// Returns the actual [File] in this environment corresponding to [id]. /// /// The returned [File] may or may not already exist. Call [ensureAssets] /// with [id] to make sure it is actually present. File fileFor(AssetId id) => File(p.join(tempDir.path, p.normalize(_relativePathFor(id)))); } /// Returns a canonical uri for [id]. /// /// If [id] is under a `lib` directory then this returns a `package:` uri, /// otherwise it just returns [id#path]. String canonicalUriFor(AssetId id) { if (topLevelDir(id.path) == 'lib') { var packagePath = p.url.join(id.package, p.url.joinAll(p.url.split(id.path).skip(1))); return 'package:$packagePath'; } else { return id.path; } } /// The path relative to the root of the environment for a given [id]. String _relativePathFor(AssetId id) => canonicalUriFor(id).replaceFirst('package:', 'packages/'); /// An indication that an output file which was expect to be non-empty had no /// content. class EmptyOutputException implements Exception { final AssetId id; EmptyOutputException(this.id); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/scratch_space
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/scratch_space/src/util.dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:path/path.dart' as p; /// Returns the top level directory in [uri]. /// /// Throws an [ArgumentError] if [uri] reaches above the top level directory. String topLevelDir(String uri) { var parts = p.url.split(p.url.normalize(uri)); if (parts.first == '..') { throw ArgumentError('Cannot compute top level dir for path `$uri` ' 'which reaches outside the root directory.'); } return parts.length == 1 ? null : parts.first; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation/json_annotation.dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Provides annotation classes to use with /// [json_serializable](https://pub.dev/packages/json_serializable). /// /// Also contains helper functions and classes – prefixed with `$` used by /// `json_serializable` when the `use_wrappers` or `checked` options are /// enabled. library json_annotation; export 'src/allowed_keys_helpers.dart'; export 'src/checked_helpers.dart'; export 'src/json_converter.dart'; export 'src/json_key.dart'; export 'src/json_literal.dart'; export 'src/json_serializable.dart'; export 'src/json_value.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation/src/json_serializable.dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'allowed_keys_helpers.dart'; import 'checked_helpers.dart'; import 'json_key.dart'; part 'json_serializable.g.dart'; /// Values for the automatic field renaming behavior for [JsonSerializable]. enum FieldRename { /// Use the field name without changes. none, /// Encodes a field named `kebabCase` with a JSON key `kebab-case`. kebab, /// Encodes a field named `snakeCase` with a JSON key `snake_case`. snake, /// Encodes a field named `pascalCase` with a JSON key `PascalCase`. pascal } /// An annotation used to specify a class to generate code for. @JsonSerializable( checked: true, disallowUnrecognizedKeys: true, fieldRename: FieldRename.snake, ) class JsonSerializable { /// If `true`, [Map] types are *not* assumed to be [Map<String, dynamic>] /// – which is the default type of [Map] instances return by JSON decode in /// `dart:convert`. /// /// This will increase the code size, but allows [Map] types returned /// from other sources, such as `package:yaml`. /// /// *Note: in many cases the key values are still assumed to be [String]*. final bool anyMap; /// If `true`, generated `fromJson` functions include extra checks to validate /// proper deserialization of types. /// /// If an exception is thrown during deserialization, a /// [CheckedFromJsonException] is thrown. final bool checked; /// If `true` (the default), a private, static `_$ExampleFromJson` method /// is created in the generated part file. /// /// Call this method from a factory constructor added to the source class: /// /// ```dart /// @JsonSerializable() /// class Example { /// // ... /// factory Example.fromJson(Map<String, dynamic> json) => /// _$ExampleFromJson(json); /// } /// ``` final bool createFactory; /// If `true` (the default), A top-level function is created that you can /// reference from your class. /// /// ```dart /// @JsonSerializable() /// class Example { /// Map<String, dynamic> toJson() => _$ExampleToJson(this); /// } /// ``` final bool createToJson; /// If `false` (the default), then the generated `FromJson` function will /// ignore unrecognized keys in the provided JSON [Map]. /// /// If `true`, unrecognized keys will cause an [UnrecognizedKeysException] to /// be thrown. final bool disallowUnrecognizedKeys; /// If `true`, generated `toJson` methods will explicitly call `toJson` on /// nested objects. /// /// When using JSON encoding support in `dart:convert`, `toJson` is /// automatically called on objects, so the default behavior /// (`explicitToJson: false`) is to omit the `toJson` call. /// /// Example of `explicitToJson: false` (default) /// /// ```dart /// Map<String, dynamic> toJson() => {'child': child}; /// ``` /// /// Example of `explicitToJson: true` /// /// ```dart /// Map<String, dynamic> toJson() => {'child': child?.toJson()}; /// ``` final bool explicitToJson; /// Defines the automatic naming strategy when converting class field names /// into JSON map keys. /// /// With a value [FieldRename.none] (the default), the name of the field is /// used without modification. /// /// See [FieldRename] for details on the other options. /// /// Note: the value for [JsonKey.name] takes precedence over this option for /// fields annotated with [JsonKey]. final FieldRename fieldRename; /// When `true` on classes with type parameters (generic types), extra /// "helper" parameters will be generated for `fromJson` and/or `toJson` to /// support serializing values of those types. /// /// For example, the generated code for /// /// ```dart /// @JsonSerializable(genericArgumentFactories: true) /// class Response<T> { /// int status; /// T value; /// } /// ``` /// /// Looks like /// /// ```dart /// Response<T> _$ResponseFromJson<T>( /// Map<String, dynamic> json, /// T Function(Object json) fromJsonT, /// ) { /// return Response<T>() /// ..status = json['status'] as int /// ..value = fromJsonT(json['value']); /// } /// /// Map<String, dynamic> _$ResponseToJson<T>( /// Response<T> instance, /// Object Function(T value) toJsonT, /// ) => /// <String, dynamic>{ /// 'status': instance.status, /// 'value': toJsonT(instance.value), /// }; /// ``` /// /// Notes: /// /// 1. This option has no effect on classes without type parameters. /// If used on such a class, a warning is echoed in the build log. /// 1. If this option is set for all classes in a package via `build.yaml` /// it is only applied to classes with type parameters – so no warning is /// echoed. final bool genericArgumentFactories; /// When `true`, only fields annotated with [JsonKey] will have code /// generated. /// /// It will have the same effect as if those fields had been annotated with /// `@JsonKey(ignore: true)`. final bool ignoreUnannotated; /// Whether the generator should include fields with `null` values in the /// serialized output. /// /// If `true` (the default), all fields are written to JSON, even if they are /// `null`. /// /// If a field is annotated with `JsonKey` with a non-`null` value for /// `includeIfNull`, that value takes precedent. final bool includeIfNull; /// When `true` (the default), `null` fields are handled gracefully when /// encoding to JSON and when decoding `null` and nonexistent values from /// JSON. /// /// Setting to `false` eliminates `null` verification in the generated code, /// which reduces the code size. Errors may be thrown at runtime if `null` /// values are encountered, but the original class should also implement /// `null` runtime validation if it's critical. final bool nullable; /// Creates a new [JsonSerializable] instance. const JsonSerializable({ this.anyMap, this.checked, this.createFactory, this.createToJson, this.disallowUnrecognizedKeys, this.explicitToJson, this.fieldRename, this.ignoreUnannotated, this.includeIfNull, this.nullable, this.genericArgumentFactories, }); factory JsonSerializable.fromJson(Map<String, dynamic> json) => _$JsonSerializableFromJson(json); /// An instance of [JsonSerializable] with all fields set to their default /// values. static const defaults = JsonSerializable( anyMap: false, checked: false, createFactory: true, createToJson: true, disallowUnrecognizedKeys: false, explicitToJson: false, fieldRename: FieldRename.none, ignoreUnannotated: false, includeIfNull: true, nullable: true, genericArgumentFactories: false, ); /// Returns a new [JsonSerializable] instance with fields equal to the /// corresponding values in `this`, if not `null`. /// /// Otherwise, the returned value has the default value as defined in /// [defaults]. JsonSerializable withDefaults() => JsonSerializable( anyMap: anyMap ?? defaults.anyMap, checked: checked ?? defaults.checked, createFactory: createFactory ?? defaults.createFactory, createToJson: createToJson ?? defaults.createToJson, disallowUnrecognizedKeys: disallowUnrecognizedKeys ?? defaults.disallowUnrecognizedKeys, explicitToJson: explicitToJson ?? defaults.explicitToJson, fieldRename: fieldRename ?? defaults.fieldRename, ignoreUnannotated: ignoreUnannotated ?? defaults.ignoreUnannotated, includeIfNull: includeIfNull ?? defaults.includeIfNull, nullable: nullable ?? defaults.nullable, genericArgumentFactories: genericArgumentFactories ?? defaults.genericArgumentFactories, ); Map<String, dynamic> toJson() => _$JsonSerializableToJson(this); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation/src/json_serializable.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'json_serializable.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** JsonSerializable _$JsonSerializableFromJson(Map<String, dynamic> json) { return $checkedNew('JsonSerializable', json, () { $checkKeys(json, allowedKeys: const [ 'any_map', 'checked', 'create_factory', 'create_to_json', 'disallow_unrecognized_keys', 'explicit_to_json', 'field_rename', 'generic_argument_factories', 'ignore_unannotated', 'include_if_null', 'nullable' ]); final val = JsonSerializable( anyMap: $checkedConvert(json, 'any_map', (v) => v as bool), checked: $checkedConvert(json, 'checked', (v) => v as bool), createFactory: $checkedConvert(json, 'create_factory', (v) => v as bool), createToJson: $checkedConvert(json, 'create_to_json', (v) => v as bool), disallowUnrecognizedKeys: $checkedConvert(json, 'disallow_unrecognized_keys', (v) => v as bool), explicitToJson: $checkedConvert(json, 'explicit_to_json', (v) => v as bool), fieldRename: $checkedConvert(json, 'field_rename', (v) => _$enumDecodeNullable(_$FieldRenameEnumMap, v)), ignoreUnannotated: $checkedConvert(json, 'ignore_unannotated', (v) => v as bool), includeIfNull: $checkedConvert(json, 'include_if_null', (v) => v as bool), nullable: $checkedConvert(json, 'nullable', (v) => v as bool), genericArgumentFactories: $checkedConvert(json, 'generic_argument_factories', (v) => v as bool), ); return val; }, fieldKeyMap: const { 'anyMap': 'any_map', 'createFactory': 'create_factory', 'createToJson': 'create_to_json', 'disallowUnrecognizedKeys': 'disallow_unrecognized_keys', 'explicitToJson': 'explicit_to_json', 'fieldRename': 'field_rename', 'ignoreUnannotated': 'ignore_unannotated', 'includeIfNull': 'include_if_null', 'genericArgumentFactories': 'generic_argument_factories' }); } Map<String, dynamic> _$JsonSerializableToJson(JsonSerializable instance) => <String, dynamic>{ 'any_map': instance.anyMap, 'checked': instance.checked, 'create_factory': instance.createFactory, 'create_to_json': instance.createToJson, 'disallow_unrecognized_keys': instance.disallowUnrecognizedKeys, 'explicit_to_json': instance.explicitToJson, 'field_rename': _$FieldRenameEnumMap[instance.fieldRename], 'generic_argument_factories': instance.genericArgumentFactories, 'ignore_unannotated': instance.ignoreUnannotated, 'include_if_null': instance.includeIfNull, 'nullable': instance.nullable, }; T _$enumDecode<T>( Map<T, dynamic> enumValues, dynamic source, { T unknownValue, }) { if (source == null) { throw ArgumentError('A value must be provided. Supported values: ' '${enumValues.values.join(', ')}'); } final value = enumValues.entries .singleWhere((e) => e.value == source, orElse: () => null) ?.key; if (value == null && unknownValue == null) { throw ArgumentError('`$source` is not one of the supported values: ' '${enumValues.values.join(', ')}'); } return value ?? unknownValue; } T _$enumDecodeNullable<T>( Map<T, dynamic> enumValues, dynamic source, { T unknownValue, }) { if (source == null) { return null; } return _$enumDecode<T>(enumValues, source, unknownValue: unknownValue); } const _$FieldRenameEnumMap = { FieldRename.none: 'none', FieldRename.kebab: 'kebab', FieldRename.snake: 'snake', FieldRename.pascal: 'pascal', };
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation/src/json_value.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// An annotation used to specify how a enum value is serialized. class JsonValue { /// The value to use when serializing and deserializing. /// /// Can be a [String] or an [int]. final dynamic value; const JsonValue(this.value); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation/src/json_key.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'allowed_keys_helpers.dart'; import 'json_serializable.dart'; /// An annotation used to specify how a field is serialized. class JsonKey { /// The value to use if the source JSON does not contain this key or if the /// value is `null`. final Object defaultValue; /// If `true`, generated code will throw a [DisallowedNullValueException] if /// the corresponding key exists, but the value is `null`. /// /// Note: this value does not affect the behavior of a JSON map *without* the /// associated key. /// /// If [disallowNullValue] is `true`, [includeIfNull] will be treated as /// `false` to ensure compatibility between `toJson` and `fromJson`. /// /// If both [includeIfNull] and [disallowNullValue] are set to `true` on the /// same field, an exception will be thrown during code generation. final bool disallowNullValue; /// A [Function] to use when decoding the associated JSON value to the /// annotated field. /// /// Must be a top-level or static [Function] that takes one argument mapping /// a JSON literal to a value compatible with the type of the annotated field. /// /// When creating a class that supports both `toJson` and `fromJson` /// (the default), you should also set [toJson] if you set [fromJson]. /// Values returned by [toJson] should "round-trip" through [fromJson]. final Function fromJson; /// `true` if the generator should ignore this field completely. /// /// If `null` (the default) or `false`, the field will be considered for /// serialization. final bool ignore; /// Whether the generator should include fields with `null` values in the /// serialized output. /// /// If `true`, the generator should include the field in the serialized /// output, even if the value is `null`. /// /// The default value, `null`, indicates that the behavior should be /// acquired from the [JsonSerializable.includeIfNull] annotation on the /// enclosing class. /// /// If [disallowNullValue] is `true`, this value is treated as `false` to /// ensure compatibility between `toJson` and `fromJson`. /// /// If both [includeIfNull] and [disallowNullValue] are set to `true` on the /// same field, an exception will be thrown during code generation. final bool includeIfNull; /// The key in a JSON map to use when reading and writing values corresponding /// to the annotated fields. /// /// If `null`, the field name is used. final String name; /// When `true`, `null` fields are handled gracefully when encoding to JSON /// and when decoding `null` and nonexistent values from JSON. /// /// Setting to `false` eliminates `null` verification in the generated code /// for the annotated field, which reduces the code size. Errors may be thrown /// at runtime if `null` values are encountered, but the original class should /// also implement `null` runtime validation if it's critical. /// /// The default value, `null`, indicates that the behavior should be /// acquired from the [JsonSerializable.nullable] annotation on the /// enclosing class. final bool nullable; /// When `true`, generated code for `fromJson` will verify that the source /// JSON map contains the associated key. /// /// If the key does not exist, a [MissingRequiredKeysException] exception is /// thrown. /// /// Note: only the existence of the key is checked. A key with a `null` value /// is considered valid. final bool required; /// A [Function] to use when encoding the annotated field to JSON. /// /// Must be a top-level or static [Function] with one parameter compatible /// with the field being serialized that returns a JSON-compatible value. /// /// When creating a class that supports both `toJson` and `fromJson` /// (the default), you should also set [fromJson] if you set [toJson]. /// Values returned by [toJson] should "round-trip" through [fromJson]. final Function toJson; /// The value to use for an enum field when the value provided is not in the /// source enum. /// /// Valid only on enum fields with a compatible enum value. final Object unknownEnumValue; /// Creates a new [JsonKey] instance. /// /// Only required when the default behavior is not desired. const JsonKey({ this.defaultValue, this.disallowNullValue, this.fromJson, this.ignore, this.includeIfNull, this.name, this.nullable, this.required, this.toJson, this.unknownEnumValue, }); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation/src/allowed_keys_helpers.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Helper function used in generated `fromJson` code when /// `JsonSerializable.disallowUnrecognizedKeys` is true for an annotated type or /// `JsonKey.required` is `true` for any annotated fields. /// /// Should not be used directly. void $checkKeys(Map map, {List<String> allowedKeys, List<String> requiredKeys, List<String> disallowNullValues}) { if (map != null && allowedKeys != null) { final invalidKeys = map.keys.cast<String>().where((k) => !allowedKeys.contains(k)).toList(); if (invalidKeys.isNotEmpty) { throw UnrecognizedKeysException(invalidKeys, map, allowedKeys); } } if (requiredKeys != null) { final missingKeys = requiredKeys.where((k) => !map.keys.contains(k)).toList(); if (missingKeys.isNotEmpty) { throw MissingRequiredKeysException(missingKeys, map); } } if (map != null && disallowNullValues != null) { final nullValuedKeys = map.entries .where((entry) => disallowNullValues.contains(entry.key) && entry.value == null) .map((entry) => entry.key as String) .toList(); if (nullValuedKeys.isNotEmpty) { throw DisallowedNullValueException(nullValuedKeys, map); } } } /// A base class for exceptions thrown when decoding JSON. abstract class BadKeyException implements Exception { BadKeyException._(this.map); /// The source [Map] that the unrecognized keys were found in. final Map map; /// A human-readable message corresponding to the error. String get message; } /// Exception thrown if there are unrecognized keys in a JSON map that was /// provided during deserialization. class UnrecognizedKeysException extends BadKeyException { /// The allowed keys for [map]. final List<String> allowedKeys; /// The keys from [map] that were unrecognized. final List<String> unrecognizedKeys; @override String get message => 'Unrecognized keys: [${unrecognizedKeys.join(', ')}]; supported keys: ' '[${allowedKeys.join(', ')}]'; UnrecognizedKeysException(this.unrecognizedKeys, Map map, this.allowedKeys) : super._(map); @override String toString() => message; } /// Exception thrown if there are missing required keys in a JSON map that was /// provided during deserialization. class MissingRequiredKeysException extends BadKeyException { /// The keys that [map] is missing. final List<String> missingKeys; @override String get message => 'Required keys are missing: ${missingKeys.join(', ')}.'; MissingRequiredKeysException(this.missingKeys, Map map) : assert(missingKeys.isNotEmpty), super._(map); } /// Exception thrown if there are keys with disallowed `null` values in a JSON /// map that was provided during deserialization. class DisallowedNullValueException extends BadKeyException { final List<String> keysWithNullValues; DisallowedNullValueException(this.keysWithNullValues, Map map) : super._(map); @override String get message => 'These keys had `null` values, ' 'which is not allowed: $keysWithNullValues'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation/src/json_converter.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Implement this class to provide custom converters for a specific [Type]. /// /// [T] is the data type you'd like to convert to and from. /// /// [S] is the type of the value stored in JSON. It must be a valid JSON type /// such as [String], [int], or [Map<String, dynamic>]. abstract class JsonConverter<T, S> { T fromJson(S json); S toJson(T object); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation/src/json_literal.dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// An annotation used to generate a private field containing the contents of a /// JSON file. /// /// The annotation can be applied to any member, but usually it's applied to /// top-level getter. /// /// In this example, the JSON content of `data.json` is populated into a /// top-level, final field `_$glossaryDataJsonLiteral` in the generated file. /// /// ```dart /// @JsonLiteral('data.json') /// Map get glossaryData => _$glossaryDataJsonLiteral; /// ``` class JsonLiteral { /// The relative path from the Dart file with the annotation to the file /// containing the source JSON. final String path; /// `true` if the JSON literal should be written as a constant. final bool asConst; /// Creates a new [JsonLiteral] instance. const JsonLiteral(this.path, {bool asConst = false}) : asConst = asConst ?? false; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/json_annotation/src/checked_helpers.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'allowed_keys_helpers.dart'; /// Helper function used in generated code when /// `JsonSerializableGenerator.checked` is `true`. /// /// Should not be used directly. T $checkedNew<T>(String className, Map map, T Function() constructor, {Map<String, String> fieldKeyMap}) { fieldKeyMap ??= const {}; try { return constructor(); } on CheckedFromJsonException catch (e) { if (identical(e.map, map) && e._className == null) { e._className = className; } rethrow; } catch (error, stack) { String key; if (error is ArgumentError) { key = fieldKeyMap[error.name] ?? error.name; } else if (error is MissingRequiredKeysException) { key = error.missingKeys.first; } else if (error is DisallowedNullValueException) { key = error.keysWithNullValues.first; } throw CheckedFromJsonException._(error, stack, map, key, className: className); } } /// Helper function used in generated code when /// `JsonSerializableGenerator.checked` is `true`. /// /// Should not be used directly. T $checkedConvert<T>(Map map, String key, T Function(Object) castFunc) { try { return castFunc(map[key]); } on CheckedFromJsonException { rethrow; } catch (error, stack) { throw CheckedFromJsonException._(error, stack, map, key); } } /// Exception thrown if there is a runtime exception in `fromJson` /// code generated when `JsonSerializableGenerator.checked` is `true` class CheckedFromJsonException implements Exception { /// The [Error] or [Exception] that triggered this exception. /// /// If this instance was created by user code, this field will be `null`. final Object innerError; /// The [StackTrace] for the [Error] or [Exception] that triggered this /// exception. /// /// If this instance was created by user code, this field will be `null`. final StackTrace innerStack; /// The key from [map] that corresponds to the thrown [innerError]. /// /// May be `null`. final String key; /// The source [Map] that was used for decoding when the [innerError] was /// thrown. final Map map; /// A human-readable message corresponding to [innerError]. /// /// May be `null`. final String message; /// The name of the class being created when [innerError] was thrown. String get className => _className; String _className; /// If this was thrown due to an invalid or unsupported key, as opposed to an /// invalid value. final bool badKey; /// Creates a new instance of [CheckedFromJsonException]. CheckedFromJsonException( this.map, this.key, String className, this.message, { bool badKey = false, }) : _className = className, badKey = badKey ?? false, innerError = null, innerStack = null; CheckedFromJsonException._( this.innerError, this.innerStack, this.map, this.key, { String className, }) : _className = className, badKey = innerError is BadKeyException, message = _getMessage(innerError); static String _getMessage(Object error) { if (error is ArgumentError) { return error.message?.toString(); } else if (error is BadKeyException) { return error.message; } else if (error is FormatException) { var message = error.message; if (error.offset != null) { message = '$message at offset ${error.offset}.'; } return message; } return error.toString(); } @override String toString() => <String>[ 'CheckedFromJsonException', if (_className != null) 'Could not create `$_className`.', if (key != null) 'There is a problem with "$key".', if (message != null) message, if (message == null && innerError != null) innerError.toString(), ].join('\n'); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/foundation
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/foundation/model/user_token.dart
import 'package:meta/meta.dart'; class UserToken { final String token; final String idUser; const UserToken({ @required this.token, @required this.idUser, }); UserToken copy({ String token, String idUser, }) => UserToken( token: token ?? this.token, idUser: idUser ?? this.idUser, ); static UserToken fromJson(Map<String, dynamic> json) => UserToken( token: json['token'], idUser: json['idUser'], ); Map<String, dynamic> toJson() => { 'token': token, 'idUser': idUser, }; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/foundation
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/foundation/request/authentication_request.dart
import 'package:meta/meta.dart'; class AuthenticationRequest { final String idUser; const AuthenticationRequest({ @required this.idUser, }); AuthenticationRequest copy({ String idUser, }) => AuthenticationRequest( idUser: idUser ?? this.idUser, ); static AuthenticationRequest fromJson(Map<String, dynamic> json) => AuthenticationRequest( idUser: json['idUser'], ); Map<String, dynamic> toJson() => { 'idUser': idUser, }; @override String toString() => 'AuthenticationRequest{idUser: $idUser}'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/foundation
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/foundation/request/authentication_response.dart
import '../model/user_token.dart'; class AuthenticationResponse { final UserToken userToken; final String error; const AuthenticationResponse({ this.userToken, this.error = '', }); AuthenticationResponse copy({ bool userToken, String error, }) => AuthenticationResponse( userToken: userToken ?? this.userToken, error: error ?? this.error, ); static AuthenticationResponse fromJson(Map<String, dynamic> json) => AuthenticationResponse( userToken: json['userToken'] == null ? null : UserToken.fromJson(Map<String, dynamic>.from(json['userToken'])), error: json['error'], ); Map<String, dynamic> toJson() => { 'userToken': userToken == null ? null : userToken.toJson(), 'error': error, }; @override String toString() => 'AuthenticationResponse{userToken: $userToken, error: $error}'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/async_serializer.dart
// Copyright (c) 2017, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'dart:async'; import 'package:built_value/serializer.dart'; /// Deserializer for `BuiltList` that runs asynchronously. /// /// If you need to deserialize large payloads without blocking, arrange that /// the top level serialized object is a `BuiltList`. Then use this class to /// deserialize to a [Stream] of objects. class BuiltListAsyncDeserializer { Stream<Object> deserialize(Serializers serializers, Iterable serialized, {FullType specifiedType = FullType.unspecified}) async* { var elementType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[0]; for (var item in serialized) { yield serializers.deserialize(item, specifiedType: elementType); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/iso_8601_date_time_serializer.dart
// Copyright (c) 2018, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; /// Alternative serializer for [DateTime]. /// /// Install this to use ISO8601 format instead of the default (microseconds /// since epoch). Use [SerializersBuilder.add] to install it. /// /// An exception will be thrown on attempt to serialize local DateTime /// instances; you must use UTC. class Iso8601DateTimeSerializer implements PrimitiveSerializer<DateTime> { final bool structured = false; @override final Iterable<Type> types = BuiltList<Type>([DateTime]); @override final String wireName = 'DateTime'; @override Object serialize(Serializers serializers, DateTime dateTime, {FullType specifiedType = FullType.unspecified}) { if (!dateTime.isUtc) { throw ArgumentError.value( dateTime, 'dateTime', 'Must be in utc for serialization.'); } return dateTime.toIso8601String(); } @override DateTime deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) { return DateTime.parse(serialized as String).toUtc(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/iso_8601_duration_serializer.dart
// Copyright (c) 2019, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; /// Alternative serializer for [Duration]. /// /// Install this to use ISO8601 compatible format instead of the default /// (microseconds). Use [SerializersBuilder.add] to install it. /// /// Note that this serializer is not 100% compatible with the ISO8601 format /// due to limitations of the [Duration] class, but is designed to produce and /// consume reasonable strings that match the standard. class Iso8601DurationSerializer extends PrimitiveSerializer<Duration> { @override Duration deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) => _parseDuration(serialized); @override Object serialize(Serializers serializers, Duration object, {FullType specifiedType = FullType.unspecified}) => _writeIso8601Duration(object); @override Iterable<Type> get types => BuiltList(const [Duration]); @override String get wireName => 'Duration'; Duration _parseDuration(String value) { final match = _parseFormat.firstMatch(value); if (match == null) { throw FormatException('Invalid duration format', value); } // Iterate through the capture groups to build the unit mappings. final unitMappings = <String, int>{}; // Start iterating at 1, because match[0] is the full match. for (var i = 1; i <= match.groupCount; i++) { final group = match[i]; if (group == null) continue; // Get all but last character in group. // The RegExp ensures this must be an int. final value = int.parse(group.substring(0, group.length - 1)); // Get last character. final unit = group.substring(group.length - 1); unitMappings[unit] = value; } return Duration( days: unitMappings[_dayToken] ?? 0, hours: unitMappings[_hourToken] ?? 0, minutes: unitMappings[_minuteToken] ?? 0, seconds: unitMappings[_secondToken] ?? 0, ); } String _writeIso8601Duration(Duration duration) { if (duration == Duration.zero) { return 'PT0S'; } final days = duration.inDays; final hours = (duration - Duration(days: days)).inHours; final minutes = (duration - Duration(days: days, hours: hours)).inMinutes; final seconds = (duration - Duration(days: days, hours: hours, minutes: minutes)) .inSeconds; final remainder = duration - Duration(days: days, hours: hours, minutes: minutes, seconds: seconds); if (remainder != Duration.zero) { throw ArgumentError.value(duration, 'duration', 'Contains sub-second data which cannot be serialized.'); } final buffer = StringBuffer(_durationToken) ..write(days == 0 ? '' : '$days$_dayToken'); if (!(hours == 0 && minutes == 0 && seconds == 0)) { buffer ..write(_timeToken) ..write(hours == 0 ? '' : '$hours$_hourToken') ..write(minutes == 0 ? '' : '$minutes$_minuteToken') ..write(seconds == 0 ? '' : '$seconds$_secondToken'); } return buffer.toString(); } // The unit tokens. static const _durationToken = 'P'; static const _dayToken = 'D'; static const _timeToken = 'T'; static const _hourToken = 'H'; static const _minuteToken = 'M'; static const _secondToken = 'S'; // The parse format for ISO8601 durations. static final _parseFormat = RegExp( '^P(?!\$)(0D|[1-9][0-9]*D)?' '(?:T(?!\$)(0H|[1-9][0-9]*H)?(0M|[1-9][0-9]*M)?(0S|[1-9][0-9]*S)?)?\$', ); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/serializer.dart
// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/src/big_int_serializer.dart'; import 'package:built_value/src/date_time_serializer.dart'; import 'package:built_value/src/duration_serializer.dart'; import 'package:built_value/src/int64_serializer.dart'; import 'package:built_value/src/json_object_serializer.dart'; import 'package:built_value/src/num_serializer.dart'; import 'package:built_value/src/uri_serializer.dart'; import 'package:quiver/core.dart'; import 'src/bool_serializer.dart'; import 'src/built_json_serializers.dart'; import 'src/built_list_multimap_serializer.dart'; import 'src/built_list_serializer.dart'; import 'src/built_map_serializer.dart'; import 'src/built_set_multimap_serializer.dart'; import 'src/built_set_serializer.dart'; import 'src/double_serializer.dart'; import 'src/int_serializer.dart'; import 'src/regexp_serializer.dart'; import 'src/string_serializer.dart'; /// Annotation to trigger code generation of a [Serializers] instance. /// /// Use like this: /// /// ``` /// @SerializersFor(const [ /// MySerializableClass, /// MyOtherSerializableClass, /// ]) /// final Serializers serializers = _$serializers; /// ``` /// /// The `_$serializers` value will be generated for you in a part file next /// to the current source file. It will hold serializers for the types /// specified plus any types used in their fields, transitively. class SerializersFor { final List<Type> types; const SerializersFor(this.types); } /// Serializes all known classes. /// /// See: https://github.com/google/built_value.dart/tree/master/example abstract class Serializers { /// Default [Serializers] that can serialize primitives and collections. /// /// Use [toBuilder] to add more serializers. factory Serializers() { return (SerializersBuilder() ..add(BigIntSerializer()) ..add(BoolSerializer()) ..add(BuiltListSerializer()) ..add(BuiltListMultimapSerializer()) ..add(BuiltMapSerializer()) ..add(BuiltSetSerializer()) ..add(BuiltSetMultimapSerializer()) ..add(DateTimeSerializer()) ..add(DoubleSerializer()) ..add(DurationSerializer()) ..add(IntSerializer()) ..add(Int64Serializer()) ..add(JsonObjectSerializer()) ..add(NumSerializer()) ..add(RegExpSerializer()) ..add(StringSerializer()) ..add(UriSerializer()) ..addBuilderFactory(const FullType(BuiltList, [FullType.object]), () => ListBuilder<Object>()) ..addBuilderFactory( const FullType( BuiltListMultimap, [FullType.object, FullType.object]), () => ListMultimapBuilder<Object, Object>()) ..addBuilderFactory( const FullType(BuiltMap, [FullType.object, FullType.object]), () => MapBuilder<Object, Object>()) ..addBuilderFactory(const FullType(BuiltSet, [FullType.object]), () => SetBuilder<Object>()) ..addBuilderFactory( const FullType( BuiltSetMultimap, [FullType.object, FullType.object]), () => SetMultimapBuilder<Object, Object>())) .build(); } /// Merges iterable of [Serializers] into a single [Serializers]. /// /// [Serializer] and builder factories are accumulated. Plugins are not. static Serializers merge(Iterable<Serializers> serializersIterable) => (Serializers().toBuilder()..mergeAll(serializersIterable)).build(); /// The installed [Serializer]s. Iterable<Serializer> get serializers; /// Serializes [object]. /// /// A [Serializer] must have been provided for every type the object uses. /// /// Types that are known statically can be provided via [specifiedType]. This /// will reduce the amount of data needed on the wire. The exact same /// [specifiedType] will be needed to deserialize. /// /// Create one using [SerializersBuilder]. /// /// TODO(davidmorgan): document the wire format. Object serialize(Object object, {FullType specifiedType = FullType.unspecified}); /// Convenience method for when you know the type you're serializing. /// Specify the type by specifying its [Serializer] class. Equivalent to /// calling [serialize] with a `specifiedType`. Object serializeWith<T>(Serializer<T> serializer, T object); /// Deserializes [serialized]. /// /// A [Serializer] must have been provided for every type the object uses. /// /// If [serialized] was produced by calling [serialize] with [specifiedType], /// the exact same [specifiedType] must be provided to deserialize. Object deserialize(Object serialized, {FullType specifiedType = FullType.unspecified}); /// Convenience method for when you know the type you're deserializing. /// Specify the type by specifying its [Serializer] class. Equivalent to /// calling [deserialize] with a `specifiedType`. T deserializeWith<T>(Serializer<T> serializer, Object serialized); /// Gets a serializer; returns `null` if none is found. For use in plugins /// and other extension code. Serializer serializerForType(Type type); /// Gets a serializer; returns `null` if none is found. For use in plugins /// and other extension code. Serializer serializerForWireName(String wireName); /// Creates a new builder for the type represented by [fullType]. /// /// For example, if [fullType] is `BuiltList<int, String>`, returns a /// `ListBuilder<int, String>`. This helps serializers to instantiate with /// correct generic type parameters. /// /// Throws a [StateError] if no matching builder factory has been added. Object newBuilder(FullType fullType); /// Whether a builder for [fullType] is available via [newBuilder]. bool hasBuilder(FullType fullType); /// Throws if a builder for [fullType] is not available via [newBuilder]. void expectBuilder(FullType fullType); /// The installed builder factories. BuiltMap<FullType, Function> get builderFactories; SerializersBuilder toBuilder(); } /// Note: this is an experimental feature. API may change without a major /// version increase. abstract class SerializerPlugin { Object beforeSerialize(Object object, FullType specifiedType); Object afterSerialize(Object object, FullType specifiedType); Object beforeDeserialize(Object object, FullType specifiedType); Object afterDeserialize(Object object, FullType specifiedType); } /// Builder for [Serializers]. abstract class SerializersBuilder { factory SerializersBuilder() = BuiltJsonSerializersBuilder; /// Adds a [Serializer]. It will be used to handle the type(s) it declares /// via its `types` property. void add(Serializer serializer); /// Merges a [Serializers], adding all of its [Serializer] instances and /// builder factories. Does _not_ add plugins. void merge(Serializers serializers); /// Adds an iterable of [Serializer]. void addAll(Iterable<Serializer> serializers); /// Merges an iterable of [Serializers]. void mergeAll(Iterable<Serializers> serializersIterable); /// Adds a builder factory. /// /// Builder factories are needed when deserializing to types that use /// generics. For example, to deserialize a `BuiltList<Foo>`, `built_value` /// needs a builder factory for `BuiltList<Foo>`. /// /// `built_value` tries to generate code that will install all the builder /// factories you need, but this support is incomplete. So you may need to /// add your own. For example: /// /// ```dart /// serializers = (serializers.toBuilder() /// ..addBuilderFactory( /// const FullType(BuiltList, [FullType(Foo)]), /// () => ListBuilder<Foo>(), /// )) /// .build(); /// ``` void addBuilderFactory(FullType specifiedType, Function function); /// Installs a [SerializerPlugin] that applies to all serialization and /// deserialization. void addPlugin(SerializerPlugin plugin); Serializers build(); } /// A [Type] with, optionally, [FullType] generic type parameters. /// /// May also be [unspecified], indicating that no type information is /// available. class FullType { /// An unspecified type. static const FullType unspecified = FullType(null); /// The [Object] type. static const FullType object = FullType(Object); /// The root of the type. final Type root; /// Type parameters of the type. final List<FullType> parameters; const FullType(this.root, [this.parameters = const []]); bool get isUnspecified => identical(root, null); @override bool operator ==(dynamic other) { if (identical(other, this)) return true; if (other is! FullType) return false; if (root != other.root) return false; if (parameters.length != other.parameters.length) return false; for (var i = 0; i != parameters.length; ++i) { if (parameters[i] != other.parameters[i]) return false; } return true; } @override int get hashCode { return hash2(root, hashObjects(parameters)); } @override String toString() => isUnspecified ? 'unspecified' : parameters.isEmpty ? _getRawName(root) : '${_getRawName(root)}<${parameters.join(", ")}>'; static String _getRawName(Type type) { var name = type.toString(); var genericsStart = name.indexOf('<'); return genericsStart == -1 ? name : name.substring(0, genericsStart); } } /// Serializes a single type. /// /// You should not usually need to implement this interface. Implementations /// are provided for collections and primitives in `built_json`. Classes using /// `built_value` and enums using `EnumClass` can have implementations /// generated using `built_json_generator`. /// /// Implementations must extend either [PrimitiveSerializer] or /// [StructuredSerializer]. abstract class Serializer<T> { /// The [Type]s that can be serialized. /// /// They must all be equal to T or a subclass of T. Subclasses are used when /// T is an abstract class, which is the case with built_value generated /// serializers. Iterable<Type> get types; /// The wire name of the serializable type. For most classes, the class name. /// For primitives and collections a lower-case name is defined as part of /// the `built_json` wire format. String get wireName; } /// A [Serializer] that serializes to and from primitive JSON values. abstract class PrimitiveSerializer<T> implements Serializer<T> { /// Serializes [object]. /// /// Use [serializers] as needed for nested serialization. Information about /// the type being serialized is provided in [specifiedType]. /// /// Returns a value that can be represented as a JSON primitive: a boolean, /// an integer, a double, or a String. /// /// TODO(davidmorgan): document the wire format. Object serialize(Serializers serializers, T object, {FullType specifiedType = FullType.unspecified}); /// Deserializes [serialized]. /// /// [serialized] is a boolean, an integer, a double or a String. /// /// Use [serializers] as needed for nested deserialization. Information about /// the type being deserialized is provided in [specifiedType]. T deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}); } /// A [Serializer] that serializes to and from an [Iterable] of primitive JSON /// values. abstract class StructuredSerializer<T> implements Serializer<T> { /// Serializes [object]. /// /// Use [serializers] as needed for nested serialization. Information about /// the type being serialized is provided in [specifiedType]. /// /// Returns an [Iterable] of values that can be represented as structured /// JSON: booleans, integers, doubles, Strings and [Iterable]s. /// /// TODO(davidmorgan): document the wire format. Iterable serialize(Serializers serializers, T object, {FullType specifiedType = FullType.unspecified}); /// Deserializes [serialized]. /// /// [serialized] is an [Iterable] that may contain booleans, integers, /// doubles, Strings and/or [Iterable]s. /// /// Use [serializers] as needed for nested deserialization. Information about /// the type being deserialized is provided in [specifiedType]. T deserialize(Serializers serializers, Iterable serialized, {FullType specifiedType = FullType.unspecified}); } /// [Error] conveying why deserialization failed. class DeserializationError extends Error { final String json; final FullType type; final Error error; factory DeserializationError(Object json, FullType type, Error error) { var limitedJson = json.toString(); if (limitedJson.length > 80) { limitedJson = limitedJson.replaceRange(77, limitedJson.length, '...'); } return DeserializationError._(limitedJson, type, error); } DeserializationError._(this.json, this.type, this.error); @override String toString() => "Deserializing '$json' to '$type' failed due to: $error"; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/json_object.dart
// Copyright (c) 2017, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:collection/collection.dart'; /// A JSON value. /// /// This class is suitable for use in built_value fields. When serialized it /// maps directly onto JSON values. /// /// Deep operator== and hashCode are provided, meaning the contents of a /// List or Map is used for equality and hashing. /// /// List and Map classes are wrapped in [UnmodifiableListView] and /// [UnmodifiableMapView] so they won't be modifiable via this object. You /// must ensure that no updates are made via the original reference, as a /// copy is not made. /// /// Note: this is an experimental feature. API may change without a major /// version increase. abstract class JsonObject { /// The value, which may be a bool, a List, a Map, a num or a String. Object get value; /// Whether the value is a [bool]. bool get isBool => false; /// The value as a [bool], or throw if not. bool get asBool => throw StateError('Not a bool.'); /// Whether the value is a [List]. bool get isList => false; /// The value as a [List], or throw if not. List get asList => throw StateError('Not a List.'); /// Whether the value is a [Map]. bool get isMap => false; /// The value as a [Map], or throw if not. Map get asMap => throw StateError('Not a Map.'); /// Whether the value is a [num]. bool get isNum => false; /// The value as a [num], or throw if not. num get asNum => throw StateError('Not a num.'); /// Whether the value is a [String]. bool get isString => false; /// The value as a [String], or throw if not. String get asString => throw StateError('Not a String.'); /// Instantiates with [value], which must be a bool, a List, a Map, a num /// or a String. Otherwise, an [ArgumentError] is thrown. factory JsonObject(Object value) { if (value is num) { return NumJsonObject(value); } else if (value is String) { return StringJsonObject(value); } else if (value is bool) { return BoolJsonObject(value); } else if (value is List<Object>) { return ListJsonObject(value); } else if (value is Map<String, Object>) { return MapJsonObject(value); } else { throw ArgumentError.value(value, 'value', 'Must be bool, List<Object>, Map<String, Object>, num or String'); } } JsonObject._(); @override String toString() { return value.toString(); } } /// A [JsonObject] holding a bool. class BoolJsonObject extends JsonObject { @override final bool value; BoolJsonObject(this.value) : super._(); @override bool get isBool => true; @override bool get asBool => value; @override bool operator ==(dynamic other) { if (identical(other, this)) return true; if (other is! BoolJsonObject) return false; return value == other.value; } @override int get hashCode => value.hashCode; } /// A [JsonObject] holding a List. class ListJsonObject extends JsonObject { @override final List<Object> value; ListJsonObject(List<Object> value) : value = UnmodifiableListView<Object>(value), super._(); @override bool get isList => true; @override List<Object> get asList => value; @override bool operator ==(dynamic other) { if (identical(other, this)) return true; if (other is! ListJsonObject) return false; return const DeepCollectionEquality().equals(value, other.value); } @override int get hashCode => const DeepCollectionEquality().hash(value); } /// A [JsonObject] holding a Map. class MapJsonObject extends JsonObject { @override final Map<String, Object> value; MapJsonObject(Map<String, Object> value) : value = UnmodifiableMapView(value), super._(); @override bool get isMap => true; @override Map<String, Object> get asMap => value; @override bool operator ==(dynamic other) { if (identical(other, this)) return true; if (other is! MapJsonObject) return false; return const DeepCollectionEquality().equals(value, other.value); } @override int get hashCode => const DeepCollectionEquality().hash(value); } /// A [JsonObject] holding a num. class NumJsonObject extends JsonObject { @override final num value; NumJsonObject(this.value) : super._(); @override bool get isNum => true; @override num get asNum => value; @override bool operator ==(dynamic other) { if (identical(other, this)) return true; if (other is! NumJsonObject) return false; return value == other.value; } @override int get hashCode => value.hashCode; } /// A [JsonObject] holding a String. class StringJsonObject extends JsonObject { @override final String value; StringJsonObject(this.value) : super._(); @override bool get isString => true; @override String get asString => value; @override bool operator ==(dynamic other) { if (identical(other, this)) return true; if (other is! StringJsonObject) return false; return value == other.value; } @override int get hashCode => value.hashCode; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/standard_json_plugin.dart
import 'package:built_collection/built_collection.dart'; import 'package:built_value/json_object.dart'; import 'package:built_value/serializer.dart'; import 'dart:convert' show json; /// Switches to "standard" JSON format. /// /// The default serialization format is more powerful, with better performance /// and support for more collection types. But, you may need to interact with /// other systems that use simple map-based JSON. If so, use /// [SerializersBuilder.addPlugin] to install this plugin. /// /// When using this plugin you may wish to also install /// `Iso8601DateTimeSerializer` which switches serialization of `DateTime` /// from microseconds since epoch to ISO 8601 format. class StandardJsonPlugin implements SerializerPlugin { static final BuiltSet<Type> _unsupportedTypes = BuiltSet<Type>([BuiltListMultimap, BuiltSetMultimap]); /// The field used to specify the value type if needed. Defaults to `$`. final String discriminator; // The key used when there is just a single value, for example if serializing // an `int`. final String valueKey; StandardJsonPlugin({this.discriminator = r'$', this.valueKey = ''}); @override Object beforeSerialize(Object object, FullType specifiedType) { if (_unsupportedTypes.contains(specifiedType.root)) { throw ArgumentError( 'Standard JSON cannot serialize type ${specifiedType.root}.'); } return object; } @override Object afterSerialize(Object object, FullType specifiedType) { if (object is List && specifiedType.root != BuiltList && specifiedType.root != BuiltSet && specifiedType.root != JsonObject) { if (specifiedType.isUnspecified) { return _toMapWithDiscriminator(object); } else { return _toMap(object, _needsEncodedKeys(specifiedType)); } } else { return object; } } @override Object beforeDeserialize(Object object, FullType specifiedType) { if (object is Map && specifiedType.root != JsonObject) { if (specifiedType.isUnspecified) { return _toListUsingDiscriminator(object); } else { return _toList(object, _needsEncodedKeys(specifiedType)); } } else { return object; } } @override Object afterDeserialize(Object object, FullType specifiedType) { return object; } /// Returns whether a type has keys that aren't supported by JSON maps; this /// only applies to `BuiltMap` with non-String keys. bool _needsEncodedKeys(FullType specifiedType) => specifiedType.root == BuiltMap && specifiedType.parameters[0].root != String; /// Converts serialization output, a `List`, to a `Map`, when the serialized /// type is known statically. Map _toMap(List list, bool needsEncodedKeys) { var result = <String, Object>{}; for (var i = 0; i != list.length ~/ 2; ++i) { final key = list[i * 2]; final value = list[i * 2 + 1]; result[needsEncodedKeys ? _encodeKey(key) : key as String] = value; } return result; } /// Converts serialization output, a `List`, to a `Map`, when the serialized /// type is not known statically. The type will be specified in the /// [discriminator] field. Map _toMapWithDiscriminator(List list) { var type = list[0]; if (type == 'list') { // Embed the list in the map. return <String, Object>{discriminator: type, valueKey: list.sublist(1)}; } // Length is at least two because we have one entry for type and one for // the value. if (list.length == 2) { // Just a type and a primitive value. Encode the value in the map. return <String, Object>{discriminator: type, valueKey: list[1]}; } // If a map has non-String keys then they need encoding to strings before // it can be converted to JSON. Because we don't know the type, we also // won't know the type on deserialization, and signal this by changing the // type name on the wire to `encoded_map`. var needToEncodeKeys = false; if (type == 'map') { for (var i = 0; i != (list.length - 1) ~/ 2; ++i) { if (list[i * 2 + 1] is! String) { needToEncodeKeys = true; type = 'encoded_map'; break; } } } var result = <String, Object>{discriminator: type}; for (var i = 0; i != (list.length - 1) ~/ 2; ++i) { final key = needToEncodeKeys ? _encodeKey(list[i * 2 + 1]) : list[i * 2 + 1] as String; final value = list[i * 2 + 2]; result[key] = value; } return result; } /// JSON-encodes an `Object` key so it can be stored as a `String`. Needed /// because JSON maps are only allowed strings as keys. String _encodeKey(Object key) { return json.encode(key); } /// Converts [StandardJsonPlugin] serialization output, a `Map`, to a `List`, /// when the serialized type is known statically. List _toList(Map map, bool hasEncodedKeys) { var result = List(map.length * 2); var i = 0; map.forEach((key, value) { // Drop null values, they are represented by missing keys. if (value == null) return; result[i] = hasEncodedKeys ? _decodeKey(key as String) : key; result[i + 1] = value; i += 2; }); return result; } /// Converts [StandardJsonPlugin] serialization output, a `Map`, to a `List`, /// when the serialized type is not known statically. The type is retrieved /// from the [discriminator] field. List _toListUsingDiscriminator(Map map) { var type = map[discriminator]; if (type == null) { throw ArgumentError('Unknown type on deserialization. ' 'Need either specifiedType or discriminator field.'); } if (type == 'list') { return [type, ...(map[valueKey] as Iterable)]; } if (map.containsKey(valueKey)) { // Just a type and a primitive value. Retrieve the value in the map. final result = List(2); result[0] = type; result[1] = map[valueKey]; return result; } // A type name of `encoded_map` indicates that the map has non-String keys // that have been serialized and JSON-encoded; decode the keys when // converting back to a `List`. var needToDecodeKeys = type == 'encoded_map'; if (needToDecodeKeys) { type = 'map'; } var result = List(map.length * 2 - 1); result[0] = type; var i = 1; map.forEach((key, value) { if (key == discriminator) return; // Drop null values, they are represented by missing keys. if (value == null) return; result[i] = needToDecodeKeys ? _decodeKey(key as String) : key; result[i + 1] = value; i += 2; }); return result; } /// JSON-decodes a `String` encoded using [_encodeKey]. Object _decodeKey(String key) { return json.decode(key); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/built_value.dart
// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /// Implement this for a Built Value. /// /// Then use built_value_generator.dart code generation functionality to /// provide the rest of the implementation. /// /// See https://github.com/google/built_value.dart/tree/master/example abstract class Built<V extends Built<V, B>, B extends Builder<V, B>> { /// Rebuilds the instance. /// /// The result is the same as this instance but with [updates] applied. /// [updates] is a function that takes a builder [B]. /// /// The implementation of this method will be generated for you by the /// built_value generator. V rebuild(Function(B) updates); /// Converts the instance to a builder [B]. /// /// The implementation of this method will be generated for you by the /// built_value generator. B toBuilder(); } /// Every [Built] class has a corresponding [Builder] class. /// /// Usually you don't need to create one by hand; it will be generated /// for you. /// /// See <https://github.com/google/built_value.dart/tree/master/example> abstract class Builder<V extends Built<V, B>, B extends Builder<V, B>> { /// Replaces the value in the builder with a new one. /// /// The implementation of this method will be generated for you by the /// built_value generator. void replace(V value); /// Applies updates. /// /// [updates] is a function that takes a builder [B]. void update(Function(B) updates); /// Builds. /// /// The implementation of this method will be generated for you by the /// built_value generator. V build(); } /// Optionally, annotate a Built Value with this to specify settings. This is /// only needed for advanced use. class BuiltValue { /// Whether the Built Value is instantiable. Defaults to `true`. /// /// A non-instantiable Built Value has no constructor or factory. No /// implementation will be generated. But, an abstract builder will be /// generated, or you may write one yourself. /// /// Other Built Values may choose to `implement` a non-instantiable Built /// Value, pulling in fields and methods from it. Their generated builders /// will automatically `implement` the corresponding builder, so you can /// access and modify the common inherited fields without knowing the /// concrete type. final bool instantiable; /// Whether to use nested builders. Defaults to `true`. /// /// If the builder class is fully generated, controls whether nested builders /// are used. This means builder fields are themselves builders if there is a /// builder available for each field type. /// /// If you write the builder class by hand, this has no effect; simply /// declare each field as the type you want, either the built type or the /// builder. final bool nestedBuilders; /// Whether to auto create nested builders. Defaults to `true`. /// /// When this is enabled, accessing a nested builder via a getter causes it /// to be instantiated if it's `null`. In most cases this is convenient, but /// if you are using builders for data processing then you might need to /// check for `null`. If so you should set this to `false`. final bool autoCreateNestedBuilders; /// Whether builders should implement `operator==` and `hashCode`, making /// them comparable. /// /// May only be used with `nestedBuilders: false` and if the builder class /// is fully generated. final bool comparableBuilders; /// Whether to generate an `onSet` field in the builder. /// /// Defaults to `false`. /// /// If generated the `onSet` field will have type `void Function()`, and will /// be called after any setter is called. Assign your own function to /// `onSet` to respond to changes to the builder. final bool generateBuilderOnSetField; /// The wire name when the class is serialized. Defaults to `null` which /// indicates that the name is to be taken from the literal class name. final String wireName; /// The default for [BuiltValueField.compare]. Set to `false` if you want to /// ignore most fields when comparing, then mark the ones you do want to /// compare on with `@BuiltValueField(compare: true)`. final bool defaultCompare; /// The default for [BuiltValueField.serialize]. Set to `false` if you want /// to ignore most fields when serializing, then mark the ones you do want /// to serialize with `@BuiltValueField(serialize: true)`. final bool defaultSerialize; const BuiltValue( {this.instantiable = true, this.nestedBuilders = true, this.autoCreateNestedBuilders = true, this.comparableBuilders = false, this.generateBuilderOnSetField = false, this.wireName, this.defaultCompare = true, this.defaultSerialize = true}); } /// Nullable annotation for Built Value fields. /// /// Fields marked with this annotation are allowed to be null. const String nullable = 'nullable'; /// Optionally, annotate a Built Value field with this to specify settings. /// This is only needed for advanced use. class BuiltValueField { /// Whether the field is compared and hashed. Defaults to `null` which means /// [BuiltValue.defaultCompare] is used. /// /// Set to `false` to ignore the field when calculating `hashCode` and when /// comparing with `operator==`. final bool compare; /// Whether the field is serialized. Defaults to `null` which means /// [BuiltValue.defaultSerialize] is used. /// /// If a field is not serialized, it must either be `@nullable` or specify a /// default for deserialization to succeed. final bool serialize; /// The wire name when the field is serialized. Defaults to `null` which /// indicates the name is to be taken from the literal field name. final String wireName; const BuiltValueField({this.compare, this.serialize, this.wireName}); } /// Optionally, annotate a Built Value `Serializer` getters with this to /// specify settings. This is only needed for advanced use. class BuiltValueSerializer { /// Set this to `true` to stop Built Value from generating a serializer for /// you. The getter may then return any compatible `Serializer`. Defaults /// to `false`. final bool custom; /// Whether the generated serializer should output `null`s. /// /// By default this is `false` and nulls are omitted from the output. final bool serializeNulls; const BuiltValueSerializer( {this.custom = false, this.serializeNulls = false}); } /// Memoized annotation for Built Value getters. /// /// Getters marked with this annotation are memoized: the result is calculated /// once on first access and stored in the instance. const String memoized = 'memoized'; /// Optionally, annotate an `EnumClass` with this to specify settings. This /// is only needed for advanced use. class BuiltValueEnum { /// The wire name when the enum is serialized. Defaults to `null` which /// indicates that the name is to be taken from the literal class name. final String wireName; const BuiltValueEnum({this.wireName}); } /// Optionally, annotate an `EnumClass` constant with this to specify settings. /// This is only needed for advanced use. class BuiltValueEnumConst { /// The wire name when the constant is serialized. Defaults to `null` which /// indicates the name is to be taken from the literal field name. /// /// Or, set [wireNumber] to serialize to an `int`. Only one of the two may be /// used. final String wireName; /// The wire name when the constant is serialized. Defaults to `null` which /// indicates the name is to be taken from the literal field name. /// /// Or, set [wireNumber] to serialize to a `String`. Only one of the two may /// be used. final int wireNumber; /// Marks a value that is used as a fallback when an unrecognized value /// is encountered. /// /// Defaults to `false`. At most one fallback is allowed per `EnumClass`. /// /// Applies to the `valueOf` method and to deserialization; both will use /// the fallback, if available, rather than throwing an exception. final bool fallback; const BuiltValueEnumConst( {this.wireName, this.wireNumber, this.fallback = false}); } /// Enum Class base class. /// /// Extend this class then use the built_value.dart code generation /// functionality to provide the rest of the implementation. /// /// See https://github.com/google/built_value.dart/tree/master/example class EnumClass { final String name; const EnumClass(this.name); @override String toString() => name; } /// For use by generated code in calculating hash codes. Do not use directly. int $jc(int hash, int value) { // Jenkins hash "combine". hash = 0x1fffffff & (hash + value); hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); return hash ^ (hash >> 6); } /// For use by generated code in calculating hash codes. Do not use directly. int $jf(int hash) { // Jenkins hash "finish". hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); hash = hash ^ (hash >> 11); return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); } /// Function that returns a [BuiltValueToStringHelper]. typedef BuiltValueToStringHelperProvider = BuiltValueToStringHelper Function( String className); /// Function used by generated code to get a [BuiltValueToStringHelper]. /// Set this to change built_value class toString() output. Built-in examples /// are [IndentingBuiltValueToStringHelper], which is the default, and /// [FlatBuiltValueToStringHelper]. BuiltValueToStringHelperProvider newBuiltValueToStringHelper = (String className) => IndentingBuiltValueToStringHelper(className); /// Interface for built_value toString() output helpers. /// /// Note: this is an experimental feature. API may change without a major /// version increase. abstract class BuiltValueToStringHelper { /// Add a field and its value. void add(String field, Object value); /// Returns to completed toString(). The helper may not be used after this /// method is called. @override String toString(); } /// A [BuiltValueToStringHelper] that produces multi-line indented output. class IndentingBuiltValueToStringHelper implements BuiltValueToStringHelper { StringBuffer _result = StringBuffer(); IndentingBuiltValueToStringHelper(String className) { _result..write(className)..write(' {\n'); _indentingBuiltValueToStringHelperIndent += 2; } @override void add(String field, Object value) { if (value != null) { _result ..write(' ' * _indentingBuiltValueToStringHelperIndent) ..write(field) ..write('=') ..write(value) ..write(',\n'); } } @override String toString() { _indentingBuiltValueToStringHelperIndent -= 2; _result..write(' ' * _indentingBuiltValueToStringHelperIndent)..write('}'); var stringResult = _result.toString(); _result = null; return stringResult; } } int _indentingBuiltValueToStringHelperIndent = 0; /// A [BuiltValueToStringHelper] that produces single line output. class FlatBuiltValueToStringHelper implements BuiltValueToStringHelper { StringBuffer _result = StringBuffer(); bool _previousField = false; FlatBuiltValueToStringHelper(String className) { _result..write(className)..write(' {'); } @override void add(String field, Object value) { if (value != null) { if (_previousField) _result.write(','); _result..write(field)..write('=')..write(value); _previousField = true; } } @override String toString() { _result..write('}'); var stringResult = _result.toString(); _result = null; return stringResult; } } /// [Error] indicating that a built_value class constructor was called with /// a `null` value for a field not marked `@nullable`. class BuiltValueNullFieldError extends Error { final String type; final String field; BuiltValueNullFieldError(this.type, this.field); @override String toString() => 'Tried to construct class "$type" with null field "$field". ' 'This is forbidden; to allow it, mark "$field" with @nullable.'; } /// [Error] indicating that a built_value class constructor was called with /// a missing or `dynamic` type parameter. class BuiltValueMissingGenericsError extends Error { final String type; final String parameter; BuiltValueMissingGenericsError(this.type, this.parameter); @override String toString() => 'Tried to construct class "$type" with missing or dynamic ' 'type argument "$parameter". All type arguments must be specified.'; } /// [Error] indicating that a built_value `build` method failed because a /// nested field builder failed. class BuiltValueNestedFieldError extends Error { final String type; final String field; final String error; BuiltValueNestedFieldError(this.type, this.field, this.error); @override String toString() => 'Tried to build class "$type" but nested builder for field "$field" ' 'threw: $error'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/built_list_serializer.dart
// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; class BuiltListSerializer implements StructuredSerializer<BuiltList> { final bool structured = true; @override final Iterable<Type> types = BuiltList<Type>([BuiltList, BuiltList<Object>().runtimeType]); @override final String wireName = 'list'; @override Iterable serialize(Serializers serializers, BuiltList builtList, {FullType specifiedType = FullType.unspecified}) { var isUnderspecified = specifiedType.isUnspecified || specifiedType.parameters.isEmpty; if (!isUnderspecified) serializers.expectBuilder(specifiedType); var elementType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[0]; return builtList .map((item) => serializers.serialize(item, specifiedType: elementType)); } @override BuiltList deserialize(Serializers serializers, Iterable serialized, {FullType specifiedType = FullType.unspecified}) { var isUnderspecified = specifiedType.isUnspecified || specifiedType.parameters.isEmpty; var elementType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[0]; var result = isUnderspecified ? ListBuilder<Object>() : serializers.newBuilder(specifiedType) as ListBuilder; result.replace(serialized.map( (item) => serializers.deserialize(item, specifiedType: elementType))); return result.build(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/built_set_multimap_serializer.dart
// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; class BuiltSetMultimapSerializer implements StructuredSerializer<BuiltSetMultimap> { final bool structured = true; @override final Iterable<Type> types = BuiltSet<Type>([BuiltSetMultimap]); @override final String wireName = 'setMultimap'; @override Iterable serialize(Serializers serializers, BuiltSetMultimap builtSetMultimap, {FullType specifiedType = FullType.unspecified}) { var isUnderspecified = specifiedType.isUnspecified || specifiedType.parameters.isEmpty; if (!isUnderspecified) serializers.expectBuilder(specifiedType); var keyType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[0]; var valueType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[1]; var result = <Object>[]; for (var key in builtSetMultimap.keys) { result.add(serializers.serialize(key, specifiedType: keyType)); result.add(builtSetMultimap[key] .map( (value) => serializers.serialize(value, specifiedType: valueType)) .toList()); } return result; } @override BuiltSetMultimap deserialize(Serializers serializers, Iterable serialized, {FullType specifiedType = FullType.unspecified}) { var isUnderspecified = specifiedType.isUnspecified || specifiedType.parameters.isEmpty; var keyType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[0]; var valueType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[1]; var result = isUnderspecified ? SetMultimapBuilder<Object, Object>() : serializers.newBuilder(specifiedType) as SetMultimapBuilder; if (serialized.length % 2 == 1) { throw ArgumentError('odd length'); } for (var i = 0; i != serialized.length; i += 2) { final key = serializers.deserialize(serialized.elementAt(i), specifiedType: keyType); final values = serialized.elementAt(i + 1).map( (value) => serializers.deserialize(value, specifiedType: valueType)); for (var value in values) { result.add(key, value); } } return result.build(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/built_map_serializer.dart
// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; class BuiltMapSerializer implements StructuredSerializer<BuiltMap> { final bool structured = true; @override final Iterable<Type> types = BuiltList<Type>([BuiltMap, BuiltMap<Object, Object>().runtimeType]); @override final String wireName = 'map'; @override Iterable serialize(Serializers serializers, BuiltMap builtMap, {FullType specifiedType = FullType.unspecified}) { var isUnderspecified = specifiedType.isUnspecified || specifiedType.parameters.isEmpty; if (!isUnderspecified) serializers.expectBuilder(specifiedType); var keyType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[0]; var valueType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[1]; var result = <Object>[]; for (var key in builtMap.keys) { result.add(serializers.serialize(key, specifiedType: keyType)); final value = builtMap[key]; result.add(serializers.serialize(value, specifiedType: valueType)); } return result; } @override BuiltMap deserialize(Serializers serializers, Iterable serialized, {FullType specifiedType = FullType.unspecified}) { var isUnderspecified = specifiedType.isUnspecified || specifiedType.parameters.isEmpty; var keyType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[0]; var valueType = specifiedType.parameters.isEmpty ? FullType.unspecified : specifiedType.parameters[1]; var result = isUnderspecified ? MapBuilder<Object, Object>() : serializers.newBuilder(specifiedType) as MapBuilder; if (serialized.length % 2 == 1) { throw ArgumentError('odd length'); } for (var i = 0; i != serialized.length; i += 2) { final key = serializers.deserialize(serialized.elementAt(i), specifiedType: keyType); final value = serializers.deserialize(serialized.elementAt(i + 1), specifiedType: valueType); result[key] = value; } return result.build(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/date_time_serializer.dart
// Copyright (c) 2017, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; /// Serializer for [DateTime]. /// /// An exception will be thrown on attempt to serialize local DateTime /// instances; you must use UTC. class DateTimeSerializer implements PrimitiveSerializer<DateTime> { final bool structured = false; @override final Iterable<Type> types = BuiltList<Type>([DateTime]); @override final String wireName = 'DateTime'; @override Object serialize(Serializers serializers, DateTime dateTime, {FullType specifiedType = FullType.unspecified}) { if (!dateTime.isUtc) { throw ArgumentError.value( dateTime, 'dateTime', 'Must be in utc for serialization.'); } return dateTime.microsecondsSinceEpoch; } @override DateTime deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) { var microsecondsSinceEpoch = serialized as int; return DateTime.fromMicrosecondsSinceEpoch(microsecondsSinceEpoch, isUtc: true); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/uri_serializer.dart
// Copyright (c) 2017, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; class UriSerializer implements PrimitiveSerializer<Uri> { final bool structured = false; @override final Iterable<Type> types = BuiltList<Type>([ Uri, // `Uri` is just an interface. Need to record actual implementation types // here. This is a `_SimpleUri`: Uri.parse('http://example.com').runtimeType, // And this is a `_Uri`: Uri.parse('http://example.com:').runtimeType, ]); @override final String wireName = 'Uri'; @override Object serialize(Serializers serializers, Uri uri, {FullType specifiedType = FullType.unspecified}) { return uri.toString(); } @override Uri deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) { return Uri.parse(serialized as String); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/double_serializer.dart
// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; class DoubleSerializer implements PrimitiveSerializer<double> { // Constant names match those in [double]. // ignore_for_file: non_constant_identifier_names static final String nan = 'NaN'; static final String infinity = 'INF'; static final String negativeInfinity = '-INF'; final bool structured = false; @override final Iterable<Type> types = BuiltList<Type>([double]); @override final String wireName = 'double'; @override Object serialize(Serializers serializers, double aDouble, {FullType specifiedType = FullType.unspecified}) { if (aDouble.isNaN) { return nan; } else if (aDouble.isInfinite) { return aDouble.isNegative ? negativeInfinity : infinity; } else { return aDouble; } } @override double deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) { if (serialized == nan) { return double.nan; } else if (serialized == negativeInfinity) { return double.negativeInfinity; } else if (serialized == infinity) { return double.infinity; } else { return (serialized as num).toDouble(); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/big_int_serializer.dart
// Copyright (c) 2018, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; class BigIntSerializer implements PrimitiveSerializer<BigInt> { final bool structured = false; // [BigInt] has a private implementation type; register it via [BigInt.zero]. @override final Iterable<Type> types = BuiltList<Type>([BigInt, BigInt.zero.runtimeType]); @override final String wireName = 'BigInt'; @override Object serialize(Serializers serializers, BigInt bigInt, {FullType specifiedType = FullType.unspecified}) { return bigInt.toString(); } @override BigInt deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) { return BigInt.parse(serialized as String); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/duration_serializer.dart
// Copyright (c) 2018, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; /// Serializer for [Duration]. /// /// [Duration] is implemented as an `int` number of microseconds, so just /// store that `int`. class DurationSerializer implements PrimitiveSerializer<Duration> { final bool structured = false; @override final Iterable<Type> types = BuiltList<Type>([Duration]); @override final String wireName = 'Duration'; @override Object serialize(Serializers serializers, Duration duration, {FullType specifiedType = FullType.unspecified}) { return duration.inMicroseconds; } @override Duration deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) { return Duration(microseconds: serialized as int); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/json_object_serializer.dart
// Copyright (c) 2017, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/json_object.dart'; import 'package:built_value/serializer.dart'; class JsonObjectSerializer implements PrimitiveSerializer<JsonObject> { final bool structured = false; @override final Iterable<Type> types = BuiltList<Type>([ JsonObject, BoolJsonObject, ListJsonObject, MapJsonObject, NumJsonObject, StringJsonObject, ]); @override final String wireName = 'JsonObject'; @override Object serialize(Serializers serializers, JsonObject jsonObject, {FullType specifiedType = FullType.unspecified}) { return jsonObject.value; } @override JsonObject deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) { return JsonObject(serialized); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/built_value/src/num_serializer.dart
// Copyright (c) 2017, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; import 'package:built_value/src/double_serializer.dart'; class NumSerializer implements PrimitiveSerializer<num> { final bool structured = false; @override final Iterable<Type> types = BuiltList<Type>([num]); @override final String wireName = 'num'; @override Object serialize(Serializers serializers, num number, {FullType specifiedType = FullType.unspecified}) { if (number.isNaN) { return DoubleSerializer.nan; } else if (number.isInfinite) { return number.isNegative ? DoubleSerializer.negativeInfinity : DoubleSerializer.infinity; } else { return number; } } @override num deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) { if (serialized == DoubleSerializer.nan) { return double.nan; } else if (serialized == DoubleSerializer.negativeInfinity) { return double.negativeInfinity; } else if (serialized == DoubleSerializer.infinity) { return double.infinity; } else { return serialized as num; } } }
0