repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/memes/lib/components/scrollList
mirrored_repositories/memes/lib/components/scrollList/controls/onscreen_controls.dart
import 'package:flutter/material.dart'; import 'package:memes/components/scrollList/controls/video_control_action.dart'; import 'package:mixpanel_analytics/mixpanel_analytics.dart'; import 'package:memes/models/meme.dart'; import 'package:flutter_share/flutter_share.dart'; Widget onScreenControls(MixpanelAnalytics _mixPanel, Meme currentMem) { like() async { await _mixPanel.track(event: 'like_mem', properties: { 'mem_id': currentMem.id, 'feed': 'scroll', 'method': 'button', }); } report() async { await _mixPanel.track(event: 'report_mem', properties: { 'mem_id': currentMem.id, 'feed': 'scroll', }); } Future<void> share() async { await _mixPanel .track(event: 'share_mem', properties: {'mem_id': currentMem.id}); await FlutterShare.share( title: 'Top Kek memes', text: 'Top Kek memes', linkUrl: currentMem.fileUrl, chooserTitle: 'Memes app'); } return Container( child: Row( children: <Widget>[ // Expanded(flex: 5, child: videoDesc()), Expanded( flex: 1, child: Container( padding: EdgeInsets.only(bottom: 60, right: 0), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ videoControlAction( icon: Icons.favorite, label: 'like', onPress: like), videoControlAction( icon: Icons.report, label: "report", onPress: report), videoControlAction( icon: Icons.share, label: "Share", size: 27, onPress: share), ], ), ), ) ], ), ); }
0
mirrored_repositories/memes/lib/components/scrollList
mirrored_repositories/memes/lib/components/scrollList/controls/video_control_action.dart
import 'package:flutter/material.dart'; Widget videoControlAction( {IconData icon, String label, double size = 35, Function onPress}) { return Padding( padding: EdgeInsets.only(top: 10, bottom: 10), child: FloatingActionButton( backgroundColor: Colors.transparent, child: Column( children: <Widget>[ Icon( icon, color: Colors.white, size: size, ), ], ), onPressed: onPress, )); }
0
mirrored_repositories/memes/lib/components/scrollList
mirrored_repositories/memes/lib/components/scrollList/video_metadata/user_profile.dart
import 'package:flutter/material.dart'; Widget userProfile() { return Padding( padding: EdgeInsets.only(top: 10, bottom: 10), child: Column( children: <Widget>[ Stack( alignment: AlignmentDirectional.center, children: <Widget>[ Container( height: 50, width: 50, decoration: BoxDecoration( border: Border.all( color: Colors.white, width: 1.0, style: BorderStyle.solid), color: Colors.black, shape: BoxShape.circle), ), Container( margin: EdgeInsets.only(top: 50), height: 18, width: 18, child: Icon(Icons.add, size: 10, color: Colors.white), decoration: BoxDecoration( color: Color.fromRGBO(255, 42, 84, 1), shape: BoxShape.circle), ) ], ) ], ), ); }
0
mirrored_repositories/memes/lib/components
mirrored_repositories/memes/lib/components/face_recognition/smile_painter.dart
import 'dart:ui' as ui show Image; import 'dart:math' as Math; import 'package:firebase_ml_vision/firebase_ml_vision.dart'; import 'package:flutter/material.dart'; class FacePaint extends CustomPaint { final CustomPainter painter; FacePaint({this.painter}) : super(painter: painter); } class SmilePainter extends CustomPainter { final ui.Image image; final List<Face> faces; SmilePainter(this.image, this.faces); @override void paint(Canvas canvas, Size size) { if (image != null) { canvas.drawImage(image, Offset.zero, Paint()); } final paintRectStyle = Paint() ..color = Colors.red ..strokeWidth = 30.0 ..style = PaintingStyle.stroke; //Draw Body final paint = Paint()..color = Colors.yellow; for (var i = 0; i < faces.length; i++) { final radius = Math.min(faces[i].boundingBox.width, faces[i].boundingBox.height) / 2; final center = faces[i].boundingBox.center; final smilePaint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = radius / 8; canvas.drawRect(faces[i].boundingBox, paintRectStyle); canvas.drawCircle(center, radius, paint); canvas.drawArc( Rect.fromCircle( center: center.translate(0, radius / 8), radius: radius / 2), 0, Math.pi, false, smilePaint); //Draw the eyes canvas.drawCircle(Offset(center.dx - radius / 2, center.dy - radius / 2), radius / 8, Paint()); canvas.drawCircle(Offset(center.dx + radius / 2, center.dy - radius / 2), radius / 8, Paint()); } } @override bool shouldRepaint(SmilePainter oldDelegate) { return image != oldDelegate.image || faces != oldDelegate.faces; } } class SmilePainterLiveCamera extends CustomPainter { final Size imageSize; final List<Face> faces; SmilePainterLiveCamera(this.imageSize, this.faces); @override void paint(Canvas canvas, Size size) { // final paintRectStyle = Paint() // ..color = Colors.red // ..strokeWidth = 10.0 // ..style = PaintingStyle.stroke; final paint = Paint()..color = Colors.yellow; for (var i = 0; i < faces.length; i++) { //Scale rect to image size final rect = _scaleRect( rect: faces[i].boundingBox, imageSize: imageSize, widgetSize: size, ); //Radius for smile circle final radius = Math.min(rect.width, rect.height) / 2; //Center of face rect final Offset center = rect.center; final smilePaint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = radius / 8; //Draw rect border //canvas.drawRect(rect, paintRectStyle); //Draw body canvas.drawCircle(center, radius, paint); //Draw mouth canvas.drawArc( Rect.fromCircle( center: center.translate(0, radius / 8), radius: radius / 2), 0, Math.pi, false, smilePaint); //Draw the eyes canvas.drawCircle(Offset(center.dx - radius / 2, center.dy - radius / 2), radius / 8, Paint()); canvas.drawCircle(Offset(center.dx + radius / 2, center.dy - radius / 2), radius / 8, Paint()); } } @override bool shouldRepaint(SmilePainterLiveCamera oldDelegate) { return imageSize != oldDelegate.imageSize || faces != oldDelegate.faces; } } Rect _scaleRect({ @required Rect rect, @required Size imageSize, @required Size widgetSize, }) { final double scaleX = widgetSize.width / imageSize.width; final double scaleY = widgetSize.height / imageSize.height; return Rect.fromLTRB( rect.left.toDouble() * scaleX, rect.top.toDouble() * scaleY, rect.right.toDouble() * scaleX, rect.bottom.toDouble() * scaleY, ); }
0
mirrored_repositories/memes/lib/components
mirrored_repositories/memes/lib/components/face_recognition/face_detection_camera.dart
import 'package:memes/components/face_recognition/smile_painter.dart'; import 'package:flutter/material.dart'; import 'package:camera/camera.dart'; import 'package:firebase_ml_vision/firebase_ml_vision.dart'; import 'package:flutter/foundation.dart'; import 'utils.dart'; class FaceDetectionFromLiveCamera extends StatefulWidget { FaceDetectionFromLiveCamera({Key key}) : super(key: key); @override _FaceDetectionFromLiveCameraState createState() => _FaceDetectionFromLiveCameraState(); } class _FaceDetectionFromLiveCameraState extends State<FaceDetectionFromLiveCamera> { final FaceDetector faceDetector = FirebaseVision.instance.faceDetector(); List<Face> faces; CameraController _camera; bool _isDetecting = false; CameraLensDirection _direction = CameraLensDirection.back; @override void initState() { super.initState(); _initializeCamera(); } void _initializeCamera() async { CameraDescription description = await getCamera(_direction); print(description); ImageRotation rotation = rotationIntToImageRotation( description.sensorOrientation, ); print(rotation); _camera = CameraController( description, defaultTargetPlatform == TargetPlatform.iOS ? ResolutionPreset.low : ResolutionPreset.medium, ); await _camera.initialize(); print(_camera); _camera.startImageStream((CameraImage image) { if (_isDetecting) return; _isDetecting = true; detect(image, FirebaseVision.instance.faceDetector().processImage, rotation) .then( (dynamic result) { setState(() { faces = result; }); _isDetecting = false; }, ).catchError( (_) { _isDetecting = false; }, ); }); } Widget _buildResults() { const Text noResultsText = const Text('No results!'); if (faces == null || _camera == null || !_camera.value.isInitialized) { return noResultsText; } CustomPainter painter; final Size imageSize = Size( _camera.value.previewSize.height, _camera.value.previewSize.width, ); if (faces is! List<Face>) return noResultsText; painter = SmilePainterLiveCamera(imageSize, faces); return CustomPaint( painter: painter, ); } Widget _buildImage() { return Container( constraints: const BoxConstraints.expand(), child: _camera == null ? const Center( child: Text( 'Initializing Camera...', style: TextStyle( color: Colors.green, fontSize: 30.0, ), ), ) : Stack( fit: StackFit.expand, children: <Widget>[ CameraPreview(_camera), _buildResults(), Positioned( bottom: 0.0, left: 0.0, right: 0.0, child: Container( color: Colors.white, height: 50.0, child: ListView( children: faces .map((face) => Text(face.boundingBox.center.toString())) .toList(), ), ), ), ], ), ); } void _toggleCameraDirection() async { if (_direction == CameraLensDirection.back) { _direction = CameraLensDirection.front; } else { _direction = CameraLensDirection.back; } await _camera.stopImageStream(); await _camera.dispose(); setState(() { _camera = null; }); _initializeCamera(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Face Detection with Smile"), ), body: _buildImage(), floatingActionButton: FloatingActionButton( onPressed: _toggleCameraDirection, child: _direction == CameraLensDirection.back ? const Icon(Icons.camera_front) : const Icon(Icons.camera_rear), ), ); } }
0
mirrored_repositories/memes/lib/components
mirrored_repositories/memes/lib/components/face_recognition/utils.dart
import 'dart:async'; import 'dart:typed_data'; import 'dart:ui'; import 'package:camera/camera.dart'; import 'package:firebase_ml_vision/firebase_ml_vision.dart'; import 'package:flutter/foundation.dart'; typedef HandleDetection = Future<List<Face>> Function(FirebaseVisionImage image); Future<CameraDescription> getCamera(CameraLensDirection dir) async { return await availableCameras().then( (List<CameraDescription> cameras) => cameras.firstWhere( (CameraDescription camera) => camera.lensDirection == dir, ), ); } Uint8List concatenatePlanes(List<Plane> planes) { final WriteBuffer allBytes = WriteBuffer(); planes.forEach((Plane plane) => allBytes.putUint8List(plane.bytes)); return allBytes.done().buffer.asUint8List(); } FirebaseVisionImageMetadata buildMetaData( CameraImage image, ImageRotation rotation, ) { return FirebaseVisionImageMetadata( rawFormat: image.format.raw, size: Size(image.width.toDouble(), image.height.toDouble()), rotation: rotation, planeData: image.planes.map( (Plane plane) { return FirebaseVisionImagePlaneMetadata( bytesPerRow: plane.bytesPerRow, height: plane.height, width: plane.width, ); }, ).toList(), ); } Future<List<Face>> detect( CameraImage image, HandleDetection handleDetection, ImageRotation rotation, ) async { return handleDetection( FirebaseVisionImage.fromBytes( concatenatePlanes(image.planes), buildMetaData(image, rotation), ), ); } ImageRotation rotationIntToImageRotation(int rotation) { switch (rotation) { case 0: return ImageRotation.rotation0; case 90: return ImageRotation.rotation90; case 180: return ImageRotation.rotation180; default: assert(rotation == 270); return ImageRotation.rotation270; } }
0
mirrored_repositories/memes/lib
mirrored_repositories/memes/lib/resources/dimen.dart
class Dimen { static const bottomNavigationTextSize = 8.5; static const createButtonBorder = 9.0; static const defaultTextSpacing = 5.0; static const textSpacing = 2.0; static const headerHeight = 50.0; static const five = 5; }
0
mirrored_repositories/memes/lib
mirrored_repositories/memes/lib/models/meme.dart
class Meme { final int id; final String name; final String fileUrl; Meme({this.id, this.name, this.fileUrl}); factory Meme.fromJson(Map<String, dynamic> json) { return Meme( id: json['id'], name: json['name'], fileUrl: json['file_url'] ); } }
0
mirrored_repositories/memes/lib
mirrored_repositories/memes/lib/api/memes_api.dart
import 'dart:async'; import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:memes/constants/enum.dart'; import 'package:memes/constants/api.dart'; import 'package:memes/models/meme.dart'; import 'package:memes/database/database_hepler.dart'; Future<List<Meme>> fetchMemes(page, perPage) async { var queryParameters = { 'page': page.toString(), 'per_page': perPage.toString(), }; var uri = Uri.http(BASE_URL, MEMES, queryParameters); final response = await http.get(uri); if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. return (json.decode(response.body)['memes'] as List).map((i) { return Meme.fromJson(i); }).toList(); } else { // If the server did not return a 200 OK response, // then throw an exception. throw Exception('Failed to load memes'); } } Future<List<Meme>> getFirstMemes() async { var token = await getToken(); if (token == null) { return fetchMemes(1, 3); } final response = await http.get( Uri.http(BASE_URL, FIRST_MEMES), headers: {"cookie": "x_forvovka_memes=$token"}, ); if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. return (json.decode(response.body)['message'] as List).map((i) { return Meme.fromJson(i); }).toList(); } else { // If the server did not return a 200 OK response, // then throw an exception. throw Exception('Failed to load memes'); } } Future<List<Meme>> scoreAndGetMem( int memId, Reaction reaction, int memCount) async { String token = await getToken(); if (token == null) { return fetchMemes(memCount, 1); } var body = { 'reaction': reaction == Reaction.like ? 'like' : 'dislike', 'mem_id': memId.toString(), }; final response = await http.post( Uri.http( BASE_URL, SET_REACTION, ), body: body, // headers: {"cookie": "x_forvovka_memes=$token"}, ); print(response.headers); if (response.statusCode == 200) { // If the server did return a 200 OK response, return (json.decode(response.body)['message'] as List).map((i) { return Meme.fromJson(i); }).toList(); } else { // If the server did not return a 200 OK response, // then throw an exception. throw Exception('Failed to score meme'); } }
0
mirrored_repositories/memes/lib
mirrored_repositories/memes/lib/api/users_api.dart
import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:memes/database/database_hepler.dart'; import 'package:memes/database/model/user.dart'; import 'package:memes/constants/api.dart'; void createOrUpdate(Map usr) async { var db = new DatabaseHelper(); var user = await db.getUserByLogin(usr["login"]); if (user != null) { db.updateUser(new User.fromMap(usr)); } else { db.saveUser(new User.fromMap(usr)); } } Future<bool> signIn(String login, String password) async { var usr = {'login': login.toString(), 'password': password.toString()}; final response = await http.post(Uri.https(BASE_URL, SIGN_IN), body: usr); if (response.statusCode == 200) { var token = json.decode(response.body)["message"]["auth_token"].toString(); usr["token"] = token; createOrUpdate(usr); return true; } else { // If the server did not return a 200 OK response, // then throw an exception. // throw Exception('Failed to sign in'); return false; } } Future<bool> signUp(String login, String password) async { var usr = {'login': login.toString(), 'password': password.toString()}; final response = await http.post(Uri.https(BASE_URL, SIGN_UP), body: usr); if (response.statusCode == 200) { return signIn(login, password); } else { // If the server did not return a 200 OK response, // then throw an exception. // throw Exception('Failed to sign up'); return false; } }
0
mirrored_repositories/memes/lib
mirrored_repositories/memes/lib/animations/spinner_animation.dart
import 'package:flutter/material.dart'; import 'dart:math' as math; import 'package:memes/resources/dimen.dart'; class SpinnerAnimation extends StatefulWidget { final Widget body; SpinnerAnimation({this.body}); @override _SpinnerAnimationState createState() => _SpinnerAnimationState(body: this.body); } class _SpinnerAnimationState extends State<SpinnerAnimation> with SingleTickerProviderStateMixin { final Widget body; _SpinnerAnimationState({this.body}); AnimationController _controller; @override void initState() { super.initState(); _controller = AnimationController( duration: const Duration(seconds: Dimen.five), vsync: this, )..repeat(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _controller, child: body, builder: (BuildContext context, Widget child) { return Transform.rotate( angle: _controller.value * 2.0 * math.pi, child: child, ); }, ); } }
0
mirrored_repositories/memes
mirrored_repositories/memes/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:memes/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_clock_app
mirrored_repositories/flutter_clock_app/lib/digital_clock.dart
// Copyright 2019 The Chromium Authors. 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:ui'; import 'package:flutter/services.dart'; import 'package:flutter_clock_helper/model.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; enum _Element { background, text, shadow } final _lightTheme = { _Element.background: Colors.white, _Element.text: Color.fromRGBO(0, 5, 33, 1), _Element.shadow: Colors.red, }; final _darkTheme = { _Element.background: Color.fromRGBO(0, 5, 33, 1), _Element.text: Colors.white, _Element.shadow: Color(0xFF00AA), }; /// A basic digital clock. /// /// You can do better than this! class DigitalClock extends StatefulWidget { const DigitalClock(this.model); final ClockModel model; @override _DigitalClockState createState() => _DigitalClockState(); } class _DigitalClockState extends State<DigitalClock> { DateTime _dateTime = DateTime.now(); Timer _timer; @override void initState() { super.initState(); // Set landspace mode SystemChrome.setPreferredOrientations( [DeviceOrientation.landscapeRight, DeviceOrientation.landscapeLeft]); widget.model.addListener(_updateModel); _updateTime(); _updateModel(); } @override void didUpdateWidget(DigitalClock oldWidget) { super.didUpdateWidget(oldWidget); if (widget.model != oldWidget.model) { oldWidget.model.removeListener(_updateModel); widget.model.addListener(_updateModel); } } @override void dispose() { _timer?.cancel(); widget.model.removeListener(_updateModel); widget.model.dispose(); SystemChrome.setPreferredOrientations([ DeviceOrientation.landscapeRight, DeviceOrientation.landscapeLeft, DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, ]); super.dispose(); } void _updateModel() { setState(() { // Cause the clock to rebuild when the model changes. }); } void _updateTime() { setState(() { _dateTime = DateTime.now(); // Update once per minute. If you want to update every second, use the // following code. _timer = Timer( Duration(minutes: 1) - Duration(seconds: _dateTime.second) - Duration(milliseconds: _dateTime.millisecond), _updateTime, ); // Update once per second, but make sure to do it at the beginning of each // new second, so that the clock is accurate. // _timer = Timer( // Duration(seconds: 1) - Duration(milliseconds: _dateTime.millisecond), // _updateTime, // ); }); } @override Widget build(BuildContext context) { final colors = Theme.of(context).brightness == Brightness.light ? _lightTheme : _darkTheme; final location = widget.model.location; final temp = widget.model.temperatureString; final weather = widget.model.weatherString; final hour = DateFormat(widget.model.is24HourFormat ? 'HH' : 'hh').format(_dateTime); final minute = DateFormat('mm').format(_dateTime); final fontSize = MediaQuery.of(context).size.width / 4; final defaultStyle = TextStyle( color: colors[_Element.text], fontFamily: 'Montserrat', fontWeight: FontWeight.w300, fontSize: fontSize, shadows: [Shadow(color: colors[_Element.shadow])]); return Container( color: colors[_Element.background], child: Center( child: DefaultTextStyle( style: defaultStyle, child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( hour + ":", style: TextStyle( color: colors[_Element.text], fontWeight: FontWeight.w200, shadows: [ Shadow( color: Colors.white, blurRadius: 10, offset: Offset(0, 3.0)), ]), ), Text(minute, style: TextStyle( fontWeight: FontWeight.w200, color: Color.fromRGBO(255, 0, 170, 1), shadows: [ Shadow( color: (colors == _lightTheme) ? Colors.transparent : colors[_Element.shadow], blurRadius: 10, offset: Offset(0, 3.0)) ], )) ], ), Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( decoration: BoxDecoration( border: Border.all( width: 2, color: Color.fromRGBO(255, 0, 170, 1)), borderRadius: BorderRadius.all(Radius.circular(3))), child: Padding( padding: const EdgeInsets.all(5.0), child: Text( location.toUpperCase(), style: TextStyle( fontSize: 20, color: colors[_Element.text]), ), ), ), ], ), ), Padding( padding: const EdgeInsets.only(top: 15, bottom: 10), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.only(right: 10), child: Container( decoration: BoxDecoration( border: Border.all( width: 2, color: Color.fromRGBO(255, 0, 170, 1)), borderRadius: BorderRadius.all(Radius.circular(3))), child: Padding( padding: const EdgeInsets.all(5.0), child: Text( weather.toUpperCase(), style: TextStyle( fontSize: 20, color: colors[_Element.text]), ), ), ), ), Container( decoration: BoxDecoration( border: Border.all( width: 2, color: Color.fromRGBO(255, 0, 170, 1)), borderRadius: BorderRadius.all(Radius.circular(3))), child: Padding( padding: const EdgeInsets.all(5.0), child: Text( temp.toUpperCase(), style: TextStyle( fontSize: 20, color: colors[_Element.text]), ), ), ), ], ), ) ], ) ], )), ), ); } }
0
mirrored_repositories/flutter_clock_app
mirrored_repositories/flutter_clock_app/lib/main.dart
// Copyright 2019 The Chromium Authors. 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:io'; import 'package:flutter_clock_helper/customizer.dart'; import 'package:flutter_clock_helper/model.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'digital_clock.dart'; void main() { // A temporary measure until Platform supports web and TargetPlatform supports // macOS. if (!kIsWeb && Platform.isMacOS) { // TODO(gspencergoog): Update this when TargetPlatform includes macOS. // https://github.com/flutter/flutter/issues/31366 // See https://github.com/flutter/flutter/wiki/Desktop-shells#target-platform-override. debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia; } // This creates a clock that enables you to customize it. // // The [ClockCustomizer] takes in a [ClockBuilder] that consists of: // - A clock widget (in this case, [DigitalClock]) // - A model (provided to you by [ClockModel]) // For more information, see the flutter_clock_helper package. // // Your job is to edit [DigitalClock], or replace it with your // own clock widget. (Look in digital_clock.dart for more details!) runApp(ClockCustomizer((ClockModel model) => DigitalClock(model))); }
0
mirrored_repositories/corona_stats
mirrored_repositories/corona_stats/lib/country.dart
List<String> country = [ "Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Anguilla", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burundi", "Cambodia", "Cameroon", "Canada", "Caribbean Netherlands", "Central African Republic", "Chad", "Chile", "China", "Colombia", "Congo", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czechia", "Denmark", "Dominica", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands", "Faroe Islands", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guatemala", "Guinea", "Guyana", "Haiti", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kuwait", "Kyrgyzstan", "Kyrgyzstan", "Kyrgyzstan", "Latvia", "Lebanon", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Moldova", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nepal", "Netherlands", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Norway", "Oman", "Pakistan", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland", "Portugal", "Qatar", "Romania", "Russia", "Rwanda", "San Marino", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Sint Maarten", "Slovakia", "Slovenia", "Somalia", "South Africa", "South Korea", "South Sudan", "Spain", "Sri Lanka", "Sudan", "Suriname", "Sweden", "Switzerland", "Syria", "Taiwan", "Tanzania", "Thailand", "Togo", "Tunisia", "Turkey", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay", "Uzbekistan", "Vatican City", "Venezuela", "Vietnam", "Western Sahara", "Yemen", "Zambia", "Zimbabwe" ];
0
mirrored_repositories/corona_stats
mirrored_repositories/corona_stats/lib/data.dart
import 'dart:convert'; import 'package:http/http.dart' as http; class Data { final String country; Data(this.country); Future getData() async { http.Response response; if (country == "Hong Kong") { response = await http.get("https://corona-stats.online/HK?format=json"); } if (country == "South Korea") { response = await http.get("https://corona-stats.online/KR?format=json"); } if (country == "United Arab Emirates") { response = await http.get("https://corona-stats.online/AE?format=json"); } if (country == "United Kingdom") { response = await http.get("https://corona-stats.online/UK?format=json"); } if (country == "United States") { response = await http.get("https://corona-stats.online/US?format=json"); } else { response = await http.get("https://corona-stats.online/$country?format=json"); } if (response.statusCode == 200) { String data = response.body; var decodedData = jsonDecode(data); return decodedData; } } }
0
mirrored_repositories/corona_stats
mirrored_repositories/corona_stats/lib/about.dart
import 'package:flutter/material.dart'; class About extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData.dark(), home: Scaffold( body: SafeArea( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('S.n. Ahad', style: TextStyle( fontFamily: 'Orbitron Regular', fontSize: 30.0, fontWeight: FontWeight.bold, )), Text( 'DEVELOPER', style: TextStyle( fontFamily: 'Orbitron Regular', color: Colors.teal.shade100, fontSize: 12.0, letterSpacing: 2.5, fontWeight: FontWeight.bold), ), SizedBox( height: 20.0, width: 150.0, child: Divider( color: Colors.teal.shade100, ), ), Card( margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0), child: ListTile( leading: Icon( Icons.link, ), title: Text( 'www.github.com/i-am-ahad', style: TextStyle( fontFamily: 'Ubuntu Regular', fontSize: 20.0), ))), Card( margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0), child: ListTile( leading: Icon( Icons.email, ), title: Text( '[email protected]', style: TextStyle( fontFamily: 'Ubuntu Regular', fontSize: 20.0, ), ), )) ], ), ), ), ); } }
0
mirrored_repositories/corona_stats
mirrored_repositories/corona_stats/lib/indicator.dart
import 'package:flutter/material.dart'; class Indicator extends StatelessWidget { final Color color; final String text; final bool isSquare; final double size; final Color textColor; const Indicator({ Key key, this.color, this.text, this.isSquare, this.size = 16, this.textColor = const Color(0xffffffff), }) : super(key: key); @override Widget build(BuildContext context) { return Row( children: <Widget>[ Container( width: size, height: size, decoration: BoxDecoration( shape: isSquare ? BoxShape.rectangle : BoxShape.circle, color: color, ), ), const SizedBox( width: 4, ), Text( text, style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: textColor, fontFamily: "Ubuntu Regular"), ) ], ); } }
0
mirrored_repositories/corona_stats
mirrored_repositories/corona_stats/lib/main.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'country.dart'; import 'package:fl_chart/fl_chart.dart'; import 'data.dart'; import 'indicator.dart'; import 'about.dart'; void main() => runApp(Corona()); class Corona extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData.dark(), debugShowCheckedModeBanner: false, home: CoronaStats(), ); } } class CoronaStats extends StatefulWidget { @override _CoronaStatsState createState() => _CoronaStatsState(); } class _CoronaStatsState extends State<CoronaStats> { int touchedIndex; String dropdownValue = 'Bangladesh'; String totalCases = '1'; String newCases = '1'; String totalDeaths = '1'; String recovered = '1'; String worldTotalCases = 'Loading...'; String worldNewCases = 'Loading...'; String worldTotalDeaths = 'Loading...'; String worldRecovered = 'Loading...'; double valueForTotalCases; double valueForNewCases; double valueForTotalDeaths; double valueForRecovered; void getData() async { Data data = new Data(dropdownValue); var fromAPI = await data.getData(); setState(() { totalCases = fromAPI['data'][0]['cases'].toString(); newCases = fromAPI['data'][0]['todayCases'].toString(); totalDeaths = fromAPI['data'][0]['deaths'].toString(); recovered = fromAPI['data'][0]['recovered'].toString(); worldTotalCases = fromAPI['worldStats']['cases'].toString(); worldNewCases = fromAPI['worldStats']['todayCases'].toString(); worldTotalDeaths = fromAPI['worldStats']['deaths'].toString(); worldRecovered = fromAPI['worldStats']['recovered'].toString(); double oneHundredPercent = double.parse(totalCases) + double.parse(newCases) + double.parse(totalDeaths) + double.parse(recovered); valueForTotalCases = (int.parse(totalCases) / oneHundredPercent * 100) + 10; valueForNewCases = (int.parse(newCases) / oneHundredPercent * 100) + 10; valueForTotalDeaths = (int.parse(totalDeaths) / oneHundredPercent * 100) + 10; valueForRecovered = (int.parse(recovered) / oneHundredPercent * 100) + 10; }); } @override void initState() { super.initState(); getData(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( actions: <Widget>[ IconButton( icon: Icon(Icons.info), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (BuildContext context) { return About(); }), ); }, ) ], title: Text( "C O R O N A S T A T S", style: TextStyle(fontFamily: "Orbitron Regular"), ), centerTitle: true, ), body: SafeArea( child: Center( child: Padding( padding: const EdgeInsets.all(20.0), child: Column( children: <Widget>[ Text( "Select your country", style: TextStyle(fontFamily: "Ubuntu Regular", fontSize: 25), ), SizedBox( height: 20, ), DropdownButton<String>( value: dropdownValue, icon: Icon(Icons.flag), iconSize: 24, elevation: 16, style: TextStyle(fontFamily: "Ubuntu Regular", fontSize: 18), underline: Container( height: 2, color: Colors.redAccent, ), onChanged: (String newValue) { setState(() { dropdownValue = newValue; getData(); showingSections(); }); }, items: country.map<DropdownMenuItem<String>>((String value) { return DropdownMenuItem<String>( value: value, child: Text(value), ); }).toList(), ), Expanded( child: AspectRatio( aspectRatio: 1, child: PieChart( PieChartData( pieTouchData: PieTouchData(touchCallback: (pieTouchResponse) { setState(() { if (pieTouchResponse.touchInput is FlLongPressEnd || pieTouchResponse.touchInput is FlPanEnd) { touchedIndex = -1; } else { touchedIndex = pieTouchResponse.touchedSectionIndex; } }); }), borderData: FlBorderData( show: false, ), sectionsSpace: 0, centerSpaceRadius: 40, sections: showingSections()), ), ), ), Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ Text( 'WORLD STATS', style: TextStyle( fontSize: 18, fontFamily: "Ubuntu Regular", fontWeight: FontWeight.w800), ), ], ), SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: const <Widget>[ Indicator( color: Colors.lightBlue, text: 'Total Cases', isSquare: true, ), SizedBox( height: 8, ), Indicator( color: Colors.yellowAccent, text: 'New Cases', isSquare: true, ), SizedBox( height: 8, ), Indicator( color: Colors.red, text: 'Total Deaths', isSquare: true, ), SizedBox( height: 8, ), Indicator( color: Colors.green, text: 'Recovered', isSquare: true, ), SizedBox( height: 28, ), ], ), SizedBox( width: 40, ), Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Row( children: <Widget>[ Indicator( color: Colors.lightBlue, text: '', isSquare: false, ), Text( worldTotalCases + '', style: TextStyle( fontSize: 16, fontFamily: "Ubuntu Regular", ), ), ], ), SizedBox( height: 8, ), Row( children: <Widget>[ Indicator( color: Colors.yellowAccent, text: '', isSquare: false, ), Text( worldNewCases, style: TextStyle( fontSize: 16, fontFamily: "Ubuntu Regular", ), ), ], ), SizedBox( height: 8, ), Row( children: <Widget>[ Indicator( color: Colors.red, text: '', isSquare: false, ), Text( worldTotalDeaths, style: TextStyle( fontSize: 16, fontFamily: "Ubuntu Regular", ), ), ], ), SizedBox( height: 8, ), Row( children: <Widget>[ Indicator( color: Colors.green, text: '', isSquare: false, ), Text( worldRecovered, style: TextStyle( fontSize: 16, fontFamily: "Ubuntu Regular", ), ), ], ), SizedBox( height: 28, ), ], ), ], ), const SizedBox( width: 28, ), ], ), ), ), ), ); } List<PieChartSectionData> showingSections() { return List.generate(4, (i) { final isTouched = i == touchedIndex; final double fontSize = isTouched ? 25 : 16; final double radius = isTouched ? 60 : 50; switch (i) { case 0: return PieChartSectionData( color: Colors.lightBlue, value: valueForTotalCases, title: totalCases, radius: radius, titleStyle: TextStyle( fontFamily: "Ubuntu Regular", fontSize: fontSize, fontWeight: FontWeight.bold, color: const Color(0xff000000)), ); case 1: return PieChartSectionData( color: Colors.yellowAccent, value: valueForNewCases, title: newCases, radius: radius, titleStyle: TextStyle( fontSize: fontSize, fontWeight: FontWeight.bold, color: const Color(0xff000000)), ); case 2: return PieChartSectionData( color: Colors.red, value: valueForTotalDeaths, title: totalDeaths, radius: radius, titleStyle: TextStyle( fontSize: fontSize, fontWeight: FontWeight.bold, color: const Color(0xff000000)), ); case 3: return PieChartSectionData( color: Colors.green, value: valueForRecovered, title: recovered, radius: radius, titleStyle: TextStyle( fontSize: fontSize, fontWeight: FontWeight.bold, color: const Color(0xff000000)), ); default: return null; } }); } }
0
mirrored_repositories/corona_stats
mirrored_repositories/corona_stats/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:coronastats/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(Corona()); // 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/productos_app
mirrored_repositories/productos_app/lib/main.dart
import 'package:flutter/material.dart'; import 'package:productos_app/screens/screens.dart'; import 'package:productos_app/services/products_service.dart'; import 'package:provider/provider.dart'; void main() => runApp(AppState()); class AppState extends StatelessWidget { @override Widget build(BuildContext context) { return MultiProvider( providers: [ChangeNotifierProvider(create: (_) => ProductsService())], child: const MyApp(), ); } } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Productos App', initialRoute: 'home', routes: { 'login': (_) => LoginScreen(), 'home': (_) => HomeScreen(), 'product': (_) => ProductScreen(), }, theme: ThemeData.light().copyWith( scaffoldBackgroundColor: Colors.grey[300], appBarTheme: const AppBarTheme(elevation: 0, color: Colors.indigo), floatingActionButtonTheme: FloatingActionButtonThemeData( backgroundColor: Colors.indigo, elevation: 0))); } }
0
mirrored_repositories/productos_app/lib
mirrored_repositories/productos_app/lib/widgets/product_image.dart
import 'package:flutter/material.dart'; class ProductImage extends StatelessWidget { @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(left: 10, right: 10, top: 10), child: Container( decoration: _buildBoxDecoration(), width: double.infinity, height: 450, child: const ClipRRect( borderRadius: BorderRadius.only( topLeft: Radius.circular(45), topRight: Radius.circular(45)), child: FadeInImage( image: NetworkImage('https://via.placeholder.com/400x300/green'), placeholder: AssetImage('assets/jar-loading.gif'), fit: BoxFit.cover, ), ), ), ); } BoxDecoration _buildBoxDecoration() => BoxDecoration( borderRadius: const BorderRadius.only( topLeft: Radius.circular(45), topRight: Radius.circular(45)), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.05), blurRadius: 10, offset: const Offset(0, 5)) ]); }
0
mirrored_repositories/productos_app/lib
mirrored_repositories/productos_app/lib/widgets/card_container.dart
import 'package:flutter/material.dart'; class CardContainer extends StatelessWidget { final Widget child; const CardContainer({ Key? key, required this.child, }) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.symmetric(horizontal: 30), child: Container( width: double.infinity, padding: EdgeInsets.all(20), decoration: _createCardShape(), child: this.child, ), ); } BoxDecoration _createCardShape() => BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(25), boxShadow: [ BoxShadow( color: Colors.black12, blurRadius: 15, offset: Offset(0, 5)) ]); }
0
mirrored_repositories/productos_app/lib
mirrored_repositories/productos_app/lib/widgets/auth_background.dart
import 'package:flutter/material.dart'; class AuthBackground extends StatelessWidget { final Widget child; const AuthBackground({super.key, required this.child}); @override Widget build(BuildContext context) { return Container( width: double.infinity, height: double.infinity, child: Stack(children: [ _purpleBox(), const _HeaderIcon(), this.child, ]), ); } } class _HeaderIcon extends StatelessWidget { const _HeaderIcon({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return SafeArea( child: Container( width: double.infinity, margin: EdgeInsets.only(top: 30), child: Icon( Icons.person_pin, color: Colors.white, size: 100, ), ), ); } } class _purpleBox extends StatelessWidget { @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return Container( width: double.infinity, height: size.height * 0.4, decoration: _purpleBackground(), child: Stack(children: [ Positioned( child: _Bubble(), top: 90, left: 30, ), Positioned( child: _Bubble(), top: -40, left: -30, ), Positioned( child: _Bubble(), top: -50, right: -20, ), Positioned( child: _Bubble(), bottom: -50, left: 10, ), Positioned( child: _Bubble(), bottom: 120, right: 20, ), ]), ); } BoxDecoration _purpleBackground() => const BoxDecoration( gradient: LinearGradient(colors: [ Color.fromRGBO(63, 63, 156, 1), Color.fromRGBO(90, 70, 178, 1) ])); } class _Bubble extends StatelessWidget { @override Widget build(BuildContext context) { return Container( width: 100, height: 100, decoration: BoxDecoration( borderRadius: BorderRadius.circular(100), color: Color.fromRGBO(255, 255, 255, 0.05)), ); } }
0
mirrored_repositories/productos_app/lib
mirrored_repositories/productos_app/lib/widgets/product_card.dart
import 'dart:ui'; import 'package:flutter/material.dart'; class ProductCard extends StatelessWidget { @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.symmetric(horizontal: 20), child: Container( margin: EdgeInsets.only(top: 30, bottom: 50), width: double.infinity, height: 400, decoration: _cardBorders(), child: Stack(alignment: Alignment.bottomLeft, children: [ _BackgroundImage(), _ProductDetails(), Positioned(top: 0, right: 0, child: _PriceTag()), //TODO: Mostrar de manera condicional Positioned(top: 0, left: 0, child: _NotAvailable()) ]), ), ); } BoxDecoration _cardBorders() { return BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(25), boxShadow: [ BoxShadow(color: Colors.black12, offset: Offset(0, 7), blurRadius: 10) ]); } } class _NotAvailable extends StatelessWidget { @override Widget build(BuildContext context) { return Container( child: FittedBox( fit: BoxFit.contain, child: Padding( padding: EdgeInsets.symmetric(horizontal: 10), child: Text( 'No disponible', style: TextStyle(color: Colors.white, fontSize: 20), ), ), ), width: 100, height: 70, alignment: Alignment.center, decoration: BoxDecoration( color: Colors.yellow[800], borderRadius: BorderRadius.only( topRight: Radius.circular(25), bottomLeft: Radius.circular(25))), ); } } class _PriceTag extends StatelessWidget { @override Widget build(BuildContext context) { return Container( child: FittedBox( fit: BoxFit.contain, child: Padding( padding: EdgeInsets.symmetric(horizontal: 10), child: Text( '\$103.99', style: TextStyle(color: Colors.white, fontSize: 20), ), ), ), width: 100, height: 70, alignment: Alignment.center, decoration: BoxDecoration( color: Colors.indigo, borderRadius: BorderRadius.only( topRight: Radius.circular(25), bottomLeft: Radius.circular(25))), ); } } class _ProductDetails extends StatelessWidget { @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(right: 50), child: Container( padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10), width: double.infinity, height: 70, decoration: _buildBoxDecoration(), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Disco Duro G', style: TextStyle( fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold), maxLines: 1, overflow: TextOverflow.ellipsis, ), Text( 'Id de disco duro', style: TextStyle(fontSize: 15, color: Colors.white), ) ], ), ), ); } BoxDecoration _buildBoxDecoration() => BoxDecoration( color: Colors.indigo, borderRadius: BorderRadius.only( bottomLeft: Radius.circular(25), topRight: Radius.circular(25))); } class _BackgroundImage extends StatelessWidget { @override Widget build(BuildContext context) { return ClipRRect( borderRadius: BorderRadius.circular(25), child: Container( width: double.infinity, height: 400, child: FadeInImage( placeholder: AssetImage('assets/jar-loading.gif'), image: NetworkImage('https://via.placeholder.com/400x300/f6f6f6'), fit: BoxFit.cover, ), ), ); } }
0
mirrored_repositories/productos_app/lib
mirrored_repositories/productos_app/lib/widgets/widgets.dart
export 'package:productos_app/widgets/auth_background.dart'; export 'package:productos_app/widgets/card_container.dart'; export 'package:productos_app/widgets/product_card.dart'; export 'package:productos_app/widgets/product_image.dart';
0
mirrored_repositories/productos_app/lib
mirrored_repositories/productos_app/lib/models/product.dart
// To parse this JSON data, do // // final product = productFromMap(jsonString); import 'dart:convert'; import 'package:productos_app/models/models.dart'; class Product { Product( {required this.available, required this.name, this.picture, required this.price, this.id}); bool available; String name; String? picture; double price; String? id; factory Product.fromJson(String str) => Product.fromMap(json.decode(str)); String toJson() => json.encode(toMap()); factory Product.fromMap(Map<String, dynamic> json) => Product( available: json["available"], name: json["name"], picture: json["picture"], price: json["price"].toDouble(), ); Map<String, dynamic> toMap() => { "available": available, "name": name, "picture": picture, "price": price, }; Product copy() => Product( available: this.available, name: this.name, picture: this.picture, price: this.price, id: this.id, ); }
0
mirrored_repositories/productos_app/lib
mirrored_repositories/productos_app/lib/models/models.dart
export 'package:productos_app/models/product.dart';
0
mirrored_repositories/productos_app/lib
mirrored_repositories/productos_app/lib/ui/input_decorations.dart
import 'package:flutter/material.dart'; class InputDecorations { static InputDecoration authInputDecoration( {required String hintText, required String labelText, IconData? prefixIcon}) { return InputDecoration( enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.deepPurple), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.deepPurple, width: 2)), hintText: hintText, labelText: labelText, labelStyle: TextStyle(color: Colors.grey), prefixIcon: prefixIcon != null ? Icon(prefixIcon, color: Colors.deepPurple) : null); } }
0
mirrored_repositories/productos_app/lib
mirrored_repositories/productos_app/lib/services/services.dart
export 'package:productos_app/services/products_service.dart';
0
mirrored_repositories/productos_app/lib
mirrored_repositories/productos_app/lib/services/products_service.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:productos_app/models/models.dart'; import 'package:http/http.dart' as http; class ProductsService extends ChangeNotifier { final String _baseUrl = ''; final List<Product> products = []; bool isLoading = true; ProductsService() { this.loadProducts(); } Future loadProducts() async { final url = Uri.https(_baseUrl, 'products.json'); final resp = await http.get(url); final Map<String, dynamic> productsMap = json.decode(resp.body); productsMap.forEach((key, value) { final tempProduct = Product.fromMap(value); tempProduct.id = key; this.products.add(tempProduct); }); } }
0
mirrored_repositories/productos_app/lib
mirrored_repositories/productos_app/lib/screens/screens.dart
export 'package:productos_app/screens/home_screen.dart'; export 'package:productos_app/screens/login_screen.dart'; export 'package:productos_app/screens/product_screen.dart';
0
mirrored_repositories/productos_app/lib
mirrored_repositories/productos_app/lib/screens/home_screen.dart
import 'package:flutter/material.dart'; import 'package:productos_app/services/products_service.dart'; import 'package:productos_app/widgets/widgets.dart'; import 'package:provider/provider.dart'; class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { final productService = Provider.of<ProductsService>(context); return Scaffold( appBar: AppBar( title: const Text('Productos'), ), body: ListView.builder( itemCount: 10, itemBuilder: (BuildContext context, int index) => GestureDetector( onTap: () => Navigator.pushNamed(context, 'product'), child: ProductCard())), floatingActionButton: FloatingActionButton( child: Icon(Icons.add), onPressed: (() {}), ), ); } }
0
mirrored_repositories/productos_app/lib
mirrored_repositories/productos_app/lib/screens/login_screen.dart
import 'package:flutter/material.dart'; import 'package:productos_app/providers/login_form_provider.dart'; import 'package:provider/provider.dart'; import 'package:productos_app/ui/input_decorations.dart'; import 'package:productos_app/widgets/widgets.dart'; class LoginScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: AuthBackground( child: SingleChildScrollView( child: Column( children: [ const SizedBox( height: 200, ), CardContainer( child: Column(children: [ const SizedBox( height: 0, ), CardContainer( child: Column( children: [ const SizedBox( height: 10, ), Text( 'Login', style: Theme.of(context).textTheme.headline4, ), const SizedBox( height: 30, ), ChangeNotifierProvider( create: (_) => LoginFormProvider(), child: _LoginForm(), ), ], )) ]), ), const SizedBox( height: 50, ), const Text( 'Crear una nueva cuenta', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), const SizedBox( height: 50, ) ], ), ))); } } class _LoginForm extends StatelessWidget { @override Widget build(BuildContext context) { final loginForm = Provider.of<LoginFormProvider>(context); return Container( child: Form( //TODO:Mantener la referencia al key key: loginForm.formKey, autovalidateMode: AutovalidateMode.onUserInteraction, child: Column( children: [ TextFormField( autocorrect: false, keyboardType: TextInputType.emailAddress, decoration: InputDecorations.authInputDecoration( hintText: '[email protected]', labelText: 'Correo Electrónico', prefixIcon: Icons.alternate_email_rounded), validator: (value) { String pattern = r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'; RegExp regExp = new RegExp(pattern); return regExp.hasMatch(value ?? '') ? null : 'El valor ingresado no luce como un correo'; }, onChanged: (value) => loginForm.email = value, ), const SizedBox( height: 30, ), TextFormField( autocorrect: false, obscureText: true, keyboardType: TextInputType.emailAddress, decoration: InputDecorations.authInputDecoration( hintText: '********', labelText: 'Contraseña', prefixIcon: Icons.lock_outline), validator: (value) { return (value != null && value.length >= 6) ? null : 'La contraseña debe de ser de 6 caracteres'; }, onChanged: (value) => loginForm.password = value, ), const SizedBox( height: 30, ), MaterialButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10)), disabledColor: Colors.grey, elevation: 0, color: Colors.deepPurple, child: Container( padding: EdgeInsets.symmetric(horizontal: 60, vertical: 15), child: Text( loginForm.isLoading ? 'Espere' : 'Ingresar', style: TextStyle(color: Colors.white), ), ), onPressed: loginForm.isLoading ? null : () async { FocusScope.of(context).unfocus(); if (!loginForm.isValidForm()) return; loginForm.isLoading = true; Future.delayed(Duration(seconds: 2)); //TODO: Validar si el loggin es correcto loginForm.isLoading = false; Navigator.pushReplacementNamed(context, 'home'); }) ], ), ), ); } }
0
mirrored_repositories/productos_app/lib
mirrored_repositories/productos_app/lib/screens/product_screen.dart
import 'package:flutter/material.dart'; import 'package:productos_app/ui/input_decorations.dart'; import 'package:productos_app/widgets/widgets.dart'; class ProductScreen extends StatelessWidget { const ProductScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( body: SingleChildScrollView( // controller: controller, child: Column( children: [ Stack( children: [ ProductImage(), Positioned( top: 60, left: 20, child: IconButton( onPressed: (() => Navigator.of(context).pop()), icon: const Icon( Icons.arrow_back_ios_new, size: 40, color: Colors.white, ), )), Positioned( top: 60, right: 20, child: IconButton( onPressed: (() {}), icon: const Icon( Icons.camera_alt_outlined, size: 40, color: Colors.white, ), )) ], ), _ProductForm(), const SizedBox( height: 100, ) ], ), ), floatingActionButtonLocation: FloatingActionButtonLocation.endDocked, floatingActionButton: FloatingActionButton( child: Icon(Icons.save_outlined), onPressed: () { //TODO: Guardar Producto }, ), ); } } class _ProductForm extends StatelessWidget { @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Container( padding: const EdgeInsets.symmetric(horizontal: 20), width: double.infinity, decoration: _buildBoxDecoration(), child: Form( child: Column( children: [ const SizedBox( height: 10, ), TextFormField( decoration: InputDecorations.authInputDecoration( hintText: 'Nombre del producto', labelText: 'Nombre:'), ), const SizedBox( height: 30, ), TextFormField( keyboardType: TextInputType.number, decoration: InputDecorations.authInputDecoration( hintText: '\$150', labelText: 'Precio:'), ), const SizedBox( height: 30, ), SwitchListTile.adaptive( value: true, title: Text('Disponible'), activeColor: Colors.indigo, onChanged: (value) { //TODO: Pendiente }), const SizedBox( height: 30, ), ], )), ), ); } BoxDecoration _buildBoxDecoration() => BoxDecoration( color: Colors.white, borderRadius: const BorderRadius.only( bottomRight: Radius.circular(25), bottomLeft: Radius.circular(25)), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.05), offset: const Offset(0, 5), blurRadius: 5) ]); }
0
mirrored_repositories/productos_app/lib
mirrored_repositories/productos_app/lib/providers/login_form_provider.dart
import 'package:flutter/material.dart'; class LoginFormProvider extends ChangeNotifier { GlobalKey<FormState> formKey = new GlobalKey<FormState>(); String email = ''; String password = ''; bool _isLoading = false; bool get isLoading => _isLoading; set isLoading(bool value) { _isLoading = value; notifyListeners(); } bool isValidForm() { return formKey.currentState?.validate() ?? false; } }
0
mirrored_repositories/productos_app
mirrored_repositories/productos_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 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:productos_app/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/Handcuffed
mirrored_repositories/Handcuffed/lib/main.dart
import 'dart:convert'; import 'dart:io'; import 'package:Face_recognition/pages/admin.dart'; import 'package:Face_recognition/pages/login.dart'; import 'package:Face_recognition/pages/login_admin.dart'; import 'package:Face_recognition/pages/login_user.dart'; import 'package:Face_recognition/pages/otp_user.dart'; import 'package:Face_recognition/pages/camera.dart'; import 'package:Face_recognition/pages/user.dart'; import 'package:Face_recognition/utils/routes.dart'; import 'package:google_ml_kit/google_ml_kit.dart'; import 'package:path_provider/path_provider.dart'; import 'package:camera/camera.dart'; // import 'package:firebase_ml_vision/firebase_ml_vision.dart'; import 'package:flutter/material.dart'; import 'pages/detector_painters.dart'; import 'pages/utils.dart'; import 'package:image/image.dart' as imglib; import 'package:tflite_flutter/tflite_flutter.dart' as tfl; import 'package:quiver/collection.dart'; import 'package:flutter/services.dart'; void main() { runApp(MaterialApp( themeMode: ThemeMode.light, theme: ThemeData(brightness: Brightness.light), // home: _MyHomePage(), debugShowCheckedModeBanner: false, routes: { "/": (context) => loginPage(), MyRoutes.loginRoute: (context) => loginPage(), MyRoutes.userRoute: (context) => user(), MyRoutes.adminRoute: (context) => admin(), MyRoutes.login_userRoute: (context) => login_user(), MyRoutes.login_adminRoute: (context) => login_admin(), MyRoutes.otp_userRoute: (context) => otp(), MyRoutes.cameraRoute: (context) => camera(false), })); }
0
mirrored_repositories/Handcuffed/lib
mirrored_repositories/Handcuffed/lib/pages/login_admin.dart
import 'package:Face_recognition/pages/widgets/header.dart'; import 'package:Face_recognition/pages/widgets/themes.dart'; import 'package:Face_recognition/utils/routes.dart'; import 'package:flutter/material.dart'; class login_admin extends StatefulWidget { const login_admin({Key? key}) : super(key: key); @override State<login_admin> createState() => _login_adminState(); } class _login_adminState extends State<login_admin> { double headerheight = 250; bool changeButton = false; String entered_phone = ''; final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: SingleChildScrollView( child: Form( key: _formKey, child: Column(children: [ Container( height: headerheight, child: HeaderWidget( headerheight, true, "Welcome", )), SafeArea( child: Column(children: [ Text( "Admin Login", style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold), ), SizedBox( height: 15.0, ), Padding( padding: EdgeInsets.symmetric(vertical: 16.0, horizontal: 32.0), child: Column(children: [ TextFormField( keyboardType: TextInputType.number, // inputFormatters: <TextInputFormatter>[ // FilteringTextInputFormatter.digitsOnly // ], cursorColor: MyTheme.blue4, decoration: InputDecoration( hintText: "Enter Mobile Number", labelText: "Mobile Number", ), validator: (value) { if (value!.isEmpty) { return "Mobile Number can not be empty"; } else if (value.length <= 9) { return "Mobile Number should be atleast 10 digits"; } return null; }, onChanged: (value) { setState(() { entered_phone = value; }); }, ), SizedBox( height: 50.0, ), Material( color: MyTheme.blue, borderRadius: BorderRadius.circular(changeButton ? 70 : 30), child: InkWell( onTap: () => Navigator.pushNamed(context, MyRoutes.adminRoute), //TODO: add send OTP functionality /* var userExists=await FirebaseService().verifyUserExistence(entered_phone); if(userExists){ var temp = await FirebaseService().sendOTP(entered_phone,context); moveToOTP(context: context, confirmationResult: temp); }else{ FlutterToastService().showToast('You are not authorized to use this app'); } */ child: AnimatedContainer( duration: Duration(seconds: 1), width: changeButton ? 50 : 150, height: 50, alignment: Alignment.center, child: changeButton ? Icon( Icons.done, color: Colors.white, ) : Text( "Login", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18), ), ), ), ), SizedBox( height: 75.0, ), ]), ), ]), ) ]), ), ), ); } }
0
mirrored_repositories/Handcuffed/lib
mirrored_repositories/Handcuffed/lib/pages/detector_painters.dart
import 'dart:ui'; // import 'package:firebase_ml_vision/firebase_ml_vision.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:google_ml_kit/google_ml_kit.dart'; class FaceDetectorPainter extends CustomPainter { FaceDetectorPainter(this.imageSize, this.results); final Size imageSize; late double scaleX; late double scaleY; late dynamic results; late Face face; @override void paint(Canvas canvas, Size size) { final Paint paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 3.0 ..color = Colors.greenAccent; for (String label in results.keys) { for (Face face in results[label]) { // face = results[label]; scaleX = size.width / imageSize.width; scaleY = size.height / imageSize.height; canvas.drawRRect( _scaleRect( rect: face.boundingBox, imageSize: imageSize, widgetSize: size, scaleX: scaleX, scaleY: scaleY), paint); TextSpan span = new TextSpan( style: new TextStyle(color: Colors.orange[300], fontSize: 15), text: label); TextPainter textPainter = new TextPainter( text: span, textAlign: TextAlign.left, textDirection: TextDirection.ltr); textPainter.layout(); textPainter.paint( canvas, new Offset( size.width - (60 + face.boundingBox.left.toDouble()) * scaleX, (face.boundingBox.top.toDouble() - 10) * scaleY)); } } } @override bool shouldRepaint(FaceDetectorPainter oldDelegate) { return oldDelegate.imageSize != imageSize || oldDelegate.results != results; } } RRect _scaleRect( {@required Rect? rect, @required Size? imageSize, @required Size? widgetSize, double? scaleX, double? scaleY}) { return RRect.fromLTRBR( (widgetSize!.width - rect!.left.toDouble() * scaleX!), rect.top.toDouble() * scaleY!, widgetSize.width - rect.right.toDouble() * scaleX, rect.bottom.toDouble() * scaleY, Radius.circular(10)); }
0
mirrored_repositories/Handcuffed/lib
mirrored_repositories/Handcuffed/lib/pages/otp_user.dart
import 'package:Face_recognition/pages/widgets/themes.dart'; import 'package:Face_recognition/utils/routes.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:pin_input_text_field/pin_input_text_field.dart'; class otp extends StatefulWidget { var confirmationResult; var phone; otp({this.confirmationResult,this.phone}); @override State<otp> createState() => _otpState(); } class _otpState extends State<otp> { // FirebaseAuth auth = FirebaseAuth.instance; TextEditingController phoneController = TextEditingController(text: "+923028997122"); TextEditingController otpController = TextEditingController(); String verificationIDReceived = ""; bool otpCodeVisible = false; late String enteredOTP; @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, backgroundColor: Colors.white, body: SafeArea( child: Padding( padding: EdgeInsets.symmetric(vertical: 24, horizontal: 32), child: Column( children: [ SizedBox( height: 18, ), Container( width: 300, height: 200, decoration: BoxDecoration( color: Colors.white, shape: BoxShape.rectangle, ), ), SizedBox( height: 24, ), Text( 'OTP Verification', style: TextStyle( fontSize: 22, fontWeight: FontWeight.bold, ), ), SizedBox( height: 10, ), Text( "Enter the OTP sent to +91 ${widget.phone}", style: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, color: Colors.black38, ), textAlign: TextAlign.center, ), SizedBox( height: 1, ), Container( padding: EdgeInsets.all(28), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(5), ), child: Column( children: [ SizedBox( height: 10, ), Container( child: Padding( padding: const EdgeInsets.all(8.0), child: PinInputTextField( decoration: BoxLooseDecoration(strokeColorBuilder: PinListenColorBuilder(MyTheme.blue, MyTheme.blue)), inputFormatters: [ FilteringTextInputFormatter.digitsOnly], onChanged: (value){ enteredOTP=value; }, //showFieldAsBox: true, onSubmit: (String pin){ //TODO: add on submit }, // end onSubmit ), // end PinEntryTextField() ), // end Padding() ), SizedBox( height: 40, ), SizedBox( width: double.infinity, child: ElevatedButton( onPressed: () => Navigator.pushNamed(context, MyRoutes.userRoute), // await FirebaseService().authenticateMe(confirmationResult, enteredOTP,context); style: ButtonStyle( foregroundColor: MaterialStateProperty.all<Color>(Colors.white), backgroundColor: MaterialStateProperty.all<Color>(MyTheme.blue), shape: MaterialStateProperty.all<RoundedRectangleBorder>( RoundedRectangleBorder( borderRadius: BorderRadius.circular(24.0), // focusedBorder: OutlineInputBorder( // borderSide: BorderSide(color: MyTheme.orange2)), ), ), ), child: Padding( padding: EdgeInsets.all(14.0), child: Text( 'Verify', style: TextStyle(fontSize: 16), ), ), ), ) ], ), ), SizedBox( height: 18, ), Text( "Incorrect phone number?", style: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, color: Colors.black38, ), textAlign: TextAlign.center, ), SizedBox( height: 18, ), TextButton(onPressed: (){Navigator.popAndPushNamed(context,MyRoutes.loginRoute);}, child: Text( "Enter new number", style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: MyTheme.blue, ), textAlign: TextAlign.center, ),) ], ), ), ), ); } void verifyOTP() async { // PhoneAuthCredential credential = PhoneAuthProvider.credential(verificationId: verificationIDReceived, smsCode: otpController.text); // await auth.signInWithCredential(credential).then((value){ print("You are logged in successfully"); // Fluttertoast.showToast( // msg: "You are logged in successfully", // toastLength: Toast.LENGTH_SHORT, // gravity: ToastGravity.CENTER, // timeInSecForIosWeb: 1, // backgroundColor: Colors.red, // textColor: Colors.white, // fontSize: 16.0 // } // ); } }
0
mirrored_repositories/Handcuffed/lib
mirrored_repositories/Handcuffed/lib/pages/login_user.dart
import 'package:Face_recognition/pages/widgets/header.dart'; import 'package:Face_recognition/pages/widgets/themes.dart'; import 'package:Face_recognition/utils/routes.dart'; import 'package:flutter/material.dart'; class login_user extends StatefulWidget { const login_user({Key? key}) : super(key: key); @override State<login_user> createState() => _login_userState(); } class _login_userState extends State<login_user> { double headerheight = 250; bool changeButton = false; String entered_phone = ''; TextEditingController _controller = TextEditingController(); //TextEditingController phoneController = TextEditingController(text: "+923028997122"); // TextEditingController otpController = TextEditingController(); // FirebaseAuth auth = FirebaseAuth.instance; String verificationIDReceived = ""; bool otpCodeVisible = false; final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: SingleChildScrollView( child: Form( key: _formKey, child: Column(children: [ Container( height: headerheight, child: HeaderWidget( headerheight, true, "Welcome", )), SafeArea( child: Column(children: [ Text( "User Login", style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold), ), SizedBox( height: 15.0, ), Padding( padding: EdgeInsets.symmetric(vertical: 16.0, horizontal: 32.0), child: Column(children: [ TextFormField( keyboardType: TextInputType.number, // inputFormatters: <TextInputFormatter>[ // FilteringTextInputFormatter.digitsOnly // ], cursorColor: MyTheme.blue4, decoration: InputDecoration( hintText: "Enter Mobile Number", labelText: "Mobile Number", ), validator: (value) { if (value!.isEmpty) { return "Mobile Number can not be empty"; } else if (value.length <= 9) { return "Mobile Number should be atleast 10 digits"; } return null; }, onChanged: (value) { setState(() { entered_phone = value; }); }, ), SizedBox( height: 50.0, ), Material( color: MyTheme.blue, borderRadius: BorderRadius.circular(changeButton ? 70 : 30), child: InkWell( onTap: () => Navigator.pushNamed(context, MyRoutes.userRoute), // { // Navigator.of(context).push(MaterialPageRoute( // builder: (context) => otp(_controller.text))); // }, // => // Navigator.pushNamed(context, MyRoutes.otp_userRoute), //TODO: add send OTP functionality /* var userExists=await FirebaseService().verifyUserExistence(entered_phone); if(userExists){ var temp = await FirebaseService().sendOTP(entered_phone,context); moveToOTP(context: context, confirmationResult: temp); }else{ FlutterToastService().showToast('You are not authorized to use this app'); } */ child: AnimatedContainer( duration: Duration(seconds: 1), width: changeButton ? 50 : 150, height: 50, alignment: Alignment.center, child: changeButton ? Icon( Icons.done, color: Colors.white, ) : Text( "Log in", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18), ), ), ), ), SizedBox( height: 75.0, ), ]), ), ]), ) ]), ), ), ); } }
0
mirrored_repositories/Handcuffed/lib
mirrored_repositories/Handcuffed/lib/pages/camera.dart
import 'dart:convert'; import 'dart:io'; import 'package:Face_recognition/pages/detector_painters.dart'; import 'package:Face_recognition/pages/utils.dart'; import 'package:Face_recognition/pages/widgets/themes.dart'; import 'package:google_ml_kit/google_ml_kit.dart'; import 'package:path_provider/path_provider.dart'; import 'package:camera/camera.dart'; // import 'package:firebase_ml_vision/firebase_ml_vision.dart'; import 'package:flutter/material.dart'; import 'detector_painters.dart'; import 'utils.dart'; import 'package:image/image.dart' as imglib; import 'package:tflite_flutter/tflite_flutter.dart' as tfl; import 'package:quiver/collection.dart'; import 'package:flutter/services.dart'; class camera extends StatefulWidget { bool abc; camera(this.abc); @override cameraState createState() => cameraState(); } class cameraState extends State<camera> { File? jsonFile; dynamic _scanResults; CameraController? _camera; var interpreter; bool _isDetecting = false; CameraLensDirection _direction = CameraLensDirection.front; dynamic data = {}; double threshold = 1.0; Directory? tempDir; List? e1; bool _faceFound = false; final TextEditingController _name = new TextEditingController(); @override void initState() { super.initState(); SystemChrome.setPreferredOrientations( [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]); _initializeCamera(); } Future loadModel() async { print("load"); try { final gpuDelegateV2 = tfl.GpuDelegateV2( options: tfl.GpuDelegateOptionsV2(), // options: tfl.GpuDelegateOptionsV2( // false, // tfl.TfLiteGpuInferenceUsage.fastSingleAnswer, // tfl.TfLiteGpuInferencePriority.minLatency, // tfl.TfLiteGpuInferencePriority.auto, // tfl.TfLiteGpuInferencePriority.auto, // ), ); var interpreterOptions = tfl.InterpreterOptions() ..addDelegate(gpuDelegateV2); interpreter = await tfl.Interpreter.fromAsset('mobilefacenet.tflite', options: interpreterOptions); } on Exception { print('Failed to load model.'); } } void _initializeCamera() async { await loadModel(); CameraDescription description = await getCamera(_direction); InputImageRotation rotation = rotationIntToImageRotation( description.sensorOrientation, ); _camera = CameraController(description, ResolutionPreset.low, enableAudio: false); await _camera!.initialize(); await Future.delayed(Duration(milliseconds: 500)); tempDir = await getApplicationDocumentsDirectory(); String _embPath = tempDir!.path + '/emb.json'; jsonFile = new File(_embPath); if (jsonFile!.existsSync()) data = json.decode(jsonFile!.readAsStringSync()); _camera!.startImageStream((CameraImage image) { if (_camera != null) { if (_isDetecting) return; _isDetecting = true; String res; dynamic finalResult = Multimap<String, Face>(); detect(image, _getDetectionMethod(), rotation).then( (dynamic result) async { if (result.length == 0) _faceFound = false; else _faceFound = true; Face _face; imglib.Image convertedImage = _convertCameraImage(image, _direction); for (_face in result) { double x, y, w, h; x = (_face.boundingBox.left - 10); y = (_face.boundingBox.top - 10); w = (_face.boundingBox.width + 10); h = (_face.boundingBox.height + 10); imglib.Image croppedImage = imglib.copyCrop( convertedImage, x.round(), y.round(), w.round(), h.round()); croppedImage = imglib.copyResizeCropSquare(croppedImage, 112); // int startTime = new DateTime.now().millisecondsSinceEpoch; res = _recog(croppedImage); // int endTime = new DateTime.now().millisecondsSinceEpoch; // print("Inference took ${endTime - startTime}ms"); finalResult.add(res, _face); } setState(() { _scanResults = finalResult; }); _isDetecting = false; }, ).catchError( (_) { print("error"); _isDetecting = false; }, ); } }); } HandleDetection _getDetectionMethod() { final faceDetector = GoogleMlKit.vision.faceDetector( FaceDetectorOptions( mode: FaceDetectorMode.accurate, ), ); return faceDetector.processImage; } Widget _buildResults() { const Text noResultsText = const Text(''); if (_scanResults == null || _camera == null || !_camera!.value.isInitialized) { return noResultsText; } CustomPainter painter; final Size imageSize = Size( _camera!.value.previewSize!.height, _camera!.value.previewSize!.width, ); painter = FaceDetectorPainter(imageSize, _scanResults); return CustomPaint( painter: painter, ); } Widget _buildImage() { if (_camera == null || !_camera!.value.isInitialized) { return Center( child: CircularProgressIndicator(), ); } return Container( constraints: const BoxConstraints.expand(), child: _camera == null ? const Center(child: null) : Stack( fit: StackFit.expand, children: <Widget>[ CameraPreview(_camera!), _buildResults(), ], ), ); } void _toggleCameraDirection() async { if (_direction == CameraLensDirection.back) { _direction = CameraLensDirection.front; } else { _direction = CameraLensDirection.back; } await _camera!.stopImageStream(); await _camera!.dispose(); setState(() { _camera = null; }); _initializeCamera(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: MyTheme.blue4, title: const Text('Face recognition'), actions: <Widget>[ widget.abc == true ? PopupMenuButton<Choice>( onSelected: (Choice result) { if (result == Choice.delete) _resetFile(); else _viewLabels(); }, itemBuilder: (BuildContext context) => <PopupMenuEntry<Choice>>[ const PopupMenuItem<Choice>( child: Text('View Saved Faces'), value: Choice.view, ), const PopupMenuItem<Choice>( child: Text('Remove all faces'), value: Choice.delete, ) ], ) : SizedBox(), ], ), body: _buildImage(), floatingActionButton: Column(mainAxisAlignment: MainAxisAlignment.end, children: [ widget.abc == true ? FloatingActionButton( backgroundColor: (_faceFound) ? MyTheme.blue4 : Colors.blueGrey, child: Icon(Icons.add), onPressed: () { if (_faceFound) _addLabel(); }, heroTag: null, ) : SizedBox(), SizedBox( height: 10, ), FloatingActionButton( onPressed: _toggleCameraDirection, backgroundColor: MyTheme.blue4, heroTag: null, child: _direction == CameraLensDirection.back ? const Icon(Icons.camera_front) : const Icon(Icons.camera_rear), ), ]), ); } imglib.Image _convertCameraImage( CameraImage image, CameraLensDirection _dir) { int width = image.width; int height = image.height; // imglib -> Image package from https://pub.dartlang.org/packages/image var img = imglib.Image(width, height); // Create Image buffer const int hexFF = 0xFF000000; final int uvyButtonStride = image.planes[1].bytesPerRow; final int uvPixelStride = image.planes[1].bytesPerPixel!; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { final int uvIndex = uvPixelStride * (x / 2).floor() + uvyButtonStride * (y / 2).floor(); final int index = y * width + x; final yp = image.planes[0].bytes[index]; final up = image.planes[1].bytes[uvIndex]; final vp = image.planes[2].bytes[uvIndex]; // Calculate pixel color int r = (yp + vp * 1436 / 1024 - 179).round().clamp(0, 255); int g = (yp - up * 46549 / 131072 + 44 - vp * 93604 / 131072 + 91) .round() .clamp(0, 255); int b = (yp + up * 1814 / 1024 - 227).round().clamp(0, 255); // color: 0x FF FF FF FF // A B G R img.data[index] = hexFF | (b << 16) | (g << 8) | r; } } var img1 = (_dir == CameraLensDirection.front) ? imglib.copyRotate(img, -90) : imglib.copyRotate(img, 90); return img1; } String _recog(imglib.Image img) { List input = imageToByteListFloat32(img, 112, 128, 128); input = input.reshape([1, 112, 112, 3]); List output = List.filled(1 * 192, null, growable: false).reshape([1, 192]); interpreter.run(input, output); output = output.reshape([192]); e1 = List.from(output); return compare(e1!).toUpperCase(); } String compare(List currEmb) { if (data.length == 0) return "No Face saved"; double minDist = 999; double currDist = 0.0; String predRes = "NOT RECOGNIZED"; for (String label in data.keys) { currDist = euclideanDistance(data[label], currEmb); if (currDist <= threshold && currDist < minDist) { minDist = currDist; predRes = label; } } print(minDist.toString() + " " + predRes); return predRes; } void _resetFile() { data = {}; jsonFile!.deleteSync(); } void _viewLabels() { setState(() { _camera = null; }); String name; var alert = new AlertDialog( title: new Text("Saved Faces"), content: new ListView.builder( padding: new EdgeInsets.all(2), itemCount: data.length, itemBuilder: (BuildContext context, int index) { name = data.keys.elementAt(index); return new Column( children: <Widget>[ new ListTile( title: new Text( name, style: new TextStyle( fontSize: 14, color: Colors.grey[400], ), ), ), new Padding( padding: EdgeInsets.all(2), ), new Divider(), ], ); }), actions: <Widget>[ new FlatButton( child: Text("OK"), onPressed: () { _initializeCamera(); Navigator.pop(context); }, ) ], ); showDialog( context: context, builder: (context) { return alert; }); } void _addLabel() { setState(() { _camera = null; }); print("Adding new face"); var alert = new AlertDialog( title: new Text("Add Face"), content: new Row( children: <Widget>[ new Expanded( child: new TextField( controller: _name, autofocus: true, decoration: new InputDecoration( labelText: "Name", icon: new Icon(Icons.face)), ), ) ], ), actions: <Widget>[ new FlatButton( child: Text("Save"), onPressed: () { _handle(_name.text.toUpperCase()); _name.clear(); Navigator.pop(context); }), new FlatButton( child: Text("Cancel"), onPressed: () { _initializeCamera(); Navigator.pop(context); }, ) ], ); showDialog( context: context, builder: (context) { return alert; }); } void _handle(String text) { data[text] = e1; jsonFile!.writeAsStringSync(json.encode(data)); _initializeCamera(); } }
0
mirrored_repositories/Handcuffed/lib
mirrored_repositories/Handcuffed/lib/pages/login.dart
import 'dart:convert'; import 'dart:io'; import 'package:Face_recognition/pages/widgets/header.dart'; import 'package:Face_recognition/pages/widgets/themes.dart'; import 'package:Face_recognition/utils/routes.dart'; import 'package:google_ml_kit/google_ml_kit.dart'; import 'package:path_provider/path_provider.dart'; import 'package:camera/camera.dart'; // import 'package:firebase_ml_vision/firebase_ml_vision.dart'; import 'package:flutter/material.dart'; class loginPage extends StatefulWidget { const loginPage({Key? key}) : super(key: key); @override State<loginPage> createState() => _loginPageState(); } class _loginPageState extends State<loginPage> { double headerheight = 250; bool changeButton = false; String entered_phone = ''; final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: SingleChildScrollView( child: Form( key: _formKey, child: Column(children: [ Container( height: headerheight, child: HeaderWidget( headerheight, true, "Welcome", )), SafeArea( child: Column(children: [ Text( "Login", style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold), ), SizedBox( height: 15.0, ), Padding( padding: EdgeInsets.symmetric(vertical: 16.0, horizontal: 32.0), child: Column(children: [ SizedBox( height: 20.0, ), Material( color: MyTheme.blue, borderRadius: BorderRadius.circular(changeButton ? 70 : 30), child: InkWell( onTap: () => Navigator.pushNamed( context, MyRoutes.login_userRoute), child: AnimatedContainer( duration: Duration(seconds: 1), width: changeButton ? 50 : 250, height: 50, alignment: Alignment.center, child: changeButton ? Icon( Icons.done, color: Colors.white, ) : Text( "AS USER", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18), ), ), ), ), SizedBox( height: 30.0, ), Material( color: MyTheme.blue, borderRadius: BorderRadius.circular(changeButton ? 70 : 30), child: InkWell( onTap: () => Navigator.pushNamed( context, MyRoutes.login_adminRoute), child: AnimatedContainer( duration: Duration(seconds: 1), width: changeButton ? 50 : 250, height: 50, alignment: Alignment.center, child: changeButton ? Icon( Icons.done, color: Colors.white, ) : Text( "AS ADMIN", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18), ), ), ), ), SizedBox( height: 40, ), Image.asset( "assets/images/handcuff.png", fit: BoxFit.cover, height: 160, ), ]), ), ]), ) ]), ), ), ); } }
0
mirrored_repositories/Handcuffed/lib
mirrored_repositories/Handcuffed/lib/pages/utils.dart
import 'dart:async'; import 'dart:math'; import 'dart:typed_data'; import 'dart:ui'; import 'package:camera/camera.dart'; // import 'package:firebase_ml_vision/firebase_ml_vision.dart'; import 'package:google_ml_kit/google_ml_kit.dart'; import 'package:image/image.dart' as imglib; typedef HandleDetection = Future<dynamic> Function(InputImage image); enum Choice { view, delete } Future<CameraDescription> getCamera(CameraLensDirection dir) async { return await availableCameras().then( (List<CameraDescription> cameras) => cameras.firstWhere( (CameraDescription camera) => camera.lensDirection == dir, ), ); } InputImageData buildMetaData( CameraImage image, InputImageRotation rotation, ) { return InputImageData( inputImageFormat: InputImageFormat.BGRA8888, size: Size(image.width.toDouble(), image.height.toDouble()), imageRotation: rotation, planeData: image.planes.map( (Plane plane) { return InputImagePlaneMetadata( bytesPerRow: plane.bytesPerRow, height: plane.height, width: plane.width, ); }, ).toList(), ); } Future<dynamic> detect( CameraImage image, HandleDetection handleDetection, InputImageRotation rotation, ) async { return handleDetection( InputImage.fromBytes( bytes: image.planes[0].bytes, inputImageData: buildMetaData(image, rotation), ), ); } InputImageRotation rotationIntToImageRotation(int rotation) { switch (rotation) { case 0: return InputImageRotation.Rotation_0deg; case 90: return InputImageRotation.Rotation_90deg; case 180: return InputImageRotation.Rotation_180deg; default: assert(rotation == 270); return InputImageRotation.Rotation_270deg; } } Float32List imageToByteListFloat32( imglib.Image image, int inputSize, double mean, double std) { var convertedBytes = Float32List(1 * inputSize * inputSize * 3); var buffer = Float32List.view(convertedBytes.buffer); int pixelIndex = 0; for (var i = 0; i < inputSize; i++) { for (var j = 0; j < inputSize; j++) { var pixel = image.getPixel(j, i); buffer[pixelIndex++] = (imglib.getRed(pixel) - mean) / std; buffer[pixelIndex++] = (imglib.getGreen(pixel) - mean) / std; buffer[pixelIndex++] = (imglib.getBlue(pixel) - mean) / std; } } return convertedBytes.buffer.asFloat32List(); } double euclideanDistance(List e1, List e2) { double sum = 0.0; for (int i = 0; i < e1.length; i++) { sum += pow((e1[i] - e2[i]), 2); } return sqrt(sum); }
0
mirrored_repositories/Handcuffed/lib
mirrored_repositories/Handcuffed/lib/pages/admin.dart
import 'package:Face_recognition/pages/widgets/themes.dart'; import 'package:Face_recognition/utils/routes.dart'; import 'package:flutter/material.dart'; import 'camera.dart'; class admin extends StatefulWidget { const admin({Key? key}) : super(key: key); @override State<admin> createState() => _adminState(); } class _adminState extends State<admin> { bool changeButton = false; @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton( backgroundColor: MyTheme.blue4, child: Padding( padding: const EdgeInsets.all(10.0), child: Text('log out'), ), onPressed: () => Navigator.pushNamed(context, MyRoutes.loginRoute)), backgroundColor: Colors.white, appBar: AppBar( title: Text('ADMIN'), leading: IconButton( onPressed: () {}, icon: Icon(Icons.person), iconSize: 26, ), iconTheme: IconThemeData(color: Colors.white), backgroundColor: MyTheme.blue4, elevation: 0, ), body: Column( children: [ Padding(padding: EdgeInsets.symmetric(horizontal: 200, vertical: 80)), SizedBox(height: 0.0), Container( height: 150.0, child: RaisedButton( onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => camera(true))), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(80.0)), padding: EdgeInsets.all(0.0), child: Ink( decoration: BoxDecoration( gradient: LinearGradient( colors: [Color(0xff374ABE), Color(0xff64B6FF)], begin: Alignment.centerLeft, end: Alignment.centerRight, ), borderRadius: BorderRadius.circular(30.0)), child: Container( constraints: BoxConstraints(maxWidth: 300.0, minHeight: 150.0), alignment: Alignment.center, child: Text( "Scan a Face", textAlign: TextAlign.center, style: TextStyle(color: Colors.white, fontSize: 24), ), ), ), ), ), SizedBox(height: 60.0), // Container( // height: 150.0, // child: RaisedButton( // onPressed: () {}, // shape: RoundedRectangleBorder( // borderRadius: BorderRadius.circular(80.0)), // padding: EdgeInsets.all(0.0), // child: Ink( // decoration: BoxDecoration( // gradient: LinearGradient( // colors: [Color(0xff374ABE), Color(0xff64B6FF)], // begin: Alignment.centerLeft, // end: Alignment.centerRight, // ), // borderRadius: BorderRadius.circular(30.0)), // child: Container( // constraints: // BoxConstraints(maxWidth: 300.0, minHeight: 150.0), // alignment: Alignment.center, // child: Text( // "Enter Criminal Details", // textAlign: TextAlign.center, // style: TextStyle(color: Colors.white, fontSize: 24), // ), // ), // ), // ), // ), ], ), ); } }
0
mirrored_repositories/Handcuffed/lib
mirrored_repositories/Handcuffed/lib/pages/user.dart
import 'dart:convert'; import 'dart:io'; import 'package:Face_recognition/pages/detector_painters.dart'; import 'package:Face_recognition/pages/widgets/themes.dart'; import 'package:Face_recognition/pages/utils.dart'; import 'package:Face_recognition/utils/routes.dart'; import 'package:google_ml_kit/google_ml_kit.dart'; import 'package:path_provider/path_provider.dart'; import 'package:camera/camera.dart'; // import 'package:firebase_ml_vision/firebase_ml_vision.dart'; import 'package:flutter/material.dart'; //import 'detector_painters.dart'; //import 'utils.dart'; import 'package:image/image.dart' as imglib; import 'package:tflite_flutter/tflite_flutter.dart' as tfl; import 'package:quiver/collection.dart'; import 'package:flutter/services.dart'; import 'camera.dart'; class user extends StatefulWidget { const user({Key? key}) : super(key: key); @override State<user> createState() => _userState(); } class _userState extends State<user> { @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton( backgroundColor: MyTheme.blue4, child: Padding( padding: const EdgeInsets.all(10.0), child: Text('log out'), ), onPressed: () => Navigator.pushNamed(context, MyRoutes.loginRoute)), backgroundColor: Colors.white, appBar: AppBar( title: Text('USER'), leading: IconButton( onPressed: () {}, icon: Icon(Icons.person), iconSize: 26, ), iconTheme: IconThemeData(color: Colors.white), backgroundColor: MyTheme.blue4, elevation: 0, ), body: Column(children: [ Padding( padding: EdgeInsets.symmetric(horizontal: 60, vertical: 80), child: Container( height: 150.0, child: RaisedButton( onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => camera(false))), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(80.0)), padding: EdgeInsets.all(0.0), child: Ink( decoration: BoxDecoration( gradient: LinearGradient( colors: [Color(0xff374ABE), Color(0xff64B6FF)], begin: Alignment.centerLeft, end: Alignment.centerRight, ), borderRadius: BorderRadius.circular(30.0)), child: Container( constraints: BoxConstraints(maxWidth: 300.0, minHeight: 150.0), alignment: Alignment.center, child: Text( "Scan a Face", textAlign: TextAlign.center, style: TextStyle(color: Colors.white, fontSize: 24), ), ), ), ), ), ), ]), ); } }
0
mirrored_repositories/Handcuffed/lib/pages
mirrored_repositories/Handcuffed/lib/pages/widgets/themes.dart
import 'package:flutter/material.dart'; class MyTheme { static Color blue = const Color(0xff327FF5); static Color blue2 = const Color(0xff32BCF5); static Color blue3 = const Color(0xff32C9F5); static Color blue4 = const Color(0xff374ABE); static Color grey = const Color(0xffBFBCBB); static Color light = const Color(0xffD4C7B3); }
0
mirrored_repositories/Handcuffed/lib/pages
mirrored_repositories/Handcuffed/lib/pages/widgets/header.dart
import 'package:flutter/material.dart'; class HeaderWidget extends StatefulWidget { final double _height; final bool _showIcon; final String _image; const HeaderWidget(this._height, this._showIcon, this._image, {Key? key}) : super(key: key); @override _HeaderWidgetState createState() => _HeaderWidgetState(_height, _showIcon, _image); } class _HeaderWidgetState extends State<HeaderWidget> { double _height; bool _showIcon; String _image; _HeaderWidgetState(this._height, this._showIcon, this._image); @override Widget build(BuildContext context) { double width = MediaQuery .of(context) .size .width; return Container( child: Stack( children: [ ClipPath( child: Container( decoration: new BoxDecoration( gradient: new LinearGradient( colors: [ Theme.of(context).primaryColor.withOpacity(0.4), Theme.of(context).accentColor.withOpacity(0.4), ], begin: const FractionalOffset(0.0, 0.0), end: const FractionalOffset(1.0, 0.0), stops: [0.0, 1.0], tileMode: TileMode.clamp ), ), ), clipper: new ShapeClipper( [ Offset(width / 5, _height), Offset(width / 10 * 5, _height - 60), Offset(width / 5 * 4, _height + 20), Offset(width, _height - 18) ] ), ), ClipPath( child: Container( decoration: new BoxDecoration( gradient: new LinearGradient( colors: [ Theme.of(context).primaryColor.withOpacity(0.4), Theme.of(context).accentColor.withOpacity(0.4), ], begin: const FractionalOffset(0.0, 0.0), end: const FractionalOffset(1.0, 0.0), stops: [0.0, 1.0], tileMode: TileMode.clamp ), ), ), clipper: new ShapeClipper( [ Offset(width / 3, _height + 20), Offset(width / 10 * 8, _height - 60), Offset(width / 5 * 4, _height - 60), Offset(width, _height - 20) ] ), ), ClipPath( child: Container( decoration: new BoxDecoration( gradient: new LinearGradient( colors: [ Theme.of(context).primaryColor, Theme.of(context).accentColor, ], begin: const FractionalOffset(0.0, 0.0), end: const FractionalOffset(1.0, 0.0), stops: [0.0, 1.0], tileMode: TileMode.clamp ), ), ), clipper: new ShapeClipper( [ Offset(width / 5, _height), Offset(width / 2, _height - 40), Offset(width / 5 * 4, _height - 80), Offset(width, _height - 20) ] ), ), Visibility( visible: _showIcon, child: Container( height: _height - 40, child: Center( child: Container( margin: EdgeInsets.all(20), padding: EdgeInsets.only( left: 5.0, top: 20.0, right: 5.0, bottom: 20.0, ), decoration: BoxDecoration( // borderRadius: BorderRadius.circular(20), // borderRadius: BorderRadius.only( // topLeft: Radius.circular(500), // topRight: Radius.circular(100), // bottomLeft: Radius.circular(60), // bottomRight: Radius.circular(60), // ), // border: Border.all(width: 5, color: Colors.white), ), child: Container( padding: EdgeInsets.only( left: 5.0, top: 40.0, right: 5.0, bottom: 0.0, ), child: Image.asset("assets/images/Assetbig.png", height: 300, width: 400, ) //( // _image, // style: TextStyle( color: Colors.white, // fontSize: 40.0, ), ), ), ), ) ], ), ); } } class ShapeClipper extends CustomClipper<Path> { List<Offset> _offsets = []; ShapeClipper(this._offsets); @override Path getClip(Size size) { var path = new Path(); path.lineTo(0.0, size.height-20); // path.quadraticBezierTo(size.width/5, size.height, size.width/2, size.height-40); // path.quadraticBezierTo(size.width/5*4, size.height-80, size.width, size.height-20); path.quadraticBezierTo(_offsets[0].dx, _offsets[0].dy, _offsets[1].dx,_offsets[1].dy); path.quadraticBezierTo(_offsets[2].dx, _offsets[2].dy, _offsets[3].dx,_offsets[3].dy); // path.lineTo(size.width, size.height-20); path.lineTo(size.width, 0.0); path.close(); return path; } @override bool shouldReclip(CustomClipper<Path> oldClipper) => false; }
0
mirrored_repositories/Handcuffed/lib
mirrored_repositories/Handcuffed/lib/utils/routes.dart
class MyRoutes { static String loginRoute = "/login"; static String homeRoute = "/home"; static String userRoute = "/user"; static String adminRoute = "/admin"; static String login_userRoute = "/login_user"; static String login_adminRoute = "/login_admin"; static String otp_userRoute = "/otp"; static String cameraRoute = "/camera"; }
0
mirrored_repositories/chat-app-web3
mirrored_repositories/chat-app-web3/lib/chat_detail.dart
import 'package:flutter/material.dart'; import 'package:chat_app_web3/chat_models.dart'; class ChatDetailPage extends StatefulWidget { final String user; const ChatDetailPage({Key? key, required this.user}) : super(key: key); @override ChatDetailPageState createState() => ChatDetailPageState(); } class ChatDetailPageState extends State<ChatDetailPage> { @override Widget build(BuildContext context) { List<ChatMessage> messages = [ ChatMessage(messageContent: "Hello, Will", messageType: "receiver"), ChatMessage( messageContent: "How have you been?", messageType: "receiver"), ChatMessage( messageContent: "Hey Kriss, I am doing fine dude. wbu?", messageType: "sender"), ChatMessage(messageContent: "ehhhh, doing OK.", messageType: "receiver"), ChatMessage( messageContent: "Is there any thing wrong?", messageType: "sender"), ]; return Scaffold( appBar: AppBar( elevation: 0, automaticallyImplyLeading: false, backgroundColor: Colors.white, flexibleSpace: SafeArea( child: Container( padding: const EdgeInsets.only(right: 16), child: Row( children: <Widget>[ IconButton( onPressed: () { Navigator.pop(context); }, icon: const Icon( Icons.arrow_back, color: Colors.black, ), ), const SizedBox( width: 2, ), const CircleAvatar( backgroundImage: NetworkImage( "<https://randomuser.me/api/portraits/men/5.jpg>"), maxRadius: 20, ), const SizedBox( width: 12, ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( widget.user, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.w600), ), const SizedBox( height: 6, ), Text( "Online", style: TextStyle( color: Colors.grey.shade600, fontSize: 13), ), ], ), ), const Icon( Icons.settings, color: Colors.black54, ), ], ), ), ), ), body: Stack( children: <Widget>[ ListView.builder( itemCount: messages.length, shrinkWrap: true, padding: const EdgeInsets.only(top: 10, bottom: 10), physics: const NeverScrollableScrollPhysics(), itemBuilder: (context, index) { return Container( padding: const EdgeInsets.only( left: 14, right: 14, top: 10, bottom: 10), child: Align( alignment: (messages[index].messageType == "receiver" ? Alignment.topLeft : Alignment.topRight), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: (messages[index].messageType == "receiver" ? Colors.grey.shade200 : Colors.blue[200]), ), padding: const EdgeInsets.all(16), child: Text( messages[index].messageContent, style: const TextStyle(fontSize: 15), ), ), ), ); }, ), Align( alignment: Alignment.bottomLeft, child: Container( padding: const EdgeInsets.only(left: 10, bottom: 10, top: 10), height: 60, width: double.infinity, color: Colors.white, child: Row( children: <Widget>[ GestureDetector( onTap: () {}, child: Container( height: 30, width: 30, decoration: BoxDecoration( color: Colors.lightBlue, borderRadius: BorderRadius.circular(30), ), child: const Icon( Icons.add, color: Colors.white, size: 20, ), ), ), const SizedBox( width: 15, ), const Expanded( child: TextField( decoration: InputDecoration( hintText: "Write message...", hintStyle: TextStyle(color: Colors.black54), border: InputBorder.none), ), ), const SizedBox( width: 15, ), FloatingActionButton( onPressed: () {}, backgroundColor: Colors.blue, elevation: 0, child: const Icon( Icons.send, color: Colors.white, size: 18, ), ), ], ), ), ), ], ), ); } }
0
mirrored_repositories/chat-app-web3
mirrored_repositories/chat-app-web3/lib/chat_models.dart
// import 'package:flutter/cupertino.dart'; class ChatUser { String name; String messageText; String imageURL; String time; ChatUser( {required this.name, required this.messageText, required this.imageURL, required this.time}); } class ChatMessage { String messageContent; String messageType; ChatMessage({required this.messageContent, required this.messageType}); }
0
mirrored_repositories/chat-app-web3
mirrored_repositories/chat-app-web3/lib/metamask_provider.dart
import 'package:flutter/material.dart'; import 'package:flutter_web3/flutter_web3.dart'; class MetamaskProvider extends ChangeNotifier { static const operatingChain = 5; String currentAddress = ""; int currentChain = -1; bool get isEnabled => ethereum != null; bool get isInOperatingChain => currentChain == operatingChain; bool get isConnected => isEnabled && currentAddress.isNotEmpty; Future<void> connect() async { if (isEnabled) { final access = await ethereum!.requestAccount(); if(access.isNotEmpty) currentAddress = access.first; currentChain = await ethereum!.getChainId(); notifyListeners(); } } reset() { currentAddress = ""; currentChain = -1; notifyListeners(); } start() { if (isEnabled) { ethereum!.onAccountsChanged((accounts) { reset(); }); ethereum!.onChainChanged((accounts) { reset(); }); } } }
0
mirrored_repositories/chat-app-web3
mirrored_repositories/chat-app-web3/lib/conversation_list.dart
import 'package:flutter/material.dart'; import 'package:chat_app_web3/chat_detail.dart'; class ConversationList extends StatefulWidget { final String name; final String messageText; final String imageUrl; final String time; final bool isMessageRead; const ConversationList( {super.key, required this.name, required this.messageText, required this.imageUrl, required this.time, required this.isMessageRead}); @override ConversationListState createState() => ConversationListState(); } class ConversationListState extends State<ConversationList> { @override Widget build(BuildContext context) { return GestureDetector( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return ChatDetailPage(user: widget.name); })); }, child: Container( padding: const EdgeInsets.only(left: 16, right: 16, top: 10, bottom: 10), child: Row( children: <Widget>[ Expanded( child: Row( children: <Widget>[ CircleAvatar( backgroundImage: NetworkImage(widget.imageUrl), maxRadius: 30, ), const SizedBox( width: 16, ), Expanded( child: Container( color: Colors.transparent, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( widget.name, style: const TextStyle(fontSize: 16), ), const SizedBox( height: 6, ), Text( widget.messageText, style: TextStyle( fontSize: 13, color: Colors.grey.shade600, fontWeight: widget.isMessageRead ? FontWeight.bold : FontWeight.normal), ), ], ), ), ), ], ), ), Text( widget.time, style: TextStyle( fontSize: 12, fontWeight: widget.isMessageRead ? FontWeight.bold : FontWeight.normal), ), ], ), ), ); } }
0
mirrored_repositories/chat-app-web3
mirrored_repositories/chat-app-web3/lib/chat_page.dart
import "package:flutter/material.dart"; class ChatPage extends StatefulWidget { const ChatPage({Key? key}) : super(key: key); @override ChatPageState createState() => ChatPageState(); } class ChatPageState extends State<ChatPage> { @override Widget build(BuildContext context) { return const Scaffold( body: SingleChildScrollView( child: Center(child: Text("Chat")), ), ); } }
0
mirrored_repositories/chat-app-web3
mirrored_repositories/chat-app-web3/lib/main.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'metamask_provider.dart'; import 'package:google_fonts/google_fonts.dart'; import 'mock_data.dart'; import 'conversation_list.dart'; void main() { runApp( const MaterialApp( home: MyApp(), title: "Chat App", ), ); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return Scaffold( backgroundColor: const Color.fromARGB(255, 12, 50, 100), body: ChangeNotifierProvider( create: (context) => MetamaskProvider()..start(), builder: (context, child) { return Center(child: Consumer<MetamaskProvider>( builder: (context, provider, child) { late final String message; if (provider.isConnected && provider.isInOperatingChain) { return Scaffold( body: SingleChildScrollView( physics: const BouncingScrollPhysics(), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SafeArea( child: Padding( padding: const EdgeInsets.only( left: 16, right: 16, top: 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ const Text( 'Conversations', style: TextStyle( fontSize: 32, fontWeight: FontWeight.bold), ), Container( padding: const EdgeInsets.only( left: 8, right: 8, top: 2, bottom: 2), height: 30, decoration: BoxDecoration( borderRadius: BorderRadius.circular(30), color: Colors.pink[50], ), child: const Row( children: <Widget>[ Icon( Icons.add, color: Colors.pink, size: 20, ), SizedBox( width: 2, ), Text( "Add New", style: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, ), ), ], ), ), ], ), ), ), Padding( padding: const EdgeInsets.only( top: 16, left: 16, right: 16), child: TextField( decoration: InputDecoration( hintText: "Search...", hintStyle: TextStyle(color: Colors.grey.shade600), prefixIcon: Icon( Icons.search, color: Colors.grey.shade600, size: 20, ), filled: true, fillColor: Colors.grey.shade100, contentPadding: const EdgeInsets.all(8), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: BorderSide(color: Colors.grey.shade100)), ), ), ), ListView.builder( itemCount: chatUsers.length, shrinkWrap: true, padding: const EdgeInsets.only(top: 16), physics: const NeverScrollableScrollPhysics(), itemBuilder: (context, index) { return ConversationList( name: chatUsers[index].name, messageText: chatUsers[index].messageText, imageUrl: chatUsers[index].imageURL, time: chatUsers[index].time, isMessageRead: (index == 0 || index == 3) ? true : false, ); }, ), ], ), ), ); } else if (provider.isConnected && !provider.isInOperatingChain) { message = 'Wrong chain. Please connect to ${MetamaskProvider.operatingChain}'; } else if (provider.isEnabled) { return Column( mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.all(15), child: Text( "Welcome to Chat App!", textAlign: TextAlign.center, style: GoogleFonts.splineSansMono( fontSize: 30, color: Colors.orange), ), ), MaterialButton( onPressed: () => context.read<MetamaskProvider>().connect(), color: Colors.indigo, padding: const EdgeInsets.all(0), child: Row(mainAxisSize: MainAxisSize.min, children: [ Image.network( 'https://images.unsplash.com/photo-1637597384338-61f51fa5cb07?auto=format&fit=crop&q=80&w=2069&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D', width: 300, ) ]), ) ], ); } else { message = 'Please use a Web3 supported browser.'; } return Text( message, textAlign: TextAlign.center, textDirection: TextDirection.ltr, style: const TextStyle(color: Colors.white), ); }, )); }, ), ); } }
0
mirrored_repositories/chat-app-web3
mirrored_repositories/chat-app-web3/lib/mock_data.dart
import 'package:chat_app_web3/chat_models.dart'; List<ChatUser> chatUsers = [ ChatUser( name: "Idriz Pelaj", messageText: "Awesome Setup", imageURL: "images/userImage1.jpeg", time: "Now"), ChatUser( name: "Jon Lumi", messageText: "That's Great", imageURL: "images/userImage2.jpeg", time: "Yesterday"), ChatUser( name: "Blert Shabani", messageText: "Hey where are you?", imageURL: "images/userImage3.jpeg", time: "31 Mar"), ChatUser( name: "Getoar Rexhepi", messageText: "Busy! Call me in 20 mins", imageURL: "images/userImage4.jpeg", time: "28 Mar"), ChatUser( name: "Altin Loshi", messageText: "Thankyou, It's awesome", imageURL: "images/userImage5.jpeg", time: "23 Mar"), ChatUser( name: "Joan Collaku", messageText: "will update you in evening", imageURL: "images/userImage6.jpeg", time: "17 Mar"), ChatUser( name: "Lis Fazliu", messageText: "Can you please share the file?", imageURL: "images/userImage7.jpeg", time: "24 Feb"), ChatUser( name: "Donat Balaj", messageText: "How are you?", imageURL: "images/userImage8.jpeg", time: "18 Feb"), ]; List<ChatMessage> messages = [ ChatMessage(messageContent: "Hello, Will", messageType: "receiver"), ChatMessage(messageContent: "How have you been?", messageType: "receiver"), ChatMessage( messageContent: "Hey Kriss, I am doing fine dude. wbu?", messageType: "sender"), ChatMessage(messageContent: "ehhhh, doing OK.", messageType: "receiver"), ChatMessage( messageContent: "Is there any thing wrong?", messageType: "sender"), ];
0
mirrored_repositories/chat-app-web3
mirrored_repositories/chat-app-web3/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:chat_app_web3/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/flutter_facebook_responsive_ui
mirrored_repositories/flutter_facebook_responsive_ui/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter_facebook_responsive_ui/config/palette.dart'; import 'package:flutter_facebook_responsive_ui/screens/screens.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Facebook UI', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, scaffoldBackgroundColor: Palette.scaffold, ), home: const NavScreen(), ); } }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/widgets/post_container.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_facebook_responsive_ui/config/palette.dart'; import 'package:flutter_facebook_responsive_ui/models/models.dart'; import 'package:flutter_facebook_responsive_ui/widgets/widgets.dart'; import 'package:material_design_icons_flutter/material_design_icons_flutter.dart'; class PostContainer extends StatelessWidget { final Post post; const PostContainer({ Key? key, required this.post, }) : super(key: key); @override Widget build(BuildContext context) { final bool isDesktop = Responsive.isDesktop(context); return Card( margin: EdgeInsets.symmetric( vertical: 5.0, horizontal: isDesktop ? 5.0 : 0.0, ), elevation: isDesktop ? 1.0 : 0.0, shape: isDesktop ? RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)) : null, child: Container( padding: const EdgeInsets.symmetric(vertical: 8.0), color: Colors.white, child: Column( children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: 12.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ _PostHeader(post: post), const SizedBox(height: 4.0), Text(post.caption), post.imageUrl != null ? const SizedBox.shrink() : const SizedBox(height: 6.0), ], ), ), post.imageUrl != null ? Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: CachedNetworkImage(imageUrl: post.imageUrl!), ) : const SizedBox.shrink(), Padding( padding: const EdgeInsets.symmetric(horizontal: 12.0), child: _PostStats(post: post), ), ], ), ), ); } } class _PostHeader extends StatelessWidget { final Post post; const _PostHeader({ Key? key, required this.post, }) : super(key: key); @override Widget build(BuildContext context) { return Row( children: [ ProfileAvatar(imageUrl: post.user.imageUrl), const SizedBox(width: 8.0), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( post.user.name, style: const TextStyle( fontWeight: FontWeight.w600, ), ), Row( children: [ Text( '${post.timeAgo} • ', style: TextStyle( color: Colors.grey[600], fontSize: 12.0, ), ), Icon( Icons.public, color: Colors.grey[600], size: 12.0, ) ], ), ], ), ), IconButton( icon: const Icon(Icons.more_horiz), onPressed: () => print('More'), ), ], ); } } class _PostStats extends StatelessWidget { final Post post; const _PostStats({ Key? key, required this.post, }) : super(key: key); @override Widget build(BuildContext context) { return Column( children: [ Row( children: [ Container( padding: const EdgeInsets.all(4.0), decoration: const BoxDecoration( color: Palette.facebookBlue, shape: BoxShape.circle, ), child: const Icon( Icons.thumb_up, size: 10.0, color: Colors.white, ), ), const SizedBox(width: 4.0), Expanded( child: Text( '${post.likes}', style: TextStyle( color: Colors.grey[600], ), ), ), Text( '${post.comments} Comments', style: TextStyle( color: Colors.grey[600], ), ), const SizedBox(width: 8.0), Text( '${post.shares} Shares', style: TextStyle( color: Colors.grey[600], ), ) ], ), const Divider(), Row( children: [ _PostButton( icon: Icon( MdiIcons.thumbUpOutline, color: Colors.grey[600], size: 20.0, ), label: 'Like', onTap: () => print('Like'), ), _PostButton( icon: Icon( MdiIcons.commentOutline, color: Colors.grey[600], size: 20.0, ), label: 'Comment', onTap: () => print('Comment'), ), _PostButton( icon: Icon( MdiIcons.shareOutline, color: Colors.grey[600], size: 25.0, ), label: 'Share', onTap: () => print('Share'), ) ], ), ], ); } } class _PostButton extends StatelessWidget { final Icon icon; final String label; final Function() onTap; const _PostButton({ Key? key, required this.icon, required this.label, required this.onTap, }) : super(key: key); @override Widget build(BuildContext context) { return Expanded( child: Material( color: Colors.white, child: InkWell( onTap: onTap, child: Container( padding: const EdgeInsets.symmetric(horizontal: 12.0), height: 25.0, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ icon, const SizedBox(width: 4.0), Text(label), ], ), ), ), ), ); } }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/widgets/responsive.dart
import 'package:flutter/material.dart'; class Responsive extends StatelessWidget { final Widget mobile; final Widget? tablet; final Widget desktop; const Responsive({ Key? key, required this.mobile, this.tablet, required this.desktop, }) : super(key: key); static bool isMobile(BuildContext context) => MediaQuery.of(context).size.width < 800; static bool isTablet(BuildContext context) => MediaQuery.of(context).size.width >= 800 && MediaQuery.of(context).size.width < 1200; static bool isDesktop(BuildContext context) => MediaQuery.of(context).size.width >= 1200; @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, constraints) { if (constraints.maxWidth >= 1200) { return desktop; } else if (constraints.maxWidth >= 800) { return tablet ?? mobile; } else { return mobile; } }, ); } }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/widgets/stories.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_facebook_responsive_ui/config/palette.dart'; import 'package:flutter_facebook_responsive_ui/models/models.dart'; import 'package:flutter_facebook_responsive_ui/widgets/widgets.dart'; class Stories extends StatelessWidget { final User currentUser; final List<Story> stories; const Stories({ Key? key, required this.currentUser, required this.stories, }) : super(key: key); @override Widget build(BuildContext context) { return Container( height: 200.0, color: Responsive.isDesktop(context) ? Colors.transparent : Colors.white, child: ListView.builder( padding: const EdgeInsets.symmetric( vertical: 10.0, horizontal: 8.0, ), scrollDirection: Axis.horizontal, itemCount: 1 + stories.length, itemBuilder: (BuildContext context, int index) { if (index == 0) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 4.0), child: _StoryCard( isAddStory: true, currentUser: currentUser, ), ); } final Story story = stories[index - 1]; return Padding( padding: const EdgeInsets.symmetric(horizontal: 4.0), child: _StoryCard(story: story), ); }, ), ); } } class _StoryCard extends StatelessWidget { final bool isAddStory; final User? currentUser; final Story? story; const _StoryCard({ Key? key, this.isAddStory = false, this.currentUser, this.story, }) : super(key: key); @override Widget build(BuildContext context) { return Stack( children: [ ClipRRect( borderRadius: BorderRadius.circular(12.0), child: CachedNetworkImage( imageUrl: isAddStory ? currentUser!.imageUrl : story!.imageUrl, height: double.infinity, width: 110.0, fit: BoxFit.cover, ), ), Container( height: double.infinity, width: 110.0, decoration: BoxDecoration( gradient: Palette.storyGradient, borderRadius: BorderRadius.circular(12.0), boxShadow: Responsive.isDesktop(context) ? const [ BoxShadow( color: Colors.black26, offset: Offset(0, 2), blurRadius: 4.0, ), ] : null, ), ), Positioned( top: 8.0, left: 8.0, child: isAddStory ? Container( height: 40.0, width: 40.0, decoration: const BoxDecoration( color: Colors.white, shape: BoxShape.circle, ), child: IconButton( padding: EdgeInsets.zero, icon: const Icon(Icons.add), iconSize: 30.0, color: Palette.facebookBlue, onPressed: () => print('Add to Story'), ), ) : ProfileAvatar( imageUrl: story!.user.imageUrl, hasBorder: !story!.isViewed, ), ), Positioned( bottom: 8.0, left: 8.0, right: 8.0, child: Text( isAddStory ? 'Add to Story' : story!.user.name, style: const TextStyle( color: Colors.white, fontWeight: FontWeight.bold, ), maxLines: 2, overflow: TextOverflow.ellipsis, ), ), ], ); } }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/widgets/custom_tab_bar.dart
import 'package:flutter/material.dart'; import 'package:flutter_facebook_responsive_ui/config/palette.dart'; class CustomTabBar extends StatelessWidget { final List<IconData> icons; final int selectedIndex; final Function(int) onTap; final bool isBottomIndicator; const CustomTabBar({ Key? key, required this.icons, required this.selectedIndex, required this.onTap, this.isBottomIndicator = false, }) : super(key: key); @override Widget build(BuildContext context) { return TabBar( indicatorPadding: EdgeInsets.zero, indicator: BoxDecoration( border: isBottomIndicator ? const Border( bottom: BorderSide( color: Palette.facebookBlue, width: 3.0, ), ) : const Border( top: BorderSide( color: Palette.facebookBlue, width: 3.0, ), ), ), tabs: icons .asMap() .map((i, e) => MapEntry( i, Tab( icon: Icon( e, color: i == selectedIndex ? Palette.facebookBlue : Colors.black45, size: 30.0, ), ), )) .values .toList(), onTap: onTap, ); } }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/widgets/circle_button.dart
import 'package:flutter/material.dart'; class CircleButton extends StatelessWidget { final IconData icon; final double iconSize; final Function() onPressed; const CircleButton({ Key? key, required this.icon, required this.iconSize, required this.onPressed, }) : super(key: key); @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.all(6.0), decoration: BoxDecoration( color: Colors.grey[200], shape: BoxShape.circle, ), child: IconButton( icon: Icon(icon), iconSize: iconSize, color: Colors.black, onPressed: onPressed, ), ); } }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/widgets/create_post_container.dart
import 'package:flutter/material.dart'; import 'package:flutter_facebook_responsive_ui/models/models.dart'; import 'package:flutter_facebook_responsive_ui/widgets/widgets.dart'; class CreatePostContainer extends StatelessWidget { final User currentUser; const CreatePostContainer({ Key? key, required this.currentUser, }) : super(key: key); @override Widget build(BuildContext context) { final bool isDesktop = Responsive.isDesktop(context); return Card( margin: EdgeInsets.symmetric(horizontal: isDesktop ? 5.0 : 0.0), elevation: isDesktop ? 1.0 : 0.0, shape: isDesktop ? RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)) : null, child: Container( padding: const EdgeInsets.fromLTRB(12.0, 8.0, 12.0, 0.0), color: Colors.white, child: Column( children: [ Row( children: [ ProfileAvatar(imageUrl: currentUser.imageUrl), const SizedBox(width: 8.0), const Expanded( child: TextField( decoration: InputDecoration.collapsed( hintText: 'What\'s on your mind?', ), ), ) ], ), const Divider(height: 10.0, thickness: 0.5), SizedBox( height: 40.0, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ TextButton.icon( onPressed: () => print('Live'), icon: const Icon( Icons.videocam, color: Colors.red, ), label: const Text('Live'), ), const VerticalDivider(width: 8.0), TextButton.icon( onPressed: () => print('Photo'), icon: const Icon( Icons.photo_library, color: Colors.green, ), label: const Text('Photo'), ), const VerticalDivider(width: 8.0), TextButton.icon( onPressed: () => print('Room'), icon: const Icon( Icons.video_call, color: Colors.purpleAccent, ), label: const Text('Room'), ), ], ), ), ], ), ), ); } }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/widgets/widgets.dart
export 'circle_button.dart'; export 'create_post_container.dart'; export 'rooms.dart'; export 'profile_avatar.dart'; export 'stories.dart'; export 'post_container.dart'; export 'custom_tab_bar.dart'; export 'responsive.dart'; export 'custom_app_bar.dart'; export 'user_card.dart'; export 'contacts_list.dart'; export 'more_options_list.dart';
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/widgets/contacts_list.dart
import 'package:flutter/material.dart'; import 'package:flutter_facebook_responsive_ui/models/models.dart'; import 'package:flutter_facebook_responsive_ui/widgets/widgets.dart'; class ContactsList extends StatefulWidget { final List<User> users; const ContactsList({ Key? key, required this.users, }) : super(key: key); @override State<ContactsList> createState() => _ContactsListState(); } class _ContactsListState extends State<ContactsList> { final ScrollController scrollController = ScrollController(); @override void dispose() { scrollController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Container( constraints: const BoxConstraints(maxWidth: 280.0), child: Column( children: [ Row( children: [ Expanded( child: Text( 'Contacts', style: TextStyle( color: Colors.grey[600], fontSize: 18.0, fontWeight: FontWeight.w500, ), ), ), Icon( Icons.search, color: Colors.grey[600], ), const SizedBox(width: 8.0), Icon( Icons.more_horiz, color: Colors.grey[600], ), ], ), Expanded( child: ListView.builder( padding: const EdgeInsets.symmetric(vertical: 10.0), itemCount: widget.users.length, controller: scrollController, itemBuilder: (BuildContext context, int index) { final User user = widget.users[index]; return Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: UserCard(user: user), ); }, ), ), ], ), ); } }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/widgets/profile_avatar.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_facebook_responsive_ui/config/palette.dart'; class ProfileAvatar extends StatelessWidget { final String imageUrl; final bool isActive; final bool hasBorder; const ProfileAvatar({ Key? key, required this.imageUrl, this.isActive = false, this.hasBorder = false, }) : super(key: key); @override Widget build(BuildContext context) { return Stack( children: [ CircleAvatar( radius: 20.0, backgroundColor: Palette.facebookBlue, child: CircleAvatar( radius: hasBorder ? 17.0 : 20.0, backgroundColor: Colors.grey[200], backgroundImage: CachedNetworkImageProvider(imageUrl), ), ), isActive ? Positioned( bottom: 0.0, right: 0.0, child: Container( height: 15.0, width: 15.0, decoration: BoxDecoration( color: Palette.online, shape: BoxShape.circle, border: Border.all( width: 2.0, color: Colors.white, ), ), ), ) : const SizedBox.shrink(), ], ); } }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/widgets/more_options_list.dart
import 'package:flutter/material.dart'; import 'package:flutter_facebook_responsive_ui/config/palette.dart'; import 'package:flutter_facebook_responsive_ui/models/models.dart'; import 'package:flutter_facebook_responsive_ui/widgets/widgets.dart'; import 'package:material_design_icons_flutter/material_design_icons_flutter.dart'; class MoreOptionsList extends StatelessWidget { final List<List> _moreOptionsList = const [ [MdiIcons.shieldAccount, Colors.deepPurple, 'COVID-19 Info Center'], [MdiIcons.accountMultiple, Colors.cyan, 'Friends'], [MdiIcons.facebookMessenger, Palette.facebookBlue, 'Messenger'], [MdiIcons.flag, Colors.orange, 'Pages'], [MdiIcons.storefront, Palette.facebookBlue, 'Marketplace'], [Icons.ondemand_video, Palette.facebookBlue, 'Watch'], [MdiIcons.calendarStar, Colors.red, 'Events'], ]; final User currentUser; const MoreOptionsList({ Key? key, required this.currentUser, }) : super(key: key); @override Widget build(BuildContext context) { return Container( constraints: const BoxConstraints(maxWidth: 280.0), child: ListView.builder( itemCount: 1 + _moreOptionsList.length, itemBuilder: (BuildContext context, int index) { if (index == 0) { return Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: UserCard(user: currentUser), ); } final List option = _moreOptionsList[index - 1]; return Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: _Option( icon: option[0], color: option[1], label: option[2], ), ); }, ), ); } } class _Option extends StatelessWidget { final IconData icon; final Color color; final String label; const _Option({ Key? key, required this.icon, required this.color, required this.label, }) : super(key: key); @override Widget build(BuildContext context) { return InkWell( onTap: () => print(label), child: Row( children: [ Icon(icon, size: 38.0, color: color), const SizedBox(width: 6.0), Flexible( child: Text( label, style: const TextStyle(fontSize: 16.0), overflow: TextOverflow.ellipsis, ), ), ], ), ); } }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/widgets/custom_app_bar.dart
import 'package:flutter/material.dart'; import 'package:flutter_facebook_responsive_ui/config/palette.dart'; import 'package:flutter_facebook_responsive_ui/models/models.dart'; import 'package:flutter_facebook_responsive_ui/widgets/widgets.dart'; import 'package:material_design_icons_flutter/material_design_icons_flutter.dart'; class CustomAppBar extends StatelessWidget { final User currentUser; final List<IconData> icons; final int selectedIndex; final Function(int) onTap; const CustomAppBar({ Key? key, required this.currentUser, required this.icons, required this.selectedIndex, required this.onTap, }) : super(key: key); @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.symmetric(horizontal: 20.0), height: 65.0, decoration: const BoxDecoration( color: Colors.white, boxShadow: [ BoxShadow( color: Colors.black12, offset: Offset(0, 2), blurRadius: 4.0, ), ], ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Expanded( child: Text( 'facebook', style: TextStyle( color: Palette.facebookBlue, fontSize: 32.0, fontWeight: FontWeight.bold, letterSpacing: -1.2, ), ), ), SizedBox( height: double.infinity, width: 600.0, child: CustomTabBar( icons: icons, selectedIndex: selectedIndex, onTap: onTap, isBottomIndicator: true, ), ), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ UserCard(user: currentUser), const SizedBox(width: 12.0), CircleButton( icon: Icons.search, iconSize: 30.0, onPressed: () => print('Search'), ), CircleButton( icon: MdiIcons.facebookMessenger, iconSize: 30.0, onPressed: () => print('Messenger'), ), ], ), ), ], ), ); } }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/widgets/rooms.dart
import 'package:flutter/material.dart'; import 'package:flutter_facebook_responsive_ui/config/palette.dart'; import 'package:flutter_facebook_responsive_ui/models/models.dart'; import 'package:flutter_facebook_responsive_ui/widgets/widgets.dart'; class Rooms extends StatelessWidget { final List<User> onlineUsers; const Rooms({ Key? key, required this.onlineUsers, }) : super(key: key); @override Widget build(BuildContext context) { final bool isDesktop = Responsive.isDesktop(context); return Card( margin: EdgeInsets.symmetric(horizontal: isDesktop ? 5.0 : 0.0), elevation: isDesktop ? 1.0 : 0.0, shape: isDesktop ? RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)) : null, child: Container( height: 60.0, color: Colors.white, child: ListView.builder( padding: const EdgeInsets.symmetric( vertical: 10.0, horizontal: 4.0, ), scrollDirection: Axis.horizontal, itemCount: 1 + onlineUsers.length, itemBuilder: (BuildContext context, int index) { if (index == 0) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: _CreateRoomButton(), ); } final User user = onlineUsers[index - 1]; return Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: ProfileAvatar( imageUrl: user.imageUrl, isActive: true, ), ); }, ), ), ); } } class _CreateRoomButton extends StatelessWidget { @override Widget build(BuildContext context) { final ButtonStyle outlineButtonStyle = OutlinedButton.styleFrom( side: BorderSide( color: Colors.blueAccent[100]!, width: 3, ), backgroundColor: Colors.white, textStyle: const TextStyle(color: Palette.facebookBlue), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(30)), ), ); return TextButton( onPressed: () => print('Create Room'), style: outlineButtonStyle, child: Row( children: const [ // ShaderMask( // shaderCallback: (rect) => // Palette.createRoomGradient.createShader(rect), // child: Icon( // Icons.video_call, // size: 35.0, // color: Colors.white, // ), // ), Icon( Icons.video_call, size: 35.0, color: Colors.purple, ), SizedBox(width: 4.0), Text('Create\nRoom'), ], ), ); } }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/widgets/user_card.dart
import 'package:flutter/material.dart'; import 'package:flutter_facebook_responsive_ui/models/models.dart'; import 'package:flutter_facebook_responsive_ui/widgets/widgets.dart'; class UserCard extends StatelessWidget { final User user; const UserCard({ Key? key, required this.user, }) : super(key: key); @override Widget build(BuildContext context) { return InkWell( onTap: () {}, child: Row( mainAxisSize: MainAxisSize.min, children: [ ProfileAvatar(imageUrl: user.imageUrl), const SizedBox(width: 6.0), Flexible( child: Text( user.name, style: const TextStyle(fontSize: 16.0), overflow: TextOverflow.ellipsis, ), ), ], ), ); } }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/models/post_model.dart
import 'package:flutter_facebook_responsive_ui/models/models.dart'; class Post { final User user; final String caption; final String timeAgo; final String? imageUrl; final int likes; final int comments; final int shares; const Post({ required this.user, required this.caption, required this.timeAgo, required this.imageUrl, required this.likes, required this.comments, required this.shares, }); }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/models/story_model.dart
import 'package:flutter_facebook_responsive_ui/models/models.dart'; class Story { final User user; final String imageUrl; final bool isViewed; const Story({ required this.user, required this.imageUrl, this.isViewed = false, }); }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/models/models.dart
export 'user_model.dart'; export 'story_model.dart'; export 'post_model.dart';
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/models/user_model.dart
class User { final String name; final String imageUrl; const User({ required this.name, required this.imageUrl, }); }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/config/palette.dart
import 'package:flutter/material.dart'; class Palette { static const Color scaffold = Color(0xFFF0F2F5); static const Color facebookBlue = Color(0xFF1777F2); static const LinearGradient createRoomGradient = LinearGradient( colors: [Color(0xFF496AE1), Color(0xFFCE48B1)], ); static const Color online = Color(0xFF4BCB1F); static const LinearGradient storyGradient = LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [Colors.transparent, Colors.black26], ); }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/data/data.dart
import 'package:flutter_facebook_responsive_ui/models/models.dart'; const User currentUser = User( name: 'Luan Batista', imageUrl: 'https://avatars.githubusercontent.com/u/56078396?v=4', ); const List<User> onlineUsers = [ User( name: 'David Brooks', imageUrl: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80', ), User( name: 'Jane Doe', imageUrl: 'https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80', ), User( name: 'Matthew Hinkle', imageUrl: 'https://images.unsplash.com/photo-1492562080023-ab3db95bfbce?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1331&q=80', ), User( name: 'Amy Smith', imageUrl: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=80', ), User( name: 'Ed Morris', imageUrl: 'https://images.unsplash.com/photo-1521119989659-a83eee488004?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=664&q=80', ), User( name: 'Carolyn Duncan', imageUrl: 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80', ), User( name: 'Paul Pinnock', imageUrl: 'https://images.unsplash.com/photo-1519631128182-433895475ffe?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80', ), User( name: 'Elizabeth Wong', imageUrl: 'https://images.unsplash.com/photo-1515077678510-ce3bdf418862?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjF9&auto=format&fit=crop&w=675&q=80'), User( name: 'James Lathrop', imageUrl: 'https://images.unsplash.com/photo-1528892952291-009c663ce843?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=592&q=80', ), User( name: 'Jessie Samson', imageUrl: 'https://images.unsplash.com/photo-1517841905240-472988babdf9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80', ), User( name: 'David Brooks', imageUrl: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80', ), User( name: 'Jane Doe', imageUrl: 'https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80', ), User( name: 'Matthew Hinkle', imageUrl: 'https://images.unsplash.com/photo-1492562080023-ab3db95bfbce?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1331&q=80', ), User( name: 'Amy Smith', imageUrl: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=80', ), User( name: 'Ed Morris', imageUrl: 'https://images.unsplash.com/photo-1521119989659-a83eee488004?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=664&q=80', ), User( name: 'Carolyn Duncan', imageUrl: 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80', ), User( name: 'Paul Pinnock', imageUrl: 'https://images.unsplash.com/photo-1519631128182-433895475ffe?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80', ), User( name: 'Elizabeth Wong', imageUrl: 'https://images.unsplash.com/photo-1515077678510-ce3bdf418862?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjF9&auto=format&fit=crop&w=675&q=80'), User( name: 'James Lathrop', imageUrl: 'https://images.unsplash.com/photo-1528892952291-009c663ce843?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=592&q=80', ), User( name: 'Jessie Samson', imageUrl: 'https://images.unsplash.com/photo-1517841905240-472988babdf9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80', ), ]; final List<Story> stories = [ Story( user: onlineUsers[2], imageUrl: 'https://images.unsplash.com/photo-1498307833015-e7b400441eb8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1400&q=80', ), Story( user: onlineUsers[6], imageUrl: 'https://images.unsplash.com/photo-1499363536502-87642509e31b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80', isViewed: true, ), Story( user: onlineUsers[3], imageUrl: 'https://images.unsplash.com/photo-1497262693247-aa258f96c4f5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=624&q=80', ), Story( user: onlineUsers[9], imageUrl: 'https://images.unsplash.com/photo-1496950866446-3253e1470e8e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80', isViewed: true, ), Story( user: onlineUsers[7], imageUrl: 'https://images.unsplash.com/photo-1475688621402-4257c812d6db?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1267&q=80', ), Story( user: onlineUsers[2], imageUrl: 'https://images.unsplash.com/photo-1498307833015-e7b400441eb8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1400&q=80', ), Story( user: onlineUsers[6], imageUrl: 'https://images.unsplash.com/photo-1499363536502-87642509e31b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80', isViewed: true, ), Story( user: onlineUsers[3], imageUrl: 'https://images.unsplash.com/photo-1497262693247-aa258f96c4f5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=624&q=80', ), Story( user: onlineUsers[9], imageUrl: 'https://images.unsplash.com/photo-1496950866446-3253e1470e8e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80', isViewed: true, ), Story( user: onlineUsers[7], imageUrl: 'https://images.unsplash.com/photo-1475688621402-4257c812d6db?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1267&q=80', ), ]; List<Post> posts = [ const Post( user: currentUser, caption: 'Check out these cool puppers', timeAgo: '58m', imageUrl: 'https://images.unsplash.com/photo-1525253086316-d0c936c814f8', likes: 1202, comments: 184, shares: 96, ), Post( user: onlineUsers[5], caption: 'Please enjoy this placeholder text: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', timeAgo: '3hr', imageUrl: null, likes: 683, comments: 79, shares: 18, ), Post( user: onlineUsers[4], caption: 'This is a very good boi.', timeAgo: '8hr', imageUrl: 'https://images.unsplash.com/photo-1575535468632-345892291673?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80', likes: 894, comments: 201, shares: 27, ), Post( user: onlineUsers[3], caption: 'Adventure 🏔', timeAgo: '15hr', imageUrl: 'https://images.unsplash.com/photo-1573331519317-30b24326bb9a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80', likes: 722, comments: 183, shares: 42, ), Post( user: onlineUsers[0], caption: 'More placeholder text for the soul: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', timeAgo: '1d', imageUrl: null, likes: 482, comments: 37, shares: 9, ), Post( user: onlineUsers[9], caption: 'A classic.', timeAgo: '1d', imageUrl: 'https://images.unsplash.com/reserve/OlxPGKgRUaX0E1hg3b3X_Dumbo.JPG?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80', likes: 1523, shares: 129, comments: 301, ) ];
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/screens/screens.dart
export 'home_screen.dart'; export 'nav_screen.dart';
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/screens/home_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_facebook_responsive_ui/config/palette.dart'; import 'package:flutter_facebook_responsive_ui/data/data.dart'; import 'package:flutter_facebook_responsive_ui/models/models.dart'; import 'package:flutter_facebook_responsive_ui/widgets/widgets.dart'; import 'package:material_design_icons_flutter/material_design_icons_flutter.dart'; class HomeScreen extends StatefulWidget { const HomeScreen({Key? key}) : super(key: key); @override _HomeScreenState createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { final TrackingScrollController _trackingScrollController = TrackingScrollController(); @override void dispose() { _trackingScrollController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return GestureDetector( onTap: () => FocusScope.of(context).unfocus(), child: Scaffold( body: Responsive( mobile: _HomeScreenMobile(scrollController: _trackingScrollController), desktop: _HomeScreenDesktop(scrollController: _trackingScrollController), ), ), ); } } class _HomeScreenMobile extends StatelessWidget { final TrackingScrollController scrollController; const _HomeScreenMobile({ Key? key, required this.scrollController, }) : super(key: key); @override Widget build(BuildContext context) { return CustomScrollView( controller: scrollController, slivers: [ SliverAppBar( systemOverlayStyle: SystemUiOverlayStyle.light, backgroundColor: Colors.white, title: const Text( 'facebook', style: TextStyle( color: Palette.facebookBlue, fontSize: 28.0, fontWeight: FontWeight.bold, letterSpacing: -1.2, ), ), centerTitle: false, floating: true, actions: [ CircleButton( icon: Icons.search, iconSize: 30.0, onPressed: () => print('Search'), ), CircleButton( icon: MdiIcons.facebookMessenger, iconSize: 30.0, onPressed: () => print('Messenger'), ), ], ), const SliverToBoxAdapter( child: CreatePostContainer(currentUser: currentUser), ), const SliverPadding( padding: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 5.0), sliver: SliverToBoxAdapter( child: Rooms(onlineUsers: onlineUsers), ), ), SliverPadding( padding: const EdgeInsets.fromLTRB(0.0, 5.0, 0.0, 5.0), sliver: SliverToBoxAdapter( child: Stories( currentUser: currentUser, stories: stories, ), ), ), SliverList( delegate: SliverChildBuilderDelegate( (context, index) { final Post post = posts[index]; return PostContainer(post: post); }, childCount: posts.length, ), ), ], ); } } class _HomeScreenDesktop extends StatelessWidget { final TrackingScrollController scrollController; const _HomeScreenDesktop({ Key? key, required this.scrollController, }) : super(key: key); @override Widget build(BuildContext context) { return Row( children: [ const Flexible( flex: 2, child: Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.all(12.0), child: MoreOptionsList(currentUser: currentUser), ), ), ), const Spacer(), SizedBox( width: 600.0, child: CustomScrollView( controller: scrollController, slivers: [ SliverPadding( padding: const EdgeInsets.fromLTRB(0.0, 20.0, 0.0, 10.0), sliver: SliverToBoxAdapter( child: Stories( currentUser: currentUser, stories: stories, ), ), ), const SliverToBoxAdapter( child: CreatePostContainer(currentUser: currentUser), ), const SliverPadding( padding: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 5.0), sliver: SliverToBoxAdapter( child: Rooms(onlineUsers: onlineUsers), ), ), SliverList( delegate: SliverChildBuilderDelegate( (context, index) { final Post post = posts[index]; return PostContainer(post: post); }, childCount: posts.length, ), ), ], ), ), const Spacer(), const Flexible( flex: 2, child: Align( alignment: Alignment.centerRight, child: Padding( padding: EdgeInsets.all(12.0), child: ContactsList(users: onlineUsers), ), ), ), ], ); } }
0
mirrored_repositories/flutter_facebook_responsive_ui/lib
mirrored_repositories/flutter_facebook_responsive_ui/lib/screens/nav_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_facebook_responsive_ui/data/data.dart'; import 'package:flutter_facebook_responsive_ui/screens/screens.dart'; import 'package:flutter_facebook_responsive_ui/widgets/widgets.dart'; import 'package:material_design_icons_flutter/material_design_icons_flutter.dart'; class NavScreen extends StatefulWidget { const NavScreen({Key? key}) : super(key: key); @override _NavScreenState createState() => _NavScreenState(); } class _NavScreenState extends State<NavScreen> { final List<Widget> _screens = [ const HomeScreen(), const Scaffold(), const Scaffold(), const Scaffold(), const Scaffold(), const Scaffold(), ]; final List<IconData> _icons = const [ Icons.home, Icons.ondemand_video, MdiIcons.accountCircleOutline, MdiIcons.accountGroupOutline, MdiIcons.bellOutline, Icons.menu, ]; int _selectedIndex = 0; @override Widget build(BuildContext context) { final Size screenSize = MediaQuery.of(context).size; return DefaultTabController( length: _icons.length, child: Scaffold( appBar: Responsive.isDesktop(context) ? PreferredSize( preferredSize: Size(screenSize.width, 100.0), child: CustomAppBar( currentUser: currentUser, icons: _icons, selectedIndex: _selectedIndex, onTap: (index) => setState(() => _selectedIndex = index), ), ) : null, body: IndexedStack( index: _selectedIndex, children: _screens, ), bottomNavigationBar: !Responsive.isDesktop(context) ? Container( padding: const EdgeInsets.only(bottom: 12.0), color: Colors.white, child: CustomTabBar( icons: _icons, selectedIndex: _selectedIndex, onTap: (index) => setState(() => _selectedIndex = index), ), ) : const SizedBox.shrink(), ), ); } }
0
mirrored_repositories/flutter_facebook_responsive_ui
mirrored_repositories/flutter_facebook_responsive_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 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:flutter_facebook_responsive_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/JS-Dict
mirrored_repositories/JS-Dict/lib/jp_text.dart
import "package:flutter/material.dart"; const _jpLocale = Locale("ja"); class JpText extends Text { const JpText( super.data, { super.key, super.style, super.strutStyle, super.textAlign, super.textDirection, super.locale = _jpLocale, super.softWrap, super.overflow, super.textScaleFactor, super.maxLines, super.semanticsLabel, super.textWidthBasis, super.textHeightBehavior, super.selectionColor, }); } const jpTextStyle = TextStyle(locale: _jpLocale); extension JpTextStyle on TextStyle { TextStyle jp() => copyWith(locale: _jpLocale); }
0
mirrored_repositories/JS-Dict
mirrored_repositories/JS-Dict/lib/singletons.dart
import "package:flutter/material.dart"; import "package:get_it/get_it.dart"; import "package:jsdict/packages/jisho_client/jisho_client.dart"; import "package:shared_preferences/shared_preferences.dart"; Future<void> registerSingletons() { WidgetsFlutterBinding.ensureInitialized(); GetIt.I.registerLazySingleton<JishoClient>(() => JishoClient()); GetIt.I.registerSingletonAsync<SharedPreferences>( () => SharedPreferences.getInstance()); return GetIt.I.allReady(); } JishoClient getClient() { return GetIt.I<JishoClient>(); } SharedPreferences getPreferences() { return GetIt.I<SharedPreferences>(); }
0
mirrored_repositories/JS-Dict
mirrored_repositories/JS-Dict/lib/main.dart
import "package:dynamic_color/dynamic_color.dart"; import "package:flutter/foundation.dart"; import "package:flutter/material.dart"; import "package:flutter/services.dart"; import "package:jsdict/providers/query_provider.dart"; import "package:jsdict/providers/theme_provider.dart"; import "package:jsdict/screens/search/search_screen.dart"; import "package:jsdict/singletons.dart"; import "package:provider/provider.dart"; void main() async { await registerSingletons(); registerKanjivgLicense(); runApp(const JsDictApp()); } void registerKanjivgLicense() => LicenseRegistry.addLicense(() async* { yield LicenseEntryWithLineBreaks(["KanjiVg"], await rootBundle.loadString("assets/kanjivg/LICENSE.kanjivg.txt")); }); const mainColor = Color(0xFF27CA27); class JsDictApp extends StatelessWidget { const JsDictApp({super.key}); @override Widget build(BuildContext context) { return DynamicColorBuilder(builder: (lightDynamic, darkDynamic) { return MultiProvider( providers: [ ChangeNotifierProvider(create: (_) => QueryProvider()), ChangeNotifierProvider(create: (_) => ThemeProvider()), ], builder: (context, _) { final themeProvider = Provider.of<ThemeProvider>(context); return MaterialApp( title: createTitle("JS-Dict"), themeMode: themeProvider.currentTheme, theme: ThemeData( useMaterial3: true, colorScheme: themeProvider.dynamicColors ? lightDynamic : null, colorSchemeSeed: (lightDynamic == null || !themeProvider.dynamicColors) ? mainColor : null, ), darkTheme: ThemeData( brightness: Brightness.dark, useMaterial3: true, colorScheme: themeProvider.dynamicColors ? darkDynamic : null, colorSchemeSeed: (darkDynamic == null || !themeProvider.dynamicColors) ? mainColor : null, ), home: const SearchScreen(), ); }); }); } // Adds a "Debug" suffix if the app is running in debug mode. String createTitle(String title) { var fullTitle = title; assert(() { fullTitle += " Debug"; return true; }()); return fullTitle; } }
0
mirrored_repositories/JS-Dict/lib
mirrored_repositories/JS-Dict/lib/widgets/copyable_furigana_text.dart
import "package:flutter/material.dart"; import "package:jsdict/jp_text.dart"; import "package:jsdict/models/models.dart"; import "package:jsdict/widgets/action_dialog.dart"; import "package:ruby_text/ruby_text.dart"; class CopyableFuriganaText extends StatelessWidget { const CopyableFuriganaText( this.furigana, { super.key, this.spacing = 0.0, this.style, this.rubyStyle, this.textAlign, this.textDirection, this.softWrap, this.overflow, this.maxLines, this.rubyAlign, this.wrapAlign, }); final Furigana furigana; final double spacing; final TextStyle? style; final TextStyle? rubyStyle; final TextAlign? textAlign; final TextDirection? textDirection; final bool? softWrap; final TextOverflow? overflow; final int? maxLines; final CrossAxisAlignment? rubyAlign; final TextAlign? wrapAlign; @override Widget build(BuildContext context) { return GestureDetector( onLongPress: () => showActionDialog(context, [ ActionTile.text("Text", furigana.getText()), if (furigana.hasFurigana) ActionTile.text("Reading", furigana.getReading()), ]), child: RubyText( furigana.rubyData, spacing: spacing, style: style?.merge(jpTextStyle) ?? jpTextStyle, rubyStyle: rubyStyle?.merge(jpTextStyle) ?? jpTextStyle, textAlign: textAlign, textDirection: textDirection, softWrap: softWrap, overflow: overflow, maxLines: maxLines, rubyAlign: rubyAlign, wrapAlign: wrapAlign, ), ); } }
0
mirrored_repositories/JS-Dict/lib
mirrored_repositories/JS-Dict/lib/widgets/action_dialog.dart
import "package:flutter/material.dart"; import "package:jsdict/packages/copy.dart"; import "package:share_plus/share_plus.dart"; import "package:url_launcher/url_launcher.dart"; void showActionDialog(BuildContext context, List<ActionTile> actions) => showModalBottomSheet( context: context, builder: (_) => ActionDialog(actions: actions), showDragHandle: true, ); class ActionDialog extends StatelessWidget { const ActionDialog({super.key, required this.actions}); final List<ActionTile> actions; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(bottom: 8), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: actions, ), ); } } class ActionTile extends StatelessWidget { const ActionTile.text(this.name, this.data, {super.key}) : isURL = false; const ActionTile.url(this.data, {super.key}) : isURL = true, name = "Link"; final String name; final String data; final bool isURL; void onCopy(BuildContext context) => copyText(context, data, name: name.toLowerCase()); void onShare(BuildContext context) => isURL ? Share.shareUri(Uri.parse(data)) : Share.share(data); void onOpenBrowser(BuildContext context) => launchUrl(Uri.parse(data), mode: LaunchMode.externalApplication); void Function() pop( BuildContext context, void Function(BuildContext context) callback) => () { Navigator.of(context).pop(); callback(context); }; @override Widget build(BuildContext context) { return ListTile( contentPadding: const EdgeInsets.symmetric(horizontal: 16), title: Padding( padding: const EdgeInsets.symmetric(horizontal: 8), child: Text(name), ), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ if (isURL) IconButton( tooltip: "Open in Browser", onPressed: pop(context, onOpenBrowser), icon: const Icon(Icons.open_in_browser)), IconButton( tooltip: "Copy", onPressed: pop(context, onCopy), icon: const Icon(Icons.copy)), IconButton( tooltip: "Share", onPressed: pop(context, onShare), icon: const Icon(Icons.share)), ], ), ); } }
0
mirrored_repositories/JS-Dict/lib
mirrored_repositories/JS-Dict/lib/widgets/error_indicator.dart
import "dart:io"; import "package:expandable_text/expandable_text.dart"; import "package:flutter/material.dart"; import "package:flutter/services.dart"; import "package:http/http.dart"; import "package:jsdict/packages/jisho_client/jisho_client.dart"; class ErrorIndicator extends StatelessWidget { const ErrorIndicator(this.error, {super.key, this.stackTrace, this.onRetry}); final Object error; final Function()? onRetry; final StackTrace? stackTrace; String get _userMessage { if (error is NotFoundException) { return "Page not found"; } if (error is SocketException || error is ClientException) { return "A network error occured.\nCheck your connection."; } return "An error occured"; } @override Widget build(BuildContext context) { return Center( child: Container( margin: const EdgeInsets.all(20.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(_userMessage, textAlign: TextAlign.center), const SizedBox(height: 8), ElevatedButton( child: const Text("Show Error"), onPressed: () => showErrorInfoDialog(context, error, stackTrace: stackTrace), ), if (onRetry != null) ...[ const SizedBox(height: 4), ElevatedButton.icon( icon: const Icon(Icons.refresh), label: const Text("Retry"), onPressed: onRetry, ), ], ], ), ), ); } } void showErrorInfoDialog(BuildContext context, Object error, {StackTrace? stackTrace}) => showDialog( context: context, builder: (context) => ErrorInfoDialog(error, stackTrace: stackTrace)); class ErrorInfoDialog extends StatelessWidget { const ErrorInfoDialog(this.error, {super.key, this.stackTrace}); final Object error; final StackTrace? stackTrace; String get _errorType => error.runtimeType.toString(); String get _errorMessage => error.toString(); Widget _infoText(String title, String info, {TextStyle? style}) { return Text.rich( TextSpan( style: style, children: [ TextSpan( text: title, style: const TextStyle(fontWeight: FontWeight.bold)), TextSpan(text: info), ], ), ); } void _copyError(BuildContext context) { final copyText = "Type: $_errorType \nMessage: $_errorMessage \nStack trace:\n```\n${stackTrace.toString()}```"; Clipboard.setData(ClipboardData(text: copyText)).then((_) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text("Copied error info")), ); }); Navigator.pop(context); } @override Widget build(BuildContext context) { return AlertDialog( titlePadding: const EdgeInsets.only(top: 28, bottom: 12, left: 28, right: 28), contentPadding: const EdgeInsets.symmetric(horizontal: 28), title: const Text("Error Info", style: TextStyle(fontSize: 20)), content: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ _infoText("Type: ", _errorType), _infoText("Message: ", _errorMessage), if (stackTrace != null) ...[ _infoText("Stack trace: ", ""), ExpandableText( stackTrace.toString(), expandText: "Show", collapseText: "Hide", maxLines: 1, linkColor: Theme.of(context).colorScheme.primary, ), ], ], ), ), actions: [ TextButton( child: const Text("Copy"), onPressed: () => _copyError(context), ), TextButton( child: const Text("Close"), onPressed: () => Navigator.pop(context), ), ], ); } }
0
mirrored_repositories/JS-Dict/lib
mirrored_repositories/JS-Dict/lib/widgets/loader.dart
import "package:flutter/material.dart"; import "error_indicator.dart"; class LoaderWidget<T> extends StatefulWidget { const LoaderWidget( {super.key, required this.onLoad, required this.handler, this.placeholder = const Text("")}); final Future<T> Function() onLoad; final Widget Function(T data) handler; final Widget placeholder; @override State<LoaderWidget<T>> createState() => _LoaderWidgetState<T>(); } class _LoaderWidgetState<T> extends State<LoaderWidget<T>> { late Future<T> _future; @override void initState() { super.initState(); _future = widget.onLoad(); } void _retry() { setState(() { _future = widget.onLoad(); }); } @override Widget build(BuildContext context) { return FutureBuilder( future: _future, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center( child: Container( margin: const EdgeInsets.all(20.0), child: const CircularProgressIndicator()), ); } if (snapshot.connectionState == ConnectionState.none) { return widget.placeholder; } if (snapshot.hasError) { return ErrorIndicator( snapshot.error!, stackTrace: snapshot.stackTrace, onRetry: _retry, ); } if (snapshot.hasData && snapshot.data != null) { return widget.handler(snapshot.data as T); } throw AssertionError(); }); } }
0
mirrored_repositories/JS-Dict/lib
mirrored_repositories/JS-Dict/lib/widgets/link_span.dart
import "package:flutter/gestures.dart"; import "package:flutter/material.dart"; import "package:jsdict/jp_text.dart"; class LinkSpan extends TextSpan { LinkSpan(BuildContext context, {required String text, required Function() onTap, bool bold = false, bool underline = true}) : super( text: text, style: TextStyle( color: Theme.of(context).colorScheme.primary, decoration: underline ? TextDecoration.underline : null, fontWeight: bold ? FontWeight.w600 : null) .jp(), recognizer: TapGestureRecognizer()..onTap = onTap); }
0
mirrored_repositories/JS-Dict/lib
mirrored_repositories/JS-Dict/lib/widgets/entry_tile.dart
import "package:flutter/material.dart"; /// Custom ListTile /// /// Adds a trailing right-arrow if [onTap] is not null. /// Rounds the bottom corners if [isLast] is true. class EntryTile extends ListTile { static const _roundedBottomBorder = RoundedRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(8), bottomRight: Radius.circular(8))); const EntryTile({ super.key, super.leading, super.title, super.subtitle, super.isThreeLine = false, super.dense, super.visualDensity, super.style, super.selectedColor, super.iconColor, super.textColor, super.titleTextStyle, super.subtitleTextStyle, super.leadingAndTrailingTextStyle, super.contentPadding, super.enabled = true, super.onTap, super.onLongPress, super.onFocusChange, super.mouseCursor, super.selected = false, super.focusColor, super.hoverColor, super.splashColor, super.focusNode, super.autofocus = false, super.tileColor, super.selectedTileColor, super.enableFeedback, super.horizontalTitleGap, super.minVerticalPadding, super.minLeadingWidth, super.titleAlignment, bool isLast = false, }) : super( trailing: onTap != null ? const Icon(Icons.keyboard_arrow_right) : null, shape: isLast ? _roundedBottomBorder : null); }
0
mirrored_repositories/JS-Dict/lib
mirrored_repositories/JS-Dict/lib/widgets/link_popup.dart
import "package:flutter/material.dart"; import "package:url_launcher/url_launcher.dart"; class LinkPopupButton extends StatelessWidget { const LinkPopupButton(this.data, {super.key}); final List<(String text, String url)> data; @override Widget build(BuildContext context) { return PopupMenuButton( itemBuilder: (context) => data .map((entry) => PopupMenuItem( child: Text(entry.$1), onTap: () => launchUrl(Uri.parse(entry.$2), mode: LaunchMode.externalApplication), )) .toList(), ); } }
0
mirrored_repositories/JS-Dict/lib
mirrored_repositories/JS-Dict/lib/widgets/wikipedia.dart
import "package:expansion_tile_card/expansion_tile_card.dart"; import "package:flutter/material.dart"; import "package:jsdict/models/models.dart"; import "package:url_launcher/url_launcher.dart"; class WikipediaWidget extends StatelessWidget { const WikipediaWidget(this.wikipedia, {super.key}); final WikipediaInfo wikipedia; Widget link(WikipediaPage page, String wikiName, String id) => Tooltip( message: wikiName, child: ElevatedButton( child: Text(id), onPressed: () { launchUrl( Uri.parse(page.url.replaceFirst(RegExp(r"[\?&]oldid=\d+"), "")), mode: LaunchMode.externalApplication); }, ), ); @override Widget build(BuildContext context) { final shadowColor = Theme.of(context).colorScheme.shadow; return ExpansionTileCard( shadowColor: shadowColor, title: const Text("Wikipedia"), children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16), child: Column( children: [ if (wikipedia.textAbstract != null) ...[ SelectableText(wikipedia.textAbstract!), const SizedBox(height: 12), ], Wrap( spacing: 8, children: [ if (wikipedia.wikipediaEnglish != null) link( wikipedia.wikipediaEnglish!, "Wikipedia English", "EN"), if (wikipedia.wikipediaJapanese != null) link(wikipedia.wikipediaJapanese!, "Wikipedia Japanese", "JP"), if (wikipedia.dbpedia != null) link(wikipedia.dbpedia!, "DBpedia", "DB"), ], ), ], ), ), ], ); } }
0
mirrored_repositories/JS-Dict/lib
mirrored_repositories/JS-Dict/lib/widgets/info_chips.dart
import "package:dynamic_color/dynamic_color.dart"; import "package:flutter/material.dart"; import "package:jsdict/jp_text.dart"; import "package:jsdict/providers/theme_provider.dart"; import "package:provider/provider.dart"; class InfoChip extends StatelessWidget { const InfoChip(this.text, {super.key, this.color, this.onTap, this.icon}); final String text; final Color? color; final Function()? onTap; final IconData? icon; @override Widget build(BuildContext context) { return DynamicColorBuilder( builder: (dynamicColorScheme, _) => Consumer<ThemeProvider>(builder: (context, themeProvider, _) { final dynamicColorsDisabled = dynamicColorScheme == null || !themeProvider.dynamicColors; return Card( surfaceTintColor: dynamicColorsDisabled ? color : null, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(48)), child: InkWell( borderRadius: BorderRadius.circular(48), onTap: onTap, child: Padding( padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8), child: icon != null ? Row( mainAxisSize: MainAxisSize.min, children: [ Icon(icon, size: 16), const SizedBox(width: 2), JpText(text), ], ) : JpText(text), ), )); }), ); } }
0
mirrored_repositories/JS-Dict/lib
mirrored_repositories/JS-Dict/lib/widgets/copyright_text.dart
import "package:flutter/material.dart"; import "package:jsdict/models/models.dart"; import "package:jsdict/widgets/link_span.dart"; import "package:url_launcher/url_launcher.dart"; class CopyrightText extends StatelessWidget { const CopyrightText(this.copyright, {super.key}); final SentenceCopyright copyright; @override Widget build(BuildContext context) { final textColor = Theme.of(context).textTheme.bodyLarge!.color; return RichText( text: TextSpan( children: [ TextSpan(text: "— ", style: TextStyle(color: textColor)), LinkSpan( context, text: copyright.name, underline: false, onTap: () { launchUrl(Uri.parse(copyright.url), mode: LaunchMode.externalApplication); }, ), ], )); } }
0
mirrored_repositories/JS-Dict/lib/widgets
mirrored_repositories/JS-Dict/lib/widgets/items/name_item.dart
import "package:flutter/material.dart"; import "package:jsdict/jp_text.dart"; import "package:jsdict/models/models.dart"; import "package:jsdict/packages/navigation.dart"; import "package:jsdict/screens/name_details_screen.dart"; import "package:jsdict/widgets/action_dialog.dart"; import "package:jsdict/widgets/items/item_card.dart"; class NameItem extends StatelessWidget { const NameItem({super.key, required this.name}); final Name name; @override Widget build(BuildContext context) { return ItemCard( onTap: pushScreen(context, NameDetailsScreen(name)), onLongPress: () => showActionDialog(context, [ if (name.wikipediaWord != null) ActionTile.url( "https://jisho.org/word/${Uri.encodeComponent(name.wikipediaWord!)}"), ActionTile.text("Name", name.japanese), if (name.reading != null) ActionTile.text("Reading", name.reading!), ActionTile.text("English", name.english), ]), child: ListTile( contentPadding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 22.0), title: JpText(name.toString()), subtitle: Text(name.english))); } }
0
mirrored_repositories/JS-Dict/lib/widgets
mirrored_repositories/JS-Dict/lib/widgets/items/sentence_item.dart
import "package:flutter/material.dart"; import "package:jsdict/jp_text.dart"; import "package:jsdict/models/models.dart"; import "package:jsdict/packages/navigation.dart"; import "package:jsdict/screens/sentence_details_screen.dart"; import "package:jsdict/widgets/action_dialog.dart"; import "package:jsdict/widgets/copyright_text.dart"; import "package:ruby_text/ruby_text.dart"; import "item_card.dart"; class SentenceItem extends StatelessWidget { const SentenceItem({super.key, required this.sentence}); final Sentence sentence; @override Widget build(BuildContext context) { return ItemCard( onTap: pushScreen(context, SentenceDetailsScreen(sentence)), onLongPress: () => showActionDialog(context, [ ActionTile.url(sentence.url), ActionTile.text("Japanese", sentence.japanese.getText()), ActionTile.text("English", sentence.english), ]), child: ListTile( contentPadding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 22.0), title: RubyText(sentence.japanese.rubyData, style: jpTextStyle, rubyAlign: CrossAxisAlignment.start, wrapAlign: TextAlign.start), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Text(sentence.english), if (sentence.copyright != null) ...[ const SizedBox(height: 4), CopyrightText(sentence.copyright!), ] ], ))); } }
0
mirrored_repositories/JS-Dict/lib/widgets
mirrored_repositories/JS-Dict/lib/widgets/items/item_card.dart
import "package:flutter/material.dart"; class ItemCard extends StatelessWidget { const ItemCard( {super.key, required this.child, this.onTap, this.onLongPress}); final Widget child; final Function()? onTap; final Function()? onLongPress; @override Widget build(BuildContext context) { return Card( child: InkWell( borderRadius: BorderRadius.circular(12), onTap: onTap ?? () => {}, onLongPress: onLongPress ?? () => {}, child: child, ), ); } }
0
mirrored_repositories/JS-Dict/lib/widgets
mirrored_repositories/JS-Dict/lib/widgets/items/word_item.dart
import "package:flutter/material.dart"; import "package:jsdict/jp_text.dart"; import "package:jsdict/models/models.dart"; import "package:jsdict/packages/list_extensions.dart"; import "package:jsdict/packages/navigation.dart"; import "package:jsdict/screens/word_details/word_details_screen.dart"; import "package:jsdict/widgets/action_dialog.dart"; import "package:ruby_text/ruby_text.dart"; import "item_card.dart"; class WordItem extends StatelessWidget { const WordItem({super.key, required this.word}); final Word word; @override Widget build(BuildContext context) { final textStyle = Theme.of(context).textTheme.bodyMedium!; return ItemCard( onTap: pushScreen(context, WordDetailsScreen(word)), onLongPress: () => showActionDialog(context, [ ActionTile.url(word.url), ActionTile.text("Word", word.word.getText()), if (word.word.hasFurigana) ActionTile.text("Reading", word.word.getReading()), ]), child: ListTile( contentPadding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 22.0), title: RubyText( word.word.rubyData, style: const TextStyle(fontSize: 18).jp(), rubyStyle: const TextStyle(fontSize: 10).jp(), ), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: word.definitions .map((e) => e.meanings.join("; ")) .toList() .deduplicateCaseInsensitive() .asMap() .entries .map((entry) => RichText( text: TextSpan(children: [ TextSpan( text: "${entry.key + 1}. ", style: textStyle.copyWith(fontWeight: FontWeight.w300)), TextSpan(text: entry.value, style: textStyle), ]))) .toList(), )), ); } }
0
mirrored_repositories/JS-Dict/lib/widgets
mirrored_repositories/JS-Dict/lib/widgets/items/kanji_item.dart
import "package:flutter/material.dart"; import "package:jsdict/jp_text.dart"; import "package:jsdict/models/models.dart"; import "package:jsdict/packages/navigation.dart"; import "package:jsdict/packages/string_util.dart"; import "package:jsdict/screens/kanji_details/kanji_details_screen.dart"; import "package:jsdict/widgets/action_dialog.dart"; import "item_card.dart"; class KanjiItem extends StatelessWidget { const KanjiItem({super.key, required this.kanji}); final Kanji kanji; @override Widget build(BuildContext context) { return ItemCard( onTap: pushScreen(context, KanjiDetailsScreen(kanji)), onLongPress: () => showActionDialog(context, [ ActionTile.url(kanji.url), ActionTile.text("Kanji", kanji.kanji), ActionTile.text("Meanings", kanji.meanings.join(", ")), ]), child: ListTile( contentPadding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 22.0), leading: JpText(kanji.kanji, style: const TextStyle(fontSize: 35)), title: Text(kanji.meanings.join(", "), style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w500)), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ if (kanji.kunReadings.isNotEmpty) JpText( "Kun: ${kanji.kunReadings.join("、$zeroWidthSpace").noBreak}"), if (kanji.onReadings.isNotEmpty) JpText( "On: ${kanji.onReadings.join("、$zeroWidthSpace").noBreak}"), JpText([ "${kanji.strokeCount} strokes", if (kanji.jlptLevel != JLPTLevel.none) "JLPT ${kanji.jlptLevel}", if (kanji.type != null) kanji.type.toString(), ].join(", ")), ], ))); } } class KanjiItemList extends StatelessWidget { const KanjiItemList(this.kanjiList, {super.key}); final List<Kanji> kanjiList; @override Widget build(BuildContext context) { return ListView.builder( physics: const NeverScrollableScrollPhysics(), shrinkWrap: true, itemCount: kanjiList.length, itemBuilder: (_, index) => KanjiItem(kanji: kanjiList[index])); } }
0