repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/feature_matcher.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'interfaces.dart'; import 'type_matcher.dart'; /// A package-private [TypeMatcher] implementation that makes it easy for /// subclasses to validate aspects of specific types while providing consistent /// type checking. abstract class FeatureMatcher<T> extends TypeMatcher<T> { const FeatureMatcher(); @override bool matches(item, Map matchState) => super.matches(item, matchState) && typedMatches(item, matchState); bool typedMatches(T item, Map matchState); @override Description describeMismatch( item, Description mismatchDescription, Map matchState, bool verbose) { if (item is T) { return describeTypedMismatch( item, mismatchDescription, matchState, verbose); } return super.describe(mismatchDescription.add('not an ')); } Description describeTypedMismatch(T item, Description mismatchDescription, Map matchState, bool verbose) => mismatchDescription; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io/node_io.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code // is governed by a BSD-style license that can be found in the LICENSE file. /// Node.js I/O system for Dart. /// /// This library is designed so that you should be able to replace imports of /// `dart:io` with `package:node_io/node_io.dart` and get the same functionality /// working without any additional modifications. library node_io; import 'package:node_interop/node.dart'; import 'src/stdout.dart'; export 'dart:io' show BytesBuilder, Datagram, FileSystemEntity, FileSystemEntityType, FileMode, IOSink, RandomAccessFile, FileSystemException, HttpHeaders, OSError; export 'src/directory.dart'; export 'src/file.dart'; export 'src/file_system_entity.dart' show FileStat; export 'src/http_server.dart'; export 'src/internet_address.dart'; export 'src/link.dart'; export 'src/network_interface.dart'; export 'src/platform.dart'; export 'src/stdout.dart'; /// Get the global exit code for the current process. /// /// The exit code is global and the last assignment to exitCode /// determines the exit code of the process on normal termination. /// /// See [exit] for more information on how to chose a value for the exit code. int get exitCode => process.exitCode; /// Set the global exit code for the current process. /// /// The exit code is global and the last assignment to exitCode /// determines the exit code of the process on normal termination. /// /// Default value is 0. /// /// See [exit] for more information on how to chose a value for the exit code. set exitCode(int value) { process.exitCode = value; } /// Exit the process immediately with the given exit code. /// /// This does not wait for any asynchronous operations to terminate. Using /// exit is therefore very likely to lose data. /// /// The handling of exit codes is platform specific. /// /// On Linux and OS X an exit code for normal termination will always be in /// the range 0..255. If an exit code outside this range is set the actual /// exit code will be the lower 8 bits masked off and treated as an unsigned /// value. E.g. using an exit code of -1 will result in an actual exit code of /// 255 being reported. /// /// On Windows the exit code can be set to any 32-bit value. However some of /// these values are reserved for reporting system errors like crashes. void exit([int code]) { if (code is! int) { throw ArgumentError('Integer value for exit code expected'); } process.exit(code); } /// Returns the PID of the current process. int get pid => process.pid; /// The standard output stream of errors written by this program. Stdout get stderr { return Stdout(process.stderr); } /// The standard output stream of data written by this program. Stdout get stdout { return Stdout(process.stdout); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io/src/http_server.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code // is governed by a BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io' as io; import 'dart:js'; import 'dart:js_util'; import 'dart:typed_data'; import 'package:node_interop/http.dart' as _http; import 'http_headers.dart'; import 'internet_address.dart'; import 'streams.dart'; export 'dart:io' show HttpDate, HttpStatus, HttpHeaders, HeaderValue, ContentType, Cookie, HttpException, HttpRequest, HttpResponse, HttpConnectionInfo; class _HttpConnectionInfo implements io.HttpConnectionInfo { @override final int localPort; @override final InternetAddress remoteAddress; @override final int remotePort; _HttpConnectionInfo(this.localPort, this.remoteAddress, this.remotePort); } /// A server that delivers content, such as web pages, using the HTTP protocol. /// /// The HttpServer is a [Stream] that provides [io.HttpRequest] objects. Each /// HttpRequest has an associated [io.HttpResponse] object. /// The server responds to a request by writing to that HttpResponse object. /// The following example shows how to bind an HttpServer to an IPv6 /// [InternetAddress] on port 80 (the standard port for HTTP servers) /// and how to listen for requests. /// Port 80 is the default HTTP port. However, on most systems accessing /// this requires super-user privileges. For local testing consider /// using a non-reserved port (1024 and above). /// /// import 'dart:io'; /// /// main() { /// HttpServer /// .bind(InternetAddress.anyIPv6, 80) /// .then((server) { /// server.listen((HttpRequest request) { /// request.response.write('Hello, world!'); /// request.response.close(); /// }); /// }); /// } /// /// Incomplete requests, in which all or part of the header is missing, are /// ignored, and no exceptions or HttpRequest objects are generated for them. /// Likewise, when writing to an HttpResponse, any [io.Socket] exceptions are /// ignored and any future writes are ignored. /// /// The HttpRequest exposes the request headers and provides the request body, /// if it exists, as a Stream of data. If the body is unread, it is drained /// when the server writes to the HttpResponse or closes it. abstract class HttpServer implements io.HttpServer { /// Starts listening for HTTP requests on the specified [address] and /// [port]. /// /// The [address] can either be a [String] or an /// [InternetAddress]. If [address] is a [String], [bind] will /// perform a [InternetAddress.lookup] and use the first value in the /// list. To listen on the loopback adapter, which will allow only /// incoming connections from the local host, use the value /// [InternetAddress.loopbackIPv4] or /// [InternetAddress.loopbackIPv6]. To allow for incoming /// connection from the network use either one of the values /// [InternetAddress.anyIPv4] or [InternetAddress.anyIPv6] to /// bind to all interfaces or the IP address of a specific interface. /// /// If an IP version 6 (IPv6) address is used, both IP version 6 /// (IPv6) and version 4 (IPv4) connections will be accepted. To /// restrict this to version 6 (IPv6) only, use [v6Only] to set /// version 6 only. However, if the address is /// [InternetAddress.loopbackIPv6], only IP version 6 (IPv6) connections /// will be accepted. /// /// If [port] has the value [:0:] an ephemeral port will be chosen by /// the system. The actual port used can be retrieved using the /// [port] getter. /// /// The optional argument [backlog] can be used to specify the listen /// backlog for the underlying OS listen setup. If [backlog] has the /// value of [:0:] (the default) a reasonable value will be chosen by /// the system. /// /// The optional argument [shared] specifies whether additional HttpServer /// objects can bind to the same combination of `address`, `port` and `v6Only`. /// If `shared` is `true` and more `HttpServer`s from this isolate or other /// isolates are bound to the port, then the incoming connections will be /// distributed among all the bound `HttpServer`s. Connections can be /// distributed over multiple isolates this way. static Future<io.HttpServer> bind(address, int port, {int backlog = 0, bool v6Only = false, bool shared = false}) => _HttpServer.bind(address, port, backlog: backlog, v6Only: v6Only, shared: shared); } class _HttpServer extends Stream<io.HttpRequest> implements HttpServer { @override final io.InternetAddress address; @override final int port; _http.HttpServer _server; Completer<io.HttpServer> _listenCompleter; StreamController<io.HttpRequest> _controller; _HttpServer._(this.address, this.port) { _controller = StreamController<io.HttpRequest>( onListen: _onListen, onPause: _onPause, onResume: _onResume, onCancel: _onCancel, ); _server = _http.http.createServer(allowInterop(_jsRequestHandler)); _server.on('error', allowInterop(_jsErrorHandler)); } void _onListen() {} void _onPause() {} void _onResume() {} void _onCancel() { _server.close(); } void _jsErrorHandler(error) { if (_listenCompleter != null) { _listenCompleter.completeError(error); _listenCompleter = null; } _controller.addError(error); } void _jsRequestHandler( _http.IncomingMessage request, _http.ServerResponse response) { if (_controller.isPaused) { // Reject any incoming request before listening started or subscription // is paused. response.statusCode = io.HttpStatus.serviceUnavailable; response.end(); return; } _controller.add(NodeHttpRequest(request, response)); } Future<io.HttpServer> _bind() { assert(_server.listening == false && _listenCompleter == null); _listenCompleter = Completer<io.HttpServer>(); void listeningHandler() { _listenCompleter.complete(this); _listenCompleter = null; } _server.listen(port, address.address, null, allowInterop(listeningHandler)); return _listenCompleter.future; } static Future<io.HttpServer> bind(address, int port, {int backlog = 0, bool v6Only = false, bool shared = false}) async { assert(!shared, 'Shared is not implemented yet'); if (address is String) { List<InternetAddress> list = await InternetAddress.lookup(address); address = list.first; } var server = _HttpServer._(address, port); return server._bind(); } @override bool autoCompress; // TODO: Implement autoCompress @override Duration idleTimeout; // TODO: Implement idleTimeout @override String serverHeader; // TODO: Implement serverHeader @override Future close({bool force = false}) { assert(!force, 'Force argument is not supported by Node HTTP server'); final completer = Completer(); _server.close(allowInterop(([error]) { _controller.close(); if (error != null) { completer.complete(error); } else { completer.complete(); } })); return completer.future; } @override io.HttpConnectionsInfo connectionsInfo() { throw UnimplementedError(); } @override io.HttpHeaders get defaultResponseHeaders => throw UnimplementedError(); @override StreamSubscription<io.HttpRequest> listen( void Function(io.HttpRequest event) onData, { Function onError, void Function() onDone, bool cancelOnError, }) { return _controller.stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } @override set sessionTimeout(int timeout) { throw UnimplementedError(); } } /// Server side HTTP request object which delegates IO operations to /// Node.js native representations. class NodeHttpRequest implements io.HttpRequest, HasReadable { final ReadableStream<Uint8List> _delegate; final _http.ServerResponse _nativeResponse; NodeHttpRequest(_http.IncomingMessage nativeRequest, this._nativeResponse) : _delegate = ReadableStream(nativeRequest, convert: (chunk) => Uint8List.fromList(chunk)); @override _http.IncomingMessage get nativeInstance => _delegate.nativeInstance; @override io.X509Certificate get certificate => throw UnimplementedError(); @override io.HttpConnectionInfo get connectionInfo { var socket = nativeInstance.socket; var address = InternetAddress(socket.remoteAddress); return _HttpConnectionInfo(socket.localPort, address, socket.remotePort); } @override int get contentLength => headers.contentLength; @override List<io.Cookie> get cookies { if (_cookies != null) return _cookies; _cookies = <io.Cookie>[]; final values = headers[io.HttpHeaders.setCookieHeader]; if (values != null) { values.forEach((value) { _cookies.add(io.Cookie.fromSetCookieValue(value)); }); } return _cookies; } List<io.Cookie> _cookies; @override io.HttpHeaders get headers => _headers ??= RequestHttpHeaders(nativeInstance); io.HttpHeaders _headers; @override String get method => nativeInstance.method; @override bool get persistentConnection => headers.persistentConnection; @override String get protocolVersion => nativeInstance.httpVersion; @override Uri get requestedUri { if (_requestedUri == null) { var socket = nativeInstance.socket; var proto = headers['x-forwarded-proto']; var scheme; if (proto != null) { scheme = proto.first; } else { var isSecure = getProperty(socket, 'encrypted') ?? false; scheme = isSecure ? 'https' : 'http'; } var hostList = headers['x-forwarded-host']; String host; if (hostList != null) { host = hostList.first; } else { hostList = headers['host']; if (hostList != null) { host = hostList.first; } else { host = '${socket.localAddress}:${socket.localPort}'; } } _requestedUri = Uri.parse('$scheme://$host$uri'); } return _requestedUri; } Uri _requestedUri; @override io.HttpResponse get response => _response ??= NodeHttpResponse(_nativeResponse); io.HttpResponse _response; // ignore: close_sinks @override io.HttpSession get session => throw UnsupportedError('Sessions are not supported by Node HTTP server.'); @override Uri get uri => Uri.parse(nativeInstance.url); @override StreamSubscription<Uint8List> listen( void Function(Uint8List event) onData, { Function onError, void Function() onDone, bool cancelOnError, }) { return const Stream<Uint8List>.empty().listen( onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError, ); } @override Future<bool> any(bool Function(Uint8List element) test) { return _delegate.any(test); } @override Stream<Uint8List> asBroadcastStream({ void Function(StreamSubscription<Uint8List> subscription) onListen, void Function(StreamSubscription<Uint8List> subscription) onCancel, }) { return _delegate.asBroadcastStream(onListen: onListen, onCancel: onCancel); } @override Stream<E> asyncExpand<E>(Stream<E> Function(Uint8List event) convert) { return _delegate.asyncExpand<E>(convert); } @override Stream<E> asyncMap<E>(FutureOr<E> Function(Uint8List event) convert) { return _delegate.asyncMap<E>(convert); } @override Stream<R> cast<R>() { return _delegate.cast<R>(); } @override Future<bool> contains(Object needle) { return _delegate.contains(needle); } @override Stream<Uint8List> distinct( [bool Function(Uint8List previous, Uint8List next) equals]) { return _delegate.distinct(equals); } @override Future<E> drain<E>([E futureValue]) { return _delegate.drain<E>(futureValue); } @override Future<Uint8List> elementAt(int index) { return _delegate.elementAt(index); } @override Future<bool> every(bool Function(Uint8List element) test) { return _delegate.every(test); } @override Stream<S> expand<S>(Iterable<S> Function(Uint8List element) convert) { return _delegate.expand(convert); } @override Future<Uint8List> get first => _delegate.first; @override Future<Uint8List> firstWhere( bool Function(Uint8List element) test, { List<int> Function() orElse, }) { return _delegate.firstWhere(test, orElse: () { return Uint8List.fromList(orElse()); }); } @override Future<S> fold<S>( S initialValue, S Function(S previous, Uint8List element) combine) { return _delegate.fold<S>(initialValue, combine); } @override Future<dynamic> forEach(void Function(Uint8List element) action) { return _delegate.forEach(action); } @override Stream<Uint8List> handleError( Function onError, { bool Function(dynamic error) test, }) { return _delegate.handleError(onError, test: test); } @override bool get isBroadcast => _delegate.isBroadcast; @override Future<bool> get isEmpty => _delegate.isEmpty; @override Future<String> join([String separator = '']) { return _delegate.join(separator); } @override Future<Uint8List> get last => _delegate.last; @override Future<Uint8List> lastWhere( bool Function(Uint8List element) test, { List<int> Function() orElse, }) { return _delegate.lastWhere(test, orElse: () { return Uint8List.fromList(orElse()); }); } @override Future<int> get length => _delegate.length; @override Stream<S> map<S>(S Function(Uint8List event) convert) { return _delegate.map<S>(convert); } @override Future<dynamic> pipe(StreamConsumer<List<int>> streamConsumer) { return _delegate.cast<List<int>>().pipe(streamConsumer); } @override Future<Uint8List> reduce( List<int> Function(Uint8List previous, Uint8List element) combine) { return _delegate.reduce((p, e) => Uint8List.fromList(combine(p, e))); } @override Future<Uint8List> get single => _delegate.single; @override Future<Uint8List> singleWhere(bool Function(Uint8List element) test, {List<int> Function() orElse}) { return _delegate.singleWhere(test, orElse: () { return Uint8List.fromList(orElse()); }); } @override Stream<Uint8List> skip(int count) { return _delegate.skip(count); } @override Stream<Uint8List> skipWhile(bool Function(Uint8List element) test) { return _delegate.skipWhile(test); } @override Stream<Uint8List> take(int count) { return _delegate.take(count); } @override Stream<Uint8List> takeWhile(bool Function(Uint8List element) test) { return _delegate.takeWhile(test); } @override Stream<Uint8List> timeout( Duration timeLimit, { void Function(EventSink<Uint8List> sink) onTimeout, }) { return _delegate.timeout(timeLimit, onTimeout: onTimeout); } @override Future<List<Uint8List>> toList() { return _delegate.toList(); } @override Future<Set<Uint8List>> toSet() { return _delegate.toSet(); } @override Stream<S> transform<S>(StreamTransformer<List<int>, S> streamTransformer) { return _delegate.cast<List<int>>().transform<S>(streamTransformer); } @override Stream<Uint8List> where(bool Function(Uint8List event) test) { return _delegate.where(test); } } /// Server side HTTP response object which delegates IO operations to /// Node.js native representations. class NodeHttpResponse extends NodeIOSink implements io.HttpResponse { NodeHttpResponse(_http.ServerResponse nativeResponse) : super(nativeResponse); @override _http.ServerResponse get nativeInstance => super.nativeInstance; @override bool get bufferOutput => throw UnimplementedError(); @override set bufferOutput(bool buffer) { throw UnimplementedError(); } @override int get contentLength => throw UnimplementedError(); @override set contentLength(int length) { throw UnimplementedError(); } @override Duration get deadline => throw UnimplementedError(); @override set deadline(Duration value) { throw UnimplementedError(); } @override bool get persistentConnection => headers.persistentConnection; @override set persistentConnection(bool persistent) { headers.persistentConnection = persistent; } @override String get reasonPhrase => nativeInstance.statusMessage; @override set reasonPhrase(String phrase) { if (nativeInstance.headersSent) { throw StateError('Headers already sent.'); } nativeInstance.statusMessage = phrase; } @override int get statusCode => nativeInstance.statusCode; @override set statusCode(int code) { if (nativeInstance.headersSent) { throw StateError('Headers already sent.'); } nativeInstance.statusCode = code; } @override Future close() { ResponseHttpHeaders responseHeaders = headers; responseHeaders.finalize(); return super.close(); } @override io.HttpConnectionInfo get connectionInfo { var socket = nativeInstance.socket; var address = InternetAddress(socket.remoteAddress); return _HttpConnectionInfo(socket.localPort, address, socket.remotePort); } @override List<io.Cookie> get cookies { if (_cookies != null) return _cookies; _cookies = <io.Cookie>[]; final values = headers[io.HttpHeaders.setCookieHeader]; if (values != null) { values.forEach((value) { _cookies.add(io.Cookie.fromSetCookieValue(value)); }); } return _cookies; } List<io.Cookie> _cookies; @override Future<io.Socket> detachSocket({bool writeHeaders = true}) { throw UnimplementedError(); } @override io.HttpHeaders get headers => _headers ??= ResponseHttpHeaders(nativeInstance); ResponseHttpHeaders _headers; @override Future redirect(Uri location, {int status = io.HttpStatus.movedTemporarily}) { statusCode = status; headers.set('location', '$location'); return close(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io/src/platform.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code // is governed by a BSD-style license that can be found in the LICENSE file. import 'package:node_interop/node.dart'; import 'package:node_interop/os.dart'; import 'package:node_interop/path.dart'; import 'package:node_interop/util.dart'; /// Information about the environment in which the current program is running. /// /// Platform provides information such as the operating system, /// the hostname of the computer, the value of environment variables, /// the path to the running program, /// and so on. /// /// ## Get the URI to the current Dart script /// /// Use the [script] getter to get the URI to the currently running /// Dart script. /// /// import 'dart:io' show Platform; /// /// void main() { /// // Get the URI of the script being run. /// var uri = Platform.script; /// // Convert the URI to a path. /// var path = uri.toFilePath(); /// } /// /// ## Get the value of an environment variable /// /// The [environment] getter returns a the names and values of environment /// variables in a [Map] that contains key-value pairs of strings. The Map is /// unmodifiable. This sample shows how to get the value of the `PATH` /// environment variable. /// /// import 'dart:io' show Platform; /// /// void main() { /// Map<String, String> envVars = Platform.environment; /// print(envVars['PATH']); /// } /// /// ## Determine the OS /// /// You can get the name of the operating system as a string with the /// [operatingSystem] getter. You can also use one of the static boolean /// getters: [isMacOS], [isLinux], and [isWindows]. /// /// import 'dart:io' show Platform, stdout; /// /// void main() { /// // Get the operating system as a string. /// String os = Platform.operatingSystem; /// // Or, use a predicate getter. /// if (Platform.isMacOS) { /// print('is a Mac'); /// } else { /// print('is not a Mac'); /// } /// } abstract class Platform { /// The number of individual execution units of the machine. static int get numberOfProcessors => os.cpus().length; /// The path separator used by the operating system to separate /// components in file paths. static String get pathSeparator => path.sep; /// Get the name of the current locale. static String get localeName => throw UnsupportedError('Not supported in Node.'); /// A string representing the operating system or platform. static String get operatingSystem => os.platform(); /// A string representing the version of the operating system or platform. static String get operatingSystemVersion => os.release(); /// The local hostname for the system. static String get localHostname => os.hostname(); /// Whether the operating system is a version of /// [Linux](https://en.wikipedia.org/wiki/Linux). /// /// This value is `false` if the operating system is a specialized /// version of Linux that identifies itself by a different name, /// for example Android (see [isAndroid]). static final bool isLinux = (operatingSystem == 'linux'); /// Whether the operating system is a version of /// [macOS](https://en.wikipedia.org/wiki/MacOS). static final bool isMacOS = (operatingSystem == 'darwin'); /// Whether the operating system is a version of /// [Microsoft Windows](https://en.wikipedia.org/wiki/Microsoft_Windows). static final bool isWindows = (operatingSystem == 'win32'); /// Whether the operating system is a version of /// [Android](https://en.wikipedia.org/wiki/Android_%28operating_system%29). static final bool isAndroid = (operatingSystem == 'android'); /// Whether the operating system is a version of /// [iOS](https://en.wikipedia.org/wiki/IOS). static bool get isIOS => throw UnsupportedError('iOS is not supported by Node.js.'); /// Whether the operating system is a version of /// [Fuchsia](https://en.wikipedia.org/wiki/Google_Fuchsia). static bool get isFuchsia => throw UnsupportedError('Fuchsia is not supported by Node.js.'); /// The environment for this process as a map from string key to string value. /// /// The map is unmodifiable, /// and its content is retrieved from the operating system on its first use. /// Environment variables on Windows are case-insensitive, /// so on Windows the map is case-insensitive and will convert /// all keys to upper case. /// On other platforms, keys can be distinguished by case. static Map<String, String> get environment => Map.unmodifiable(dartify(process.env)); /// The path of the executable used to run the script in this isolate. /// /// The literal path used to identify the script. /// This path might be relative or just be a name from which the executable /// was found by searching the system path. /// /// Use [resolvedExecutable] to get an absolute path to the executable. static String get executable => process.argv0; /// The path of the executable used to run the script in this /// isolate after it has been resolved by the OS. /// /// This is the absolute path, with all symlinks resolved, to the /// executable used to run the script. static String get resolvedExecutable => process.execPath; /// The absolute URI of the script being run in this isolate. /// /// If the script argument on the command line is relative, /// it is resolved to an absolute URI before fetching the script, and /// that absolute URI is returned. /// /// URI resolution only does string manipulation on the script path, and this /// may be different from the file system's path resolution behavior. For /// example, a symbolic link immediately followed by '..' will not be /// looked up. /// /// If the executable environment does not support [script], /// the URI is empty. static Uri get script => Uri.file(process.argv[1], windows: Platform.isWindows); /// The flags passed to the executable used to run the script in this isolate. /// /// These are the command-line flags to the executable that precedes /// the script name. /// Provides a list every time the value is read. static List<String> get executableArguments => List.from(process.execArgv); /// The `--package-root` flag passed to the executable used to run the script /// in this isolate. /// /// If present, it specifies the directory where Dart packages are looked up. /// Is `null` if there is no `--package-root` flag. static String get packageRoot => throw UnsupportedError('Not supported in Node.'); /// The `--packages` flag passed to the executable used to run the script /// in this isolate. /// /// If present, it specifies a file describing how Dart packages are looked up. /// Is `null` if there is no `--packages` flag. static String get packageConfig => throw UnsupportedError('Not supported in Node.'); /// The version of the current Dart runtime. /// /// The value is a [semantic versioning](http://semver.org) /// string representing the version of the current Dart runtime, /// possibly followed by whitespace and other version and /// build details. static String get version => throw UnsupportedError('Not supported in Node.'); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io/src/stdout.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. 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' as io; import 'package:node_interop/tty.dart'; import 'streams.dart'; class Stdout extends NodeIOSink implements io.Stdout { Stdout(TTYWriteStream nativeStream) : super(nativeStream); @override TTYWriteStream get nativeInstance => super.nativeInstance; @override bool get hasTerminal => nativeInstance.isTTY; @override io.IOSink get nonBlocking => throw UnsupportedError('Not supported by Node.js'); @override // This is not strictly accurate but Dart's own implementation is a // best-effort solution as well, so we allow ourselves a bit of a slack here // too. bool get supportsAnsiEscapes => nativeInstance.getColorDepth() > 1; @override int get terminalColumns => nativeInstance.columns; @override int get terminalLines => nativeInstance.rows; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io/src/internet_address.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code // is governed by a BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io' as io; import 'dart:js'; import 'dart:typed_data'; import 'package:node_interop/dns.dart'; import 'package:node_interop/net.dart'; export 'dart:io' show InternetAddressType; /// An internet address. /// /// This object holds an internet address. If this internet address /// is the result of a DNS lookup, the address also holds the hostname /// used to make the lookup. /// An Internet address combined with a port number represents an /// endpoint to which a socket can connect or a listening socket can /// bind. class InternetAddress implements io.InternetAddress { static const int _IPV6_ADDR_LENGTH = 16; final String _host; final Uint8List _inAddr; @override final String address; @override String get host => _host ?? address; @override io.InternetAddressType get type => net.isIPv4(address) ? io.InternetAddressType.IPv4 : io.InternetAddressType.IPv6; InternetAddress._(this.address, [this._host]) : _inAddr = _inet_pton(address) { if (net.isIP(address) == 0) { throw ArgumentError('${address} is not valid.'); } } /// Creates a new [InternetAddress] from a numeric address. /// /// If the address in [address] is not a numeric IPv4 /// (dotted-decimal notation) or IPv6 (hexadecimal representation). /// address [ArgumentError] is thrown. factory InternetAddress(String address) => InternetAddress._(address); /// Lookup a host, returning a Future of a list of /// [InternetAddress]s. If [type] is [InternetAddressType.ANY], it /// will lookup both IP version 4 (IPv4) and IP version 6 (IPv6) /// addresses. If [type] is either [InternetAddressType.IPv4] or /// [InternetAddressType.IPv6] it will only lookup addresses of the /// specified type. The order of the list can, and most likely will, /// change over time. static Future<List<io.InternetAddress>> lookup(String host) { final completer = Completer<List<io.InternetAddress>>(); final options = DNSLookupOptions(all: true, verbatim: true); void handleLookup(error, result) { if (error != null) { completer.completeError(error); } else { final addresses = List<DNSAddress>.from(result); var list = addresses .map((item) => InternetAddress._(item.address, host)) .toList(growable: false); completer.complete(list); } } dns.lookup(host, options, allowInterop(handleLookup)); return completer.future; } @override bool get isLinkLocal { // Copied from dart:io switch (type) { case io.InternetAddressType.IPv4: // Checking for 169.254.0.0/16. return _inAddr[0] == 169 && _inAddr[1] == 254; case io.InternetAddressType.IPv6: // Checking for fe80::/10. return _inAddr[0] == 0xFE && (_inAddr[1] & 0xB0) == 0x80; } throw StateError('Unreachable'); } @override bool get isLoopback { // Copied from dart:io switch (type) { case io.InternetAddressType.IPv4: return _inAddr[0] == 127; case io.InternetAddressType.IPv6: for (var i = 0; i < _IPV6_ADDR_LENGTH - 1; i++) { if (_inAddr[i] != 0) return false; } return _inAddr[_IPV6_ADDR_LENGTH - 1] == 1; } throw StateError('Unreachable'); } @override bool get isMulticast { // Copied from dart:io switch (type) { case io.InternetAddressType.IPv4: // Checking for 224.0.0.0 through 239.255.255.255. return _inAddr[0] >= 224 && _inAddr[0] < 240; case io.InternetAddressType.IPv6: // Checking for ff00::/8. return _inAddr[0] == 0xFF; } throw StateError('Unreachable'); } @override Uint8List get rawAddress => Uint8List.fromList(_inAddr); @override Future<io.InternetAddress> reverse() { final completer = Completer<io.InternetAddress>(); void reverseResult(error, result) { if (error != null) { completer.completeError(error); } else { final hostnames = List<String>.from(result); completer.complete(InternetAddress._(address, hostnames.first)); } } dns.reverse(address, allowInterop(reverseResult)); return completer.future; } @override String toString() => '$address'; } const int _kColon = 58; /// Best-effort implementation of native inet_pton. /// /// This implementation assumes that [ip] address has been validated for /// correctness. Uint8List _inet_pton(String ip) { if (ip.contains(':')) { // ipv6 final result = Uint8List(16); // Special cases: if (ip == '::') return result; if (ip == '::1') return result..[15] = 1; const maxSingleColons = 7; final totalColons = ip.codeUnits.where((code) => code == _kColon).length; final hasDoubleColon = ip.contains('::'); final singleColons = hasDoubleColon ? (totalColons - 1) : totalColons; final skippedSegments = maxSingleColons - singleColons; final segment = StringBuffer(); var pos = 0; for (var i = 0; i < ip.length; i++) { if (i > 0 && ip[i] == ':' && ip[i - 1] == ':') { /// We don't need to set bytes to zeros as our [result] array is /// prefilled with zeros already, so we just need to shift our position /// forward. pos += 2 * skippedSegments; } else if (ip[i] == ':') { if (segment.isEmpty) segment.write('0'); final value = int.parse(segment.toString(), radix: 16); result[pos] = value ~/ 256; result[pos + 1] = value % 256; pos += 2; segment.clear(); } else { segment.write(ip[i]); } } // Don't forget about the last segment: if (segment.isEmpty) segment.write('0'); final value = int.parse(segment.toString(), radix: 16); result[pos] = value ~/ 256; result[pos + 1] = value % 256; return result; } else { // ipv4 return Uint8List.fromList(ip.split('.').map(int.parse).toList()); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io/src/streams.dart
// Copyright (c) 2018, Anatoly Pulyaevskiy. 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:convert'; import 'dart:io'; import 'dart:js'; import 'dart:typed_data'; import 'package:node_interop/node.dart'; import 'package:node_interop/stream.dart'; abstract class HasReadable { Readable get nativeInstance; } /// [Stream] wrapper around Node's [Readable] stream. class ReadableStream<T> extends Stream<T> implements HasReadable { /// Native `Readable` instance wrapped by this stream. /// /// It is not recommended to interact with this object directly. @override final Readable nativeInstance; final Function _convert; StreamController<T> _controller; /// Creates new [ReadableStream] which wraps [nativeInstance] of `Readable` /// type. /// /// The [convert] hook is called for each element of this stream before it's /// send to the listener. This allows implementations to convert raw /// JavaScript data in to desired Dart representation. If no convert /// function is provided then data is send to the listener unchanged. ReadableStream(this.nativeInstance, {T Function(dynamic data) convert}) : _convert = convert { _controller = StreamController( onPause: _onPause, onResume: _onResume, onCancel: _onCancel); nativeInstance.on('error', allowInterop(_errorHandler)); } void _errorHandler([JsError error]) { _controller.addError(error); } void _onPause() { nativeInstance.pause(); } void _onResume() { nativeInstance.resume(); } void _onCancel() { nativeInstance.removeAllListeners('data'); nativeInstance.removeAllListeners('end'); _controller.close(); } @override StreamSubscription<T> listen(void Function(T event) onData, {Function onError, void Function() onDone, bool cancelOnError}) { nativeInstance.on('data', allowInterop((chunk) { assert(chunk != null); var data = (_convert == null) ? chunk : _convert(chunk); _controller.add(data); })); nativeInstance.on('end', allowInterop(() { _controller.close(); })); return _controller.stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } } /// [StreamSink] wrapper around Node's [Writable] stream. class WritableStream<S> implements StreamSink<S> { /// Native JavaScript Writable wrapped by this stream. /// /// It is not recommended to interact with this object directly. final Writable nativeInstance; final Function _convert; Completer _drainCompleter; /// Creates [WritableStream] which wraps [nativeInstance] of `Writable` /// type. /// /// The [convert] hook is called for each element of this stream sink before /// it's added to the [nativeInstance]. This allows implementations to convert /// Dart objects in to values accepted by JavaScript streams. If no convert /// function is provided then data is sent to target unchanged. WritableStream(this.nativeInstance, {dynamic Function(S data) convert}) : _convert = convert { nativeInstance.on('error', allowInterop(_errorHandler)); } void _errorHandler(JsError error) { if (_drainCompleter != null && !_drainCompleter.isCompleted) { _drainCompleter.completeError(error); } else if (_closeCompleter != null && !_closeCompleter.isCompleted) { _closeCompleter.completeError(error); } else { throw error; } } /// Writes [data] to nativeStream. void _write(S data) { var completer = Completer(); void _flush([JsError error]) { if (completer.isCompleted) return; if (error != null) { completer.completeError(error); } else { completer.complete(); } } var chunk = (_convert == null) ? data : _convert(data); var isFlushed = nativeInstance.write(chunk, allowInterop(_flush)); if (!isFlushed) { // Keep track of the latest unflushed chunk of data. _drainCompleter = completer; } } /// Returns Future which completes once all buffered data is accepted by /// underlying target. /// /// If there is no buffered data to drain then returned Future completes in /// next event-loop iteration. Future get drain { if (_drainCompleter != null && !_drainCompleter.isCompleted) { return _drainCompleter.future; } return Future.value(); } @override void add(S data) { _write(data); } @override void addError(Object error, [StackTrace stackTrace]) { nativeInstance.emit('error', error); } @override Future addStream(Stream<S> stream) { throw UnimplementedError(); } @override Future close() { if (_closeCompleter != null) return _closeCompleter.future; _closeCompleter = Completer(); void end() { if (!_closeCompleter.isCompleted) _closeCompleter.complete(); } nativeInstance.end(allowInterop(end)); return _closeCompleter.future; } Completer _closeCompleter; @override Future get done => close(); } /// Writable stream of bytes, also accepts `String` values which are encoded /// with specified [Encoding]. class NodeIOSink extends WritableStream<List<int>> implements IOSink { static dynamic _nodeIoSinkConvert(List<int> data) { if (data is! Uint8List) { data = Uint8List.fromList(data); } return Buffer.from(data); } Encoding _encoding; NodeIOSink(Writable nativeStream, {Encoding encoding = utf8}) : super(nativeStream, convert: _nodeIoSinkConvert) { _encoding = encoding; } @override Encoding get encoding => _encoding; @override set encoding(Encoding value) { _encoding = value; } @override Future flush() => drain; @override void write(Object obj) { _write(encoding.encode(obj.toString())); } @override void writeAll(Iterable objects, [String separator = '']) { var data = objects.map((obj) => obj.toString()).join(separator); _write(encoding.encode(data)); } @override void writeCharCode(int charCode) { _write(encoding.encode(String.fromCharCode(charCode))); } @override void writeln([Object obj = '']) { _write(encoding.encode('$obj\n')); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io/src/file.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. 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:convert'; import 'dart:io' as io; import 'dart:js' as js; import 'dart:typed_data'; import 'package:node_interop/buffer.dart'; import 'package:node_interop/fs.dart'; import 'package:node_interop/js.dart'; import 'package:node_interop/path.dart' as node_path; import 'package:node_interop/util.dart'; import 'file_system_entity.dart'; import 'streams.dart'; class _ReadStream extends ReadableStream<Uint8List> { _ReadStream(ReadStream nativeStream) : super(nativeStream, convert: (chunk) => Uint8List.fromList(chunk)); } class _WriteStream extends NodeIOSink { _WriteStream(WriteStream nativeStream, Encoding encoding) : super(nativeStream, encoding: encoding); } /// A reference to a file on the file system. /// /// A File instance is an object that holds a [path] on which operations can /// be performed. /// You can get the parent directory of the file using the getter [parent], /// a property inherited from [FileSystemEntity]. /// /// Create a File object with a pathname to access the specified file on the /// file system from your program. /// /// var myFile = File('file.txt'); /// /// The File class contains methods for manipulating files and their contents. /// Using methods in this class, you can open and close files, read to and write /// from them, create and delete them, and check for their existence. /// /// When reading or writing a file, you can use streams (with [openRead]), /// random access operations (with [open]), /// or convenience methods such as [readAsString], /// /// Most methods in this class occur in synchronous and asynchronous pairs, /// for example, [readAsString] and [readAsStringSync]. /// Unless you have a specific reason for using the synchronous version /// of a method, prefer the asynchronous version to avoid blocking your program. /// /// ## If path is a link /// /// If [path] is a symbolic link, rather than a file, /// then the methods of File operate on the ultimate target of the /// link, except for [delete] and [deleteSync], which operate on /// the link. /// /// ## Read from a file /// /// The following code sample reads the entire contents from a file as a string /// using the asynchronous [readAsString] method: /// /// import 'dart:async'; /// /// import 'package:node_io/node_io.dart'; /// /// void main() { /// File('file.txt').readAsString().then((String contents) { /// print(contents); /// }); /// } /// /// A more flexible and useful way to read a file is with a [Stream]. /// Open the file with [openRead], which returns a stream that /// provides the data in the file as chunks of bytes. /// Listen to the stream for data and process as needed. /// You can use various transformers in succession to manipulate the /// data into the required format or to prepare it for output. /// /// You might want to use a stream to read large files, /// to manipulate the data with transformers, /// or for compatibility with another API. /// /// import 'dart:convert'; /// import 'dart:async'; /// /// import 'package:node_io/node_io.dart'; /// /// main() { /// final file = File('file.txt'); /// Stream<List<int>> inputStream = file.openRead(); /// /// inputStream /// .transform(utf8.decoder) // Decode bytes to UTF-8. /// .transform(LineSplitter()) // Convert stream to individual lines. /// .listen((String line) { // Process results. /// print('$line: ${line.length} bytes'); /// }, /// onDone: () { print('File is now closed.'); }, /// onError: (e) { print(e.toString()); }); /// } /// /// ## Write to a file /// /// To write a string to a file, use the [writeAsString] method: /// /// import 'package:node_io/node_io.dart'; /// /// void main() { /// final filename = 'file.txt'; /// File(filename).writeAsString('some content') /// .then((File file) { /// // Do something with the file. /// }); /// } /// /// You can also write to a file using a [Stream]. Open the file with /// [openWrite], which returns an [io.IOSink] to which you can write data. /// Be sure to close the sink with the [io.IOSink.close] method. /// /// import 'package:node_io/node_io.dart'; /// /// void main() { /// var file = File('file.txt'); /// var sink = file.openWrite(); /// sink.write('FILE ACCESSED ${DateTime.now()}\n'); /// /// // Close the IOSink to free system resources. /// sink.close(); /// } class File extends FileSystemEntity implements io.File { @override final String path; File(this.path); @override File get absolute => File(_absolutePath); String get _absolutePath => node_path.path.resolve(path); @override Future<File> copy(String newPath) { final completer = Completer<File>(); void callback(err) { if (err != null) { completer.completeError(err); } else { completer.complete(File(newPath)); } } final jsCallback = js.allowInterop(callback); fs.copyFile(_absolutePath, newPath, 0, jsCallback); return completer.future; } @override File copySync(String newPath) { fs.copyFileSync(_absolutePath, newPath, 0); return File(newPath); } @override Future<File> create({bool recursive = false}) { // write an empty file final completer = Completer<File>(); void callback(err, [fd]) { if (err != null) { completer.completeError(err); } else { fs.close(fd, js.allowInterop((err) { if (err != null) { completer.completeError(err); } else { completer.complete(this); } })); } } final jsCallback = js.allowInterop(callback); fs.open(_absolutePath, 'w', jsCallback); return completer.future; } @override void createSync({bool recursive = false}) { final fd = fs.openSync(_absolutePath, 'w'); fs.closeSync(fd); } @override Future<io.FileSystemEntity> delete({bool recursive = false}) { if (recursive) { return Future.error( UnsupportedError('Recursive delete is not supported by Node API')); } final completer = Completer<File>(); void callback(err) { if (err != null) { completer.completeError(err); } else { completer.complete(this); } } final jsCallback = js.allowInterop(callback); fs.unlink(_absolutePath, jsCallback); return completer.future; } @override void deleteSync({bool recursive = false}) { if (recursive) { throw UnsupportedError('Recursive delete is not supported by Node API'); } fs.unlinkSync(_absolutePath); } @override Future<bool> exists() async { var stat = await FileStat.stat(path); return stat.type == io.FileSystemEntityType.file; } @override bool existsSync() { var stat = FileStat.statSync(path); return stat.type == io.FileSystemEntityType.file; } @override Future<DateTime> lastAccessed() => FileStat.stat(path).then((_) => _.accessed); @override DateTime lastAccessedSync() => FileStat.statSync(path).accessed; @override Future<DateTime> lastModified() => FileStat.stat(path).then((_) => _.modified); @override DateTime lastModifiedSync() => FileStat.statSync(path).modified; @override Future<int> length() => FileStat.stat(path).then((_) => _.size); @override int lengthSync() => FileStat.statSync(path).size; @override Future<io.RandomAccessFile> open({io.FileMode mode = io.FileMode.read}) => _RandomAccessFile.open(path, mode); @override Stream<Uint8List> openRead([int start, int end]) { var options = ReadStreamOptions(); if (start != null) options.start = start; if (end != null) options.end = end; var nativeStream = fs.createReadStream(path, options); return _ReadStream(nativeStream); } @override io.RandomAccessFile openSync({io.FileMode mode = io.FileMode.read}) => _RandomAccessFile.openSync(path, mode); @override io.IOSink openWrite( {io.FileMode mode = io.FileMode.write, Encoding encoding = utf8}) { assert(mode == io.FileMode.write || mode == io.FileMode.append); var flags = (mode == io.FileMode.append) ? 'a+' : 'w'; var options = WriteStreamOptions(flags: flags); var stream = fs.createWriteStream(path, options); return _WriteStream(stream, encoding); } @override Future<Uint8List> readAsBytes() => openRead().fold( <int>[], (List<int> previous, List<int> element) => previous ..addAll(element)).then((List<int> list) => Uint8List.fromList(list)); @override Uint8List readAsBytesSync() { final List<int> buffer = fs.readFileSync(path); return Uint8List.fromList(buffer); } @override Future<List<String>> readAsLines({Encoding encoding = utf8}) { return encoding.decoder.bind(openRead()).transform(LineSplitter()).toList(); } @override List<String> readAsLinesSync({Encoding encoding = utf8}) { return utf8.decode(readAsBytesSync()).split('\n'); } @override Future<String> readAsString({Encoding encoding = utf8}) async { var bytes = await readAsBytes(); return encoding.decode(bytes); } @override String readAsStringSync({Encoding encoding = utf8}) { return encoding.decode(readAsBytesSync()); } @override Future<File> rename(String newPath) { final completer = Completer<File>(); void cb(err) { if (err != null) { completer.completeError(err); } else { completer.complete(File(newPath)); } } final jsCallback = js.allowInterop(cb); fs.rename(path, newPath, jsCallback); return completer.future; } @override File renameSync(String newPath) { fs.renameSync(path, newPath); return File(newPath); } @override Future<void> setLastAccessed(DateTime time) async { return _utimes(atime: Date(time.millisecondsSinceEpoch)); } @override void setLastAccessedSync(DateTime time) { _utimesSync(atime: Date(time.millisecondsSinceEpoch)); } @override Future<void> setLastModified(DateTime time) async { return _utimes(mtime: Date(time.millisecondsSinceEpoch)); } @override void setLastModifiedSync(DateTime time) { _utimesSync(mtime: Date(time.millisecondsSinceEpoch)); } Future<void> _utimes({Date atime, Date mtime}) async { final currentStat = await stat(); atime ??= Date(currentStat.accessed.millisecondsSinceEpoch); mtime ??= Date(currentStat.modified.millisecondsSinceEpoch); final completer = Completer(); void cb([err]) { if (err != null) { completer.completeError(err); } else { completer.complete(); } } final jsCallback = js.allowInterop(cb); fs.utimes(_absolutePath, atime, mtime, jsCallback); return completer.future; } void _utimesSync({Date atime, Date mtime}) { final currentStat = statSync(); atime ??= Date(currentStat.accessed.millisecondsSinceEpoch); mtime ??= Date(currentStat.modified.millisecondsSinceEpoch); fs.utimesSync(_absolutePath, atime, mtime); } @override Future<io.File> writeAsBytes(List<int> bytes, {io.FileMode mode = io.FileMode.write, bool flush = false}) async { var sink = openWrite(mode: mode); sink.add(bytes); if (flush == true) { await sink.flush(); } await sink.close(); return this; } @override void writeAsBytesSync(List<int> bytes, {io.FileMode mode = io.FileMode.write, bool flush = false}) { var flag = _RandomAccessFile.fileModeToJsFlags(mode); var options = jsify({'flag': flag}); fs.writeFileSync(_absolutePath, Buffer.from(bytes), options); } @override Future<io.File> writeAsString(String contents, {io.FileMode mode = io.FileMode.write, Encoding encoding = utf8, bool flush = false}) async { var sink = openWrite(mode: mode, encoding: encoding); sink.write(contents); if (flush == true) { await sink.flush(); } await sink.close(); return this; } @override void writeAsStringSync(String contents, {io.FileMode mode = io.FileMode.write, Encoding encoding = utf8, bool flush = false}) { fs.writeFileSync(_absolutePath, contents); } @override String toString() { return "File: '$path'"; } } class _RandomAccessFile implements io.RandomAccessFile { /// File Descriptor final int fd; /// File path. @override final String path; bool _asyncDispatched = false; int _position = 0; _RandomAccessFile(this.fd, this.path); static Future<io.RandomAccessFile> open(String path, io.FileMode mode) { final completer = Completer<_RandomAccessFile>(); void cb(err, [fd]) { if (err != null) { completer.completeError(err); } else { completer.complete(_RandomAccessFile(fd, path)); } } final jsCallback = js.allowInterop(cb); fs.open(path, fileModeToJsFlags(mode), jsCallback); return completer.future; } static io.RandomAccessFile openSync(String path, io.FileMode mode) { final fd = fs.openSync(path, fileModeToJsFlags(mode)); return _RandomAccessFile(fd, path); } static String fileModeToJsFlags(io.FileMode mode) { switch (mode) { case io.FileMode.read: return 'r'; case io.FileMode.write: return 'w+'; case io.FileMode.writeOnly: return 'w'; case io.FileMode.append: return 'a+'; case io.FileMode.writeOnlyAppend: return 'a'; default: throw UnsupportedError('$mode is not supported'); } } @override Future<io.RandomAccessFile> close() { return _dispatch(() { var completer = Completer<io.RandomAccessFile>(); void callback(err) { if (err == null) { completer.complete(this); } else { completer.completeError(err); } } var jsCallback = js.allowInterop(callback); fs.close(fd, jsCallback); return completer.future; }); } @override void closeSync() { _checkAvailable(); fs.closeSync(fd); } @override Future<io.RandomAccessFile> flush() { return _dispatch(() { return Future.value(this); }); } @override void flushSync() { _checkAvailable(); // Still check for async ops for consistency. // no-op } @override Future<int> length() { return _dispatch(() { final file = File(path); return file.stat().then((stat) => stat.size); }); } @override int lengthSync() { _checkAvailable(); final file = File(path); return file.statSync().size; } @override Future<io.RandomAccessFile> lock( [io.FileLock mode = io.FileLock.exclusive, int start = 0, int end = -1]) { throw UnsupportedError('File locks are not supported by Node.js'); } @override void lockSync( [io.FileLock mode = io.FileLock.exclusive, int start = 0, int end = -1]) { throw UnsupportedError('File locks are not supported by Node.js'); } @override Future<int> position() { return _dispatch(() => Future<int>.value(_position)); } @override int positionSync() { _checkAvailable(); return _position; } @override Future<Uint8List> read(int bytes) { return _dispatch(() { var buffer = Buffer.alloc(bytes); final completer = Completer<Uint8List>(); void cb(err, bytesRead, buffer) { if (err != null) { completer.completeError(err); } else { assert(bytesRead == bytes); _position += bytes; completer.complete(Uint8List.fromList(buffer)); } } final jsCallback = js.allowInterop(cb); fs.read(fd, buffer, 0, bytes, _position, jsCallback); return completer.future; }); } @override Future<int> readByte() { return read(1).then((bytes) => bytes.single); } @override int readByteSync() { _checkAvailable(); return readSync(1).single; } @override Future<int> readInto(List<int> buffer, [int start = 0, int end]) { end ??= buffer.length; var bytes = end - start; if (bytes == 0) return Future.value(0); return read(bytes).then((readBytes) { buffer.setRange(start, end, readBytes); return readBytes.length; }); } @override int readIntoSync(List<int> buffer, [int start = 0, int end]) { _checkAvailable(); end ??= buffer.length; var bytes = end - start; if (bytes == 0) return 0; var readBytes = readSync(bytes); buffer.setRange(start, end, readBytes); return bytes; } @override Uint8List readSync(int bytes) { _checkAvailable(); Object buffer = Buffer.alloc(bytes); final bytesRead = fs.readSync(fd, buffer, 0, bytes, _position); assert(bytesRead == bytes); _position += bytes; return Uint8List.fromList(buffer); } @override Future<io.RandomAccessFile> setPosition(int position) { throw UnsupportedError('Setting position is not supported by Node.js'); } @override void setPositionSync(int position) { throw UnsupportedError('Setting position is not supported by Node.js'); } @override Future<io.RandomAccessFile> truncate(int length) { return _dispatch(() { final completer = Completer<io.RandomAccessFile>(); void cb([err]) { if (err != null) { completer.completeError(err); } else { completer.complete(this); } } final jsCallback = js.allowInterop(cb); fs.ftruncate(fd, length, jsCallback); return completer.future; }); } @override void truncateSync(int length) { _checkAvailable(); fs.ftruncateSync(fd, length); } @override Future<io.RandomAccessFile> unlock([int start = 0, int end = -1]) { throw UnsupportedError('File locks are not supported by Node.js'); } @override void unlockSync([int start = 0, int end = -1]) { throw UnsupportedError('File locks are not supported by Node.js'); } @override Future<io.RandomAccessFile> writeByte(int value) { return _dispatch(() { final completer = Completer<io.RandomAccessFile>(); void cb(err, bytesWritten, buffer) { if (err != null) { completer.completeError(err); } else { completer.complete(this); } } final jsCallback = js.allowInterop(cb); fs.write(fd, Buffer.from([value]), jsCallback); return completer.future; }); } @override int writeByteSync(int value) { _checkAvailable(); return fs.writeSync(fd, Buffer.from([value])); } @override Future<io.RandomAccessFile> writeFrom(List<int> buffer, [int start = 0, int end]) { return _dispatch(() { final completer = Completer<io.RandomAccessFile>(); void cb(err, bytesWritten, buffer) { if (err != null) { completer.completeError(err); } else { completer.complete(this); } } final jsCallback = js.allowInterop(cb); end ??= buffer.length; final length = end - start; fs.write(fd, Buffer.from(buffer), start, length, jsCallback); return completer.future; }); } @override void writeFromSync(List<int> buffer, [int start = 0, int end]) { _checkAvailable(); end ??= buffer.length; final length = end - start; fs.writeSync(fd, Buffer.from(buffer), start, length); } @override Future<io.RandomAccessFile> writeString(String string, {Encoding encoding = utf8}) { return writeFrom(encoding.encode(string)); } @override void writeStringSync(String string, {Encoding encoding = utf8}) { _checkAvailable(); writeFromSync(encoding.encode(string)); } bool _closed = false; Future<T> _dispatch<T>(Future<T> Function() request, {bool markClosed = false}) { if (_closed) { return Future.error(io.FileSystemException('File closed', path)); } if (_asyncDispatched) { var msg = 'An async operation is currently pending'; return Future.error(io.FileSystemException(msg, path)); } if (markClosed) { // Set closed to true to ensure that no more async requests can be issued // for this file. _closed = true; } _asyncDispatched = true; return request().whenComplete(() { _asyncDispatched = false; }); } void _checkAvailable() { if (_asyncDispatched) { throw io.FileSystemException( 'An async operation is currently pending', path); } if (_closed) { throw io.FileSystemException('File closed', path); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io/src/link.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code // is governed by a BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io' as io; import 'dart:js' as js; import 'dart:typed_data'; import 'package:node_interop/fs.dart'; import 'package:node_interop/path.dart' as node_path; import 'directory.dart'; import 'file_system_entity.dart'; /// Link objects are references to filesystem links. class Link extends FileSystemEntity implements io.Link { @override final String path; Link(this.path); factory Link.fromRawPath(Uint8List rawPath) { // TODO: implement fromRawPath throw UnimplementedError(); } /// Creates a [Link] object. /// /// If [path] is a relative path, it will be interpreted relative to the /// current working directory (see [Directory.current]), when used. /// /// If [path] is an absolute path, it will be immune to changes to the /// current working directory. factory Link.fromUri(Uri uri) => Link(uri.toFilePath()); @override Future<bool> exists() async { var stat = await FileStat.stat(path); return stat.type == io.FileSystemEntityType.link; } @override bool existsSync() { var stat = FileStat.statSync(path); return stat.type == io.FileSystemEntityType.link; } @override Link get absolute => Link(_absolutePath); String get _absolutePath => node_path.path.resolve(path); @override Future<Link> create(String target, {bool recursive = false}) { if (recursive) { throw UnsupportedError('Recursive flag not supported by Node.js'); } final completer = Completer<Link>(); void cb([err]) { if (err != null) { completer.completeError(err); } else { completer.complete(this); } } final jsCallback = js.allowInterop(cb); fs.symlink(target, path, jsCallback); return completer.future; } @override void createSync(String target, {bool recursive = false}) { if (recursive) { throw UnsupportedError('Recursive flag not supported by Node.js'); } fs.symlinkSync(target, path); } @override Future<Link> delete({bool recursive = false}) { if (recursive) { return Future.error( UnsupportedError('Recursive flag is not supported by Node.js')); } final completer = Completer<Link>(); void callback(err) { if (err != null) { completer.completeError(err); } else { completer.complete(this); } } final jsCallback = js.allowInterop(callback); fs.unlink(_absolutePath, jsCallback); return completer.future; } @override void deleteSync({bool recursive = false}) { if (recursive) { throw UnsupportedError('Recursive flag is not supported by Node.js'); } fs.unlinkSync(_absolutePath); } @override Future<Link> rename(String newPath) { final completer = Completer<Link>(); void cb(err) { if (err != null) { completer.completeError(err); } else { completer.complete(Link(newPath)); } } final jsCallback = js.allowInterop(cb); fs.rename(path, newPath, jsCallback); return completer.future; } @override Link renameSync(String newPath) { fs.renameSync(path, newPath); return Link(newPath); } @override Future<String> target() { final completer = Completer<String>(); void cb(err, String target) { if (err != null) { completer.completeError(err); } else { completer.complete(target); } } final jsCallback = js.allowInterop(cb); fs.readlink(path, jsCallback); return completer.future; } @override String targetSync() { return fs.readlinkSync(path); } @override Future<Link> update(String target) { return delete().then((link) => link.create(target)); } @override void updateSync(String target) { deleteSync(); createSync(target); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io/src/stdin.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. 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:convert'; import 'dart:io' as io; import 'package:node_interop/tty.dart'; import 'streams.dart'; class Stdin extends ReadableStream<List<int>> implements io.Stdin { Stdin(TTYReadStream nativeInstance) : super(nativeInstance); @override TTYReadStream get nativeInstance => super.nativeInstance; @override bool echoMode; @override bool lineMode; @override bool get hasTerminal => nativeInstance.isTTY; @override int readByteSync() { return null; } @override String readLineSync( {Encoding encoding = io.systemEncoding, bool retainNewlines = false}) { // TODO: implement io.systemEncoding (!) // TODO: implement readLineSync return null; } @override // TODO: implement supportsAnsiEscapes bool get supportsAnsiEscapes => null; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io/src/file_system_entity.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code // is governed by a BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io' as io; import 'dart:js' as js; import 'package:node_interop/fs.dart'; import 'package:node_interop/path.dart' as node_path; import 'directory.dart'; import 'platform.dart'; abstract class FileSystemEntity implements io.FileSystemEntity { static final RegExp _absoluteWindowsPathPattern = RegExp(r'^(\\\\|[a-zA-Z]:[/\\])'); @override bool get isAbsolute => node_path.path.isAbsolute(path); @override String toString() => "$runtimeType: '$path'"; static final RegExp _parentRegExp = Platform.isWindows ? RegExp(r'[^/\\][/\\]+[^/\\]') : RegExp(r'[^/]/+[^/]'); static String parentOf(String path) { var rootEnd = -1; if (Platform.isWindows) { if (path.startsWith(_absoluteWindowsPathPattern)) { // Root ends at first / or \ after the first two characters. rootEnd = path.indexOf(RegExp(r'[/\\]'), 2); if (rootEnd == -1) return path; } else if (path.startsWith('\\') || path.startsWith('/')) { rootEnd = 0; } } else if (path.startsWith('/')) { rootEnd = 0; } // Ignore trailing slashes. // All non-trivial cases have separators between two non-separators. var pos = path.lastIndexOf(_parentRegExp); if (pos > rootEnd) { return path.substring(0, pos + 1); } else if (rootEnd > -1) { return path.substring(0, rootEnd + 1); } else { return '.'; } } @override io.Directory get parent => Directory(parentOf(path)); @override Future<String> resolveSymbolicLinks() { var completer = Completer<String>(); void callback(err, String resolvedPath) { if (err == null) { completer.complete(resolvedPath); } else { completer.completeError(err); } } var jsCallback = js.allowInterop(callback); fs.realpath(path, jsCallback); return completer.future; } @override String resolveSymbolicLinksSync() => fs.realpathSync(path); @override Future<FileStat> stat() => FileStat.stat(path); @override FileStat statSync() => FileStat.statSync(path); @override Uri get uri => Uri.file(path, windows: Platform.isWindows); @override Stream<io.FileSystemEvent> watch( {int events = io.FileSystemEvent.all, bool recursive = false}) { // TODO: implement watch throw UnimplementedError(); } } /// A FileStat object represents the result of calling the POSIX stat() function /// on a file system object. It is an immutable object, representing the /// snapshotted values returned by the stat() call. class FileStat implements io.FileStat { @override final DateTime changed; @override final DateTime modified; @override final DateTime accessed; @override final io.FileSystemEntityType type; @override final int mode; @override final int size; FileStat._internal(this.changed, this.modified, this.accessed, this.type, this.mode, this.size); const FileStat._internalNotFound() : changed = null, modified = null, accessed = null, type = io.FileSystemEntityType.notFound, mode = 0, size = -1; factory FileStat._fromNodeStats(Stats stats) { var type = io.FileSystemEntityType.notFound; if (stats.isDirectory()) { type = io.FileSystemEntityType.directory; } else if (stats.isFile()) { type = io.FileSystemEntityType.file; } else if (stats.isSymbolicLink()) { type = io.FileSystemEntityType.link; } return FileStat._internal( DateTime.parse(stats.ctime.toISOString()), DateTime.parse(stats.mtime.toISOString()), DateTime.parse(stats.atime.toISOString()), type, stats.mode, stats.size, ); } /// Asynchronously calls the operating system's stat() function on [path]. /// /// Returns a Future which completes with a [FileStat] object containing /// the data returned by stat(). If the call fails, completes the future with a /// [FileStat] object with `.type` set to FileSystemEntityType.notFound and /// the other fields invalid. static Future<FileStat> stat(String path) { var completer = Completer<FileStat>(); // stats has to be an optional param despite what the documentation says... void callback(err, [stats]) { if (err == null) { completer.complete(FileStat._fromNodeStats(stats)); } else { completer.complete(FileStat._internalNotFound()); } } var jsCallback = js.allowInterop(callback); fs.lstat(path, jsCallback); return completer.future; } /// Calls the operating system's stat() function on [path]. /// /// Returns a [FileStat] object containing the data returned by stat(). /// If the call fails, returns a [FileStat] object with .type set to /// FileSystemEntityType.notFound and the other fields invalid. static FileStat statSync(String path) { try { return FileStat._fromNodeStats(fs.lstatSync(path)); } catch (_) { return FileStat._internalNotFound(); } } @override String modeString() { var permissions = mode & 0xFFF; var codes = const ['---', '--x', '-w-', '-wx', 'r--', 'r-x', 'rw-', 'rwx']; var result = []; if ((permissions & 0x800) != 0) result.add('(suid) '); if ((permissions & 0x400) != 0) result.add('(guid) '); if ((permissions & 0x200) != 0) result.add('(sticky) '); result ..add(codes[(permissions >> 6) & 0x7]) ..add(codes[(permissions >> 3) & 0x7]) ..add(codes[permissions & 0x7]); return result.join(); } @override String toString() => ''' FileStat: type $type changed $changed modified $modified accessed $accessed mode ${modeString()} size $size'''; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io/src/http_headers.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. 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' as io; import 'dart:js_util' as js_util; import 'package:node_interop/http.dart'; import 'package:node_interop/js.dart'; import 'package:node_interop/util.dart'; /// List of HTTP header names which can only have single value. const _singleValueHttpHeaders = [ 'age', 'authorization', 'content-length', 'content-type', 'date', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent', ]; class ResponseHttpHeaders extends HttpHeaders { ResponseHttpHeaders(this._nativeResponse); final ServerResponse _nativeResponse; bool _mutable = true; /// Collection of header names set in native response object. final Set<String> _headerNames = <String>{}; void finalize() { _mutable = false; } void _checkMutable() { if (_mutable == false) { throw io.HttpException('HTTP headers are not mutable.'); } } @override dynamic _getHeader(String name) => _nativeResponse.getHeader(name); @override Iterable<String> _getHeaderNames() => _headerNames; @override void _removeHeader(String name) { _checkMutable(); _nativeResponse.removeHeader(name); _headerNames.remove(name); } @override void _setHeader(String name, value) { _checkMutable(); _nativeResponse.setHeader(name, value); _headerNames.add(name); } } class RequestHttpHeaders extends HttpHeaders { final IncomingMessage _request; RequestHttpHeaders(this._request); @override dynamic _getHeader(String name) => js_util.getProperty(_request.headers, name); @override void _setHeader(String name, dynamic value) => throw io.HttpException('HTTP headers are not mutable.'); @override void _removeHeader(String name) => throw io.HttpException('HTTP headers are not mutable.'); @override Iterable<String> _getHeaderNames() => List<String>.from(objectKeys(_request.headers)); } /// Proxy to native JavaScript HTTP headers. abstract class HttpHeaders implements io.HttpHeaders { dynamic _getHeader(String name); void _setHeader(String name, value); void _removeHeader(String name); Iterable<String> _getHeaderNames(); dynamic getHeader(String name) => _getHeader(name); @override bool get chunkedTransferEncoding => _getHeader(io.HttpHeaders.transferEncodingHeader) == 'chunked'; @override set chunkedTransferEncoding(bool chunked) { if (chunked) { _setHeader(io.HttpHeaders.transferEncodingHeader, 'chunked'); } else { _removeHeader(io.HttpHeaders.transferEncodingHeader); } } @override int get contentLength { var value = _getHeader(io.HttpHeaders.contentLengthHeader); if (value != null) return int.parse(value); return 0; } @override set contentLength(int length) { _setHeader(io.HttpHeaders.contentLengthHeader, length); } @override io.ContentType get contentType { if (_contentType != null) return _contentType; String value = _getHeader(io.HttpHeaders.contentTypeHeader); if (value == null || value.isEmpty) return null; var types = value.split(','); _contentType = io.ContentType.parse(types.first); return _contentType; } io.ContentType _contentType; @override set contentType(io.ContentType type) { _setHeader(io.HttpHeaders.contentTypeHeader, type.toString()); } @override DateTime get date { String value = _getHeader(io.HttpHeaders.dateHeader); if (value == null || value.isEmpty) return null; try { return io.HttpDate.parse(value); } on Exception { return null; } } @override set date(DateTime date) { _setHeader(io.HttpHeaders.dateHeader, io.HttpDate.format(date)); } @override DateTime get expires { String value = _getHeader(io.HttpHeaders.expiresHeader); if (value == null || value.isEmpty) return null; try { return io.HttpDate.parse(value); } on Exception { return null; } } @override set expires(DateTime expires) { _setHeader(io.HttpHeaders.expiresHeader, io.HttpDate.format(expires)); } @override String get host { String value = _getHeader(io.HttpHeaders.hostHeader); if (value != null) { return value.split(':').first; } return null; } @override set host(String host) { var hostAndPort = host; var _port = port; if (_port != null) { hostAndPort = '$host:$_port'; } _setHeader(io.HttpHeaders.hostHeader, hostAndPort); } @override int get port { String value = _getHeader(io.HttpHeaders.hostHeader); if (value != null) { var parts = value.split(':'); if (parts.length == 2) return int.parse(parts.last); } return null; } @override set port(int value) { var hostAndPort = host; if (value != null) { hostAndPort = '$host:$value'; } _setHeader(io.HttpHeaders.hostHeader, hostAndPort); } @override DateTime get ifModifiedSince { String value = _getHeader(io.HttpHeaders.ifModifiedSinceHeader); if (value == null || value.isEmpty) return null; try { return io.HttpDate.parse(value); } on Exception { return null; } } @override set ifModifiedSince(DateTime ifModifiedSince) { _setHeader(io.HttpHeaders.ifModifiedSinceHeader, io.HttpDate.format(ifModifiedSince)); } @override bool get persistentConnection { var connection = _getHeader(io.HttpHeaders.connectionHeader); return (connection == 'keep-alive'); } @override set persistentConnection(bool persistentConnection) { var value = persistentConnection ? 'keep-alive' : 'close'; _setHeader(io.HttpHeaders.connectionHeader, value); } bool _isMultiValue(String name) => !_singleValueHttpHeaders.contains(name); @override List<String> operator [](String name) { name = name.toLowerCase(); var value = _getHeader(name); if (value != null) { if (value is String) { return _isMultiValue(name) ? value.split(',') : [value]; } else { // Node.js treats `set-cookie` differently from other headers and // composes all values in an array. return List.unmodifiable(value); } } return null; } @override String value(String name) { final values = this[name]; if (values == null) return null; if (values.length > 1) { throw io.HttpException('More than one value for header $name'); } return values[0]; } @override void add(String name, Object value, {bool preserveHeaderCase = false}) { if (preserveHeaderCase ?? false) { // new since 2.8 // not supported on node throw UnsupportedError('HttpHeaders.add(preserveHeaderCase: true)'); } else { final existingValues = this[name]; var values = existingValues != null ? List.from(existingValues) : []; values.add(value.toString()); _setHeader(name, values); } } @override void clear() { var names = _getHeaderNames(); for (var name in names) { _removeHeader(name); } } @override void forEach(void Function(String name, List<String> values) f) { var names = _getHeaderNames(); names.forEach((String name) { f(name, this[name]); }); } @override void noFolding(String name) { throw UnsupportedError('Folding is not supported for Node.'); } @override void remove(String name, Object value) { // TODO: this could actually be implemented on our side now. throw UnsupportedError( 'Removing individual values not supported for Node.'); } @override void removeAll(String name) { _removeHeader(name); } @override void set(String name, Object value, {bool preserveHeaderCase = false}) { if (preserveHeaderCase ?? false) { // new since 2.8 // not supported on node throw UnsupportedError('HttpHeaders.set(preserveHeaderCase: true)'); } else { _setHeader(name, jsify(value)); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io/src/directory.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code // is governed by a BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io' as io; import 'dart:js' as js; import 'package:node_interop/fs.dart'; import 'package:node_interop/node.dart'; import 'package:node_interop/os.dart'; import 'package:node_interop/path.dart' as node_path; import 'package:path/path.dart'; import 'file.dart'; import 'file_system_entity.dart'; import 'link.dart'; import 'platform.dart'; /// A reference to a directory (or _folder_) on the file system. /// /// A Directory instance is an object holding a [path] on which operations can /// be performed. The path to the directory can be [absolute] or relative. /// You can get the parent directory using the getter [parent], /// a property inherited from [FileSystemEntity]. /// /// In addition to being used as an instance to access the file system, /// Directory has a number of static properties, such as [systemTemp], /// which gets the system's temporary directory, and the getter and setter /// [current], which you can use to access or change the current directory. /// /// Create a new Directory object with a pathname to access the specified /// directory on the file system from your program. /// /// var myDir = Directory('myDir'); /// /// Most methods in this class occur in synchronous and asynchronous pairs, /// for example, [create] and [createSync]. /// Unless you have a specific reason for using the synchronous version /// of a method, prefer the asynchronous version to avoid blocking your program. /// /// ## Create a directory /// /// The following code sample creates a directory using the [create] method. /// By setting the `recursive` parameter to true, you can create the /// named directory and all its necessary parent directories, /// if they do not already exist. /// /// import 'package:node_io/node_io.dart'; /// /// void main() { /// // Creates dir/ and dir/subdir/. /// Directory('dir/subdir').create(recursive: true) /// // The created directory is returned as a Future. /// .then((Directory directory) { /// print(directory.path); /// }); /// } /// /// ## List a directory /// /// Use the [list] or [listSync] methods to get the files and directories /// contained by a directory. /// Set `recursive` to true to recursively list all subdirectories. /// Set `followLinks` to true to follow symbolic links. /// The list method returns a [Stream] that provides FileSystemEntity /// objects. Use the listen callback function to process each object /// as it become available. /// /// import 'package:node_io/node_io.dart'; /// /// void main() { /// // Get the system temp directory. /// var systemTempDir = Directory.systemTemp; /// /// // List directory contents, recursing into sub-directories, /// // but not following symbolic links. /// systemTempDir.list(recursive: true, followLinks: false) /// .listen((FileSystemEntity entity) { /// print(entity.path); /// }); /// } class Directory extends FileSystemEntity implements io.Directory { @override final String path; Directory(this.path); /// Creates a directory object pointing to the current working /// directory. static io.Directory get current => Directory(process.cwd()); /// Sets the current working directory of the Dart process including /// all running isolates. The new value set can be either a [Directory] /// or a [String]. /// /// The new value is passed to the OS's system call unchanged, so a /// relative path passed as the new working directory will be /// resolved by the OS. static set current(path) { path = (path is io.Directory) ? path.path : path; assert(path is String); process.chdir(path); } /// Gets the system temp directory. /// /// Gets the directory provided by the operating system for creating /// temporary files and directories in. /// The location of the system temp directory is platform-dependent, /// and may be set by an environment variable. static io.Directory get systemTemp { return Directory(os.tmpdir()); } @override io.Directory get absolute => Directory(node_path.path.resolve(path)); @override Future<bool> exists() => FileStat.stat(path) .then((stat) => stat.type == io.FileSystemEntityType.directory); @override bool existsSync() => FileStat.statSync(path).type == io.FileSystemEntityType.directory; @override Future<io.FileSystemEntity> delete({bool recursive = false}) { if (recursive) { return Future.error( UnsupportedError('Recursive delete is not supported by Node API')); } final completer = Completer<Directory>(); void callback([error]) { if (error == null) { completer.complete(this); } else { completer.completeError(error); } } final jsCallback = js.allowInterop(callback); fs.rmdir(path, jsCallback); return completer.future; } @override void deleteSync({bool recursive = false}) { if (recursive) { throw UnsupportedError('Recursive delete is not supported in Node.'); } fs.rmdirSync(path); } @override Stream<FileSystemEntity> list( {bool recursive = false, bool followLinks = true}) { if (recursive) { throw UnsupportedError('Recursive list is not supported in Node.'); } final controller = StreamController<FileSystemEntity>(); void callback(err, [files]) { if (err != null) { controller.addError(err); controller.close(); } else { for (var filePath in files) { // Need to append the original path to build a proper path filePath = join(path, filePath); final stat = FileStat.statSync(filePath); if (stat.type == io.FileSystemEntityType.file) { controller.add(File(filePath)); } else if (stat.type == io.FileSystemEntityType.directory) { controller.add(Directory(filePath)); } else { controller.add(Link(filePath)); } } controller.close(); } } fs.readdir(path, js.allowInterop(callback)); return controller.stream; } @override Future<io.Directory> rename(String newPath) { final completer = Completer<Directory>(); void callback(err) { if (err == null) { completer.complete(Directory(newPath)); } else { completer.completeError(err); } } final jsCallback = js.allowInterop(callback); fs.rename(path, newPath, jsCallback); return completer.future; } @override io.Directory renameSync(String newPath) { fs.renameSync(path, newPath); return Directory(newPath); } @override Future<Directory> create({bool recursive = false}) { if (recursive) { throw UnsupportedError('Recursive create is not supported in Node.'); } final completer = Completer<Directory>(); void callback(err) { if (err == null) { completer.complete(Directory(path)); } else { completer.completeError(err); } } var jsCallback = js.allowInterop(callback); fs.mkdir(path, jsCallback); return completer.future; } @override void createSync({bool recursive = false}) { if (recursive) { throw UnsupportedError('Recursive create is not supported in Node.'); } fs.mkdirSync(path); } @override Future<io.Directory> createTemp([String prefix]) { prefix ??= ''; if (path == '') { throw ArgumentError('Directory.createTemp called with an empty path. ' 'To use the system temp directory, use Directory.systemTemp'); } String fullPrefix; if (path.endsWith('/') || (Platform.isWindows && path.endsWith('\\'))) { fullPrefix = '$path$prefix'; } else { fullPrefix = '$path${Platform.pathSeparator}$prefix'; } final completer = Completer<Directory>(); void callback(err, result) { if (err == null) { completer.complete(Directory(result)); } else { completer.completeError(err); } } var jsCallback = js.allowInterop(callback); fs.mkdtemp(fullPrefix, jsCallback); return completer.future; } @override io.Directory createTempSync([String prefix]) { prefix ??= ''; if (path == '') { throw ArgumentError('Directory.createTemp called with an empty path. ' 'To use the system temp directory, use Directory.systemTemp'); } String fullPrefix; if (path.endsWith('/') || (Platform.isWindows && path.endsWith('\\'))) { fullPrefix = '$path$prefix'; } else { fullPrefix = '$path${Platform.pathSeparator}$prefix'; } final resultPath = fs.mkdtempSync(fullPrefix); return Directory(resultPath); } @override List<io.FileSystemEntity> listSync( {bool recursive = false, bool followLinks = true}) { if (recursive) { throw UnsupportedError('Recursive list is not supported in Node.js.'); } final files = fs.readdirSync(path); return files.map((filePath) { // Need to append the original path to build a proper path filePath = join(path, filePath); final stat = FileStat.statSync(filePath); if (stat.type == io.FileSystemEntityType.file) { return File(filePath); } else if (stat.type == io.FileSystemEntityType.directory) { return Directory(filePath); } else { return Link(filePath); } }).toList(); } @override String toString() { return "Directory: '$path'"; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_io/src/network_interface.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. 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' as io; import 'package:node_interop/os.dart'; import 'package:node_interop/util.dart'; import 'internet_address.dart'; /// A [NetworkInterface] represents an active network interface on the current /// system. It contains a list of [InternetAddress]es that are bound to the /// interface. abstract class NetworkInterface implements io.NetworkInterface { /// Whether [list] is supported. static bool get listSupported => true; /// Query the system for [NetworkInterface]s. // TODO: Implement all named arguments for this method. static Future<List<io.NetworkInterface>> list() { // ignore: omit_local_variable_types final Map<String, Object> data = dartify(os.networkInterfaces()); var index = 0; final result = data.entries .map((entry) => _NetworkInterface.fromJS( entry.key, index++, List<Map>.from(entry.value))) .toList(growable: false); return Future.value(result); } } class _NetworkInterface implements io.NetworkInterface { @override final List<io.InternetAddress> addresses; @override final int index; @override final String name; factory _NetworkInterface.fromJS(String name, int index, List<Map> data) { final addresses = data .map((Map addr) => addr['address'] as String) .map((ip) => InternetAddress(ip)) .toList(growable: false); return _NetworkInterface(addresses, index, name); } _NetworkInterface(this.addresses, this.index, this.name); @override String toString() { return 'NetworkInterface #$index($name, $addresses)'; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/node/stream.dart
@JS() library stream; import 'dart:async'; import 'package:js/js.dart'; import 'package:meta/meta.dart'; import 'package:node_interop/node.dart'; import 'package:node_interop/util.dart'; @JS() @anonymous abstract class Stream { external void generateToken(String idUser, doneCallback); } Future<String> generateToken({ @required String idUser, }) { final stream = require('./stream.js'); final completer = Completer(); final doneCallback = allowInterop((result) => completer.complete(result)); stream.generateToken(idUser, doneCallback); return completer.future.then(dartify); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/node/authentication.dart
import 'dart:async'; import 'dart:convert'; import 'package:firebase_functions_interop/firebase_functions_interop.dart' hide Message; import 'package:foundation/model/user_token.dart'; import 'package:foundation/request/authentication_request.dart'; import 'package:foundation/request/authentication_response.dart'; import 'stream.dart'; class Authentication { static void handle() { functions['createToken'] = functions.https.onRequest(createToken); } static Future createToken(ExpressHttpRequest request) async { try { final requestData = AuthenticationRequest.fromJson(request.body); print('ID USer: ${requestData.idUser}'); if (requestData.idUser != null && requestData.idUser.isNotEmpty) { final idUser = requestData.idUser; print('Got idUser: ${idUser}'); final token = await generateToken(idUser: idUser); print('Got Token: ${token}'); final userToken = UserToken(idUser: idUser, token: token); final response = AuthenticationResponse(userToken: userToken); await _sendResponse(request, response); } else { print('Got not idUser'); await _sendError(request); } } catch (e) { print('Error: $e'); await _sendError(request); } return null; } static Future _sendError(ExpressHttpRequest request) async { final response = AuthenticationResponse(error: 'Some error occurred'); await _sendResponse(request, response); } static Future _sendResponse(ExpressHttpRequest request, response) async { request.response.headers.add("Access-Control-Allow-Origin", "*"); request.response.headers.add('Access-Control-Allow-Headers', '*'); request.response.headers .add("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,OPTIONS"); request.response.writeln(json.encode(response.toJson())); await request.response.close(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/node/index.dart
import 'authentication.dart'; void main() { Authentication.handle(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/node/stream.dart
@JS() library stream; import 'dart:async'; import 'package:js/js.dart'; import 'package:meta/meta.dart'; import 'package:node_interop/node.dart'; import 'package:node_interop/util.dart'; @JS() @anonymous abstract class Stream { external void generateToken(String idUser, doneCallback); } Future<String> generateToken({ @required String idUser, }) { final stream = require('./stream.js'); final completer = Completer(); final doneCallback = allowInterop((result) => completer.complete(result)); stream.generateToken(idUser, doneCallback); return completer.future.then(dartify); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/node/authentication.dart
import 'dart:async'; import 'dart:convert'; import 'package:firebase_functions_interop/firebase_functions_interop.dart' hide Message; import 'package:foundation/model/user_token.dart'; import 'package:foundation/request/authentication_request.dart'; import 'package:foundation/request/authentication_response.dart'; import 'stream.dart'; class Authentication { static void handle() { functions['createToken'] = functions.https.onRequest(createToken); } static Future createToken(ExpressHttpRequest request) async { try { final requestData = AuthenticationRequest.fromJson(request.body); print('ID USer: ${requestData.idUser}'); if (requestData.idUser != null && requestData.idUser.isNotEmpty) { final idUser = requestData.idUser; print('Got idUser: ${idUser}'); final token = await generateToken(idUser: idUser); print('Got Token: ${token}'); final userToken = UserToken(idUser: idUser, token: token); final response = AuthenticationResponse(userToken: userToken); await _sendResponse(request, response); } else { print('Got not idUser'); await _sendError(request); } } catch (e) { print('Error: $e'); await _sendError(request); } return null; } static Future _sendError(ExpressHttpRequest request) async { final response = AuthenticationResponse(error: 'Some error occurred'); await _sendResponse(request, response); } static Future _sendResponse(ExpressHttpRequest request, response) async { request.response.headers.add("Access-Control-Allow-Origin", "*"); request.response.headers.add('Access-Control-Allow-Headers', '*'); request.response.headers .add("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,OPTIONS"); request.response.writeln(json.encode(response.toJson())); await request.response.close(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/node/index.dart
import 'authentication.dart'; void main() { Authentication.handle(); }
0
mirrored_repositories/courseApp_flutter
mirrored_repositories/courseApp_flutter/lib/app_states.dart
class AppStates { int counter; AppStates({required this.counter}); } class InitStates extends AppStates { InitStates() : super(counter: 0); }
0
mirrored_repositories/courseApp_flutter
mirrored_repositories/courseApp_flutter/lib/app_events.dart
class AppEvents {} class Increments extends AppEvents {} class Decrements extends AppEvents {}
0
mirrored_repositories/courseApp_flutter
mirrored_repositories/courseApp_flutter/lib/global.dart
import 'package:course_app/common/service/storage_service.dart'; import 'package:flutter/cupertino.dart'; import 'package:firebase_core/firebase_core.dart'; class Global { static late StorageService storageService; static Future init() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( //option : DefaultFirebaseOption.currentPlatform; ); storageService = await StorageService().init(); } }
0
mirrored_repositories/courseApp_flutter
mirrored_repositories/courseApp_flutter/lib/app_blocs.dart
import 'package:course_app/app_events.dart'; import 'package:course_app/app_states.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:course_app/app_events.dart'; class AppBlocs extends Bloc<AppEvents, AppStates> { AppBlocs() : super(InitStates()) { on<Increments>((events, ask) { ask(AppStates(counter: state.counter + 1)); print(state.counter); }); on<Decrements>((events, ask) { ask(AppStates(counter: state.counter - 1)); print(state.counter); }); } }
0
mirrored_repositories/courseApp_flutter
mirrored_repositories/courseApp_flutter/lib/main.dart
import 'package:course_app/pages/application/application_page.dart'; import 'package:course_app/pages/sign_in/bloc/sign_in_blocs.dart'; import 'package:course_app/pages/bloc_provider.dart'; import 'package:course_app/pages/register/register.dart'; import 'package:course_app/pages/sign_in/sign_in.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:firebase_core/firebase_core.dart'; import 'common/routes/routes.dart'; import 'common/values/colors.dart'; import 'global.dart'; Future<void> main() async { await Global.init(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [...AppPages.allBlocProviders(context)], child: ScreenUtilInit( designSize: const Size(375, 812), builder: (context, child) => MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( appBarTheme: const AppBarTheme( iconTheme: IconThemeData(color: AppColors.primaryText), elevation: 0, backgroundColor: Colors.white, centerTitle: true)), onGenerateRoute: AppPages.GenerateRouteSettings, ))); } } // class MyHomePage extends StatelessWidget { // const MyHomePage({super.key}); // @override // Widget build(BuildContext context) { // return Scaffold( // // appBar: AppBar( // // title: const Text("Flutter Demo Home Page"), // // ), // body: Center( // child: BlocBuilder<AppBlocs, AppStates>(builder: (context, state) { // return Column( // mainAxisAlignment: MainAxisAlignment.center, // children: <Widget>[ // const Text( // 'You have pushed the button this many times:', // ), // Text( // "${BlocProvider.of<AppBlocs>(context).state.counter}", // style: Theme.of(context).textTheme.headlineMedium, // ), // ], // ); // })), // floatingActionButton: Row( // mainAxisAlignment: MainAxisAlignment.spaceAround, // children: [ // FloatingActionButton( // heroTag: "heroTag1", // onPressed: () => // BlocProvider.of<AppBlocs>(context).add(Increments()), // tooltip: 'Increment', // child: const Icon(Icons.add), // ), // FloatingActionButton( // heroTag: "heroTag2", // onPressed: () => // BlocProvider.of<AppBlocs>(context).add(Decrements()), // tooltip: 'Decrement', // child: const Icon(Icons.remove), // ), // ], // ) // This trailing comma makes auto-formatting nicer for build methods. // ); // } // }
0
mirrored_repositories/courseApp_flutter/lib
mirrored_repositories/courseApp_flutter/lib/pages/common_widget.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../../common/values/colors.dart'; AppBar buildAppBar() { return AppBar( bottom: PreferredSize( preferredSize: const Size.fromHeight(1.0), child: Container( color: AppColors.primarySecondaryBackground, height: 1.0, ), ), title: Text( "Log In", style: TextStyle( color: AppColors.primaryText, fontSize: 16.sp, fontWeight: FontWeight.w500, ), ), ); } //we need context to accessing bloc Widget buildThirdPartyLogin(BuildContext context) { return Center( child: Container( margin: EdgeInsets.only(top: 30.h, bottom: 40.h), padding: EdgeInsets.only(left: 25.w, right: 25.w), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ _reusableIcons("google"), _reusableIcons("apple"), _reusableIcons("facebook"), ], ), ), ); } Widget _reusableIcons(String iconName) { return GestureDetector( onTap: () {}, child: SizedBox( width: 40.w, height: 40.w, child: Image.asset("assets/icons/$iconName.png"), ), ); } Widget reusableText(String text) { return Container( margin: EdgeInsets.only( bottom: 5.h, ), child: Text(text, style: TextStyle( color: Colors.black.withOpacity(0.6), fontWeight: FontWeight.normal, fontSize: 14.sp)), ); } Widget buildTextField(String hintText, String textType, String iconName, void Function(String value)? func) { return Container( width: 325.h, height: 50.h, margin: EdgeInsets.only(bottom: 20.h), decoration: BoxDecoration( borderRadius: BorderRadius.circular(15.w), border: Border.all(color: AppColors.primaryText)), child: Row( children: [ Container( width: 16.w, height: 16.w, margin: EdgeInsets.only(left: 17.w), child: Image.asset("assets/icons/$iconName.png"), ), Container( width: 270.w, height: 50.h, child: TextField( onChanged: (value) => func!(value), keyboardType: TextInputType.multiline, decoration: InputDecoration( hintText: hintText, enabledBorder: const OutlineInputBorder( borderSide: BorderSide(color: Colors.transparent), ), disabledBorder: const OutlineInputBorder( borderSide: BorderSide(color: Colors.transparent), ), focusedBorder: const OutlineInputBorder( borderSide: BorderSide(color: Colors.transparent), ), hintStyle: const TextStyle( color: AppColors.primarySecondaryElementText, )), style: TextStyle( color: AppColors.primaryText, fontFamily: "Avenir", fontWeight: FontWeight.normal, fontSize: 14.sp, ), autocorrect: false, obscureText: textType == "password" ? true : false, ), ), ], ), ); } Widget forgotPassword() { return Container( margin: EdgeInsets.only(left: 25.w), width: 250.w, height: 44.h, child: GestureDetector( onTap: () {}, child: Text("Forgot Password?", style: TextStyle( color: AppColors.primaryText, fontWeight: FontWeight.normal, fontSize: 14.sp, decoration: TextDecoration.underline, decorationColor: AppColors.primaryText)), ), ); } Widget buildLogInAdnRegButton( String buttonName, String buttonType, void Function()? func) { return GestureDetector( onTap: func, child: Container( width: 325.w, height: 50.h, margin: EdgeInsets.only( left: 25.w, right: 25.w, top: buttonType == "login" ? 40.h : 20.h), decoration: BoxDecoration( color: buttonType == "login" ? AppColors.primaryElement : AppColors.primaryBackground, borderRadius: BorderRadius.circular(15.w), border: Border.all( //check for register button border color color: buttonType == "login" ? Colors.transparent : AppColors.primaryFourthElementText, ), boxShadow: [ BoxShadow( spreadRadius: 1, blurRadius: 2, offset: Offset(0, 1), color: Colors.grey.withOpacity(0.3)), ]), child: Center( child: Text( buttonName, style: TextStyle( fontSize: 16.sp, fontWeight: FontWeight.normal, color: buttonType == "login" ? AppColors.primaryBackground : AppColors.primaryText, ), )), ), ); }
0
mirrored_repositories/courseApp_flutter/lib
mirrored_repositories/courseApp_flutter/lib/pages/bloc_provider.dart
import 'package:course_app/pages/welcome/bloc/welcome_blocs.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../app_blocs.dart'; import 'sign_in/bloc/sign_in_blocs.dart'; class AppBlocProviders { static get allBlocProviders => [ BlocProvider(create: (context) => WelcomeBloc()), BlocProvider(create: (context) => AppBlocs()), BlocProvider(create: (context) => SignInBloc()), ]; }
0
mirrored_repositories/courseApp_flutter/lib/pages
mirrored_repositories/courseApp_flutter/lib/pages/sign_in/sign_in.dart
import 'package:course_app/pages/sign_in/bloc/sign_in_blocs.dart'; import 'package:course_app/pages/sign_in/bloc/sign_in_states.dart'; import 'package:course_app/pages/sign_in/sign_in_controller.dart'; import 'package:course_app/pages/sign_in/widgets/sign_in_widget.dart'; import 'package:flutter/material.dart'; import 'package:flutter/src/widgets/framework.dart'; import 'package:flutter/src/widgets/placeholder.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'bloc/sign_in_events.dart'; class SignIn extends StatefulWidget { const SignIn({super.key}); @override State<SignIn> createState() => _SignInState(); } class _SignInState extends State<SignIn> { @override Widget build(BuildContext context) { return BlocBuilder<SignInBloc, SignInState>(builder: (context, state) { return Container( color: Colors.white, child: SafeArea( child: Scaffold( backgroundColor: Colors.white, appBar: buildAppBar(), body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ buildThirdPartyLogin(context), Center( child: reusableText("Or use your emailaccount to login")), Container( margin: EdgeInsets.only( top: 36.h, ), padding: EdgeInsets.only( left: 25.w, right: 25.w, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ reusableText("Email"), // SizedBox( // height: 5.h, // ), buildTextField( "Enter your email addres", "email", "user", (value) { context.read<SignInBloc>().add(EmailEvent(value)); }), reusableText("Password"), // SizedBox( // height: 3.h, // ), buildTextField( "Enter your email password", "password", "lock", (value) { context.read<SignInBloc>().add(PasswordEvent(value)); }), ], ), ), forgotPassword(), buildLogInAdnRegButton("Log in", "login", () { SignInController(context: context).handleSignIn("email"); // print("Succesfully"); }), buildLogInAdnRegButton("Register", "register", () { Navigator.of(context).pushNamed("register"); }), ], ), ), ), ), ); }); } }
0
mirrored_repositories/courseApp_flutter/lib/pages
mirrored_repositories/courseApp_flutter/lib/pages/sign_in/sign_in_controller.dart
import 'package:course_app/common/widgets/flutter_toast.dart'; import 'package:course_app/pages/sign_in/bloc/sign_in_blocs.dart'; import 'package:course_app/pages/sign_in/bloc/sign_in_states.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class SignInController { final BuildContext context; const SignInController({required this.context}); Future<void> handleSignIn(String type) async { try { if (type == "email") { final state = context.read<SignInBloc>().state; String emailAddres = state.email; String password = state.password; if (emailAddres.isEmpty) { // toastInfo(msg: "You need to fiil email addres"); } if (password.isEmpty) { // toastInfo(msg: "You need to fiil password"); } try { final credential = await FirebaseAuth.instance .signInWithEmailAndPassword( email: emailAddres, password: password); if (credential.user == null) { // toastInfo(msg: "You don't exist"); } if (!credential.user!.emailVerified) { // toastInfo(msg: "You need to verify your email addres"); } var user = credential.user; if (user != null) { //we got verified user from firebase print("user exist"); } else { //we have error getting user from firebase toastInfo(msg: "You not a user of this app"); } } on FirebaseAuthException catch (e) { if (e.code == "user-not-found") { toastInfo(msg: "No user for that email"); } else if (e.code == "wrong-password") { toastInfo(msg: "Wrong password for that user"); } else if (e.code == "invalid-email") { toastInfo(msg: "Your email addres format is wrong"); } } } } catch (e) { // } } }
0
mirrored_repositories/courseApp_flutter/lib/pages/sign_in
mirrored_repositories/courseApp_flutter/lib/pages/sign_in/widgets/sign_in_widget.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../../common/values/colors.dart'; AppBar buildAppBar(String type) { return AppBar( bottom: PreferredSize( preferredSize: const Size.fromHeight(1.0), child: Container( color: AppColors.primarySecondaryBackground, height: 1.0, ), ), title: Text( type, style: TextStyle( color: AppColors.primaryText, fontSize: 16.sp, fontWeight: FontWeight.w500, ), ), ); } //we need context to accessing bloc Widget buildThirdPartyLogin(BuildContext context) { return Center( child: Container( margin: EdgeInsets.only(top: 30.h, bottom: 40.h), padding: EdgeInsets.only(left: 50.w, right: 50.w), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ _reusableIcons("google"), _reusableIcons("apple"), _reusableIcons("facebook"), ], ), ), ); } Widget _reusableIcons(String iconName) { return GestureDetector( onTap: () {}, child: SizedBox( width: 40.w, height: 40.w, child: Image.asset("assets/icons/$iconName.png"), ), ); } Widget reusableText(String text) { return Container( margin: EdgeInsets.only( bottom: 5.h, ), child: Text(text, style: TextStyle( color: Colors.black.withOpacity(0.6), fontWeight: FontWeight.normal, fontSize: 14.sp)), ); } Widget buildTextField(String hintText, String textType, String iconName, void Function(String value)? func) { return Container( width: 325.h, height: 50.h, margin: EdgeInsets.only(bottom: 20.h), decoration: BoxDecoration( borderRadius: BorderRadius.circular(15.w), border: Border.all(color: AppColors.primaryText)), child: Row( children: [ Container( width: 16.w, height: 16.w, margin: EdgeInsets.only(left: 17.w), child: Image.asset("assets/icons/$iconName.png"), ), Container( width: 270.w, height: 50.h, child: TextField( onChanged: (value) => func!(value), keyboardType: TextInputType.multiline, decoration: InputDecoration( hintText: hintText, enabledBorder: const OutlineInputBorder( borderSide: BorderSide(color: Colors.transparent), ), disabledBorder: const OutlineInputBorder( borderSide: BorderSide(color: Colors.transparent), ), focusedBorder: const OutlineInputBorder( borderSide: BorderSide(color: Colors.transparent), ), hintStyle: const TextStyle( color: AppColors.primarySecondaryElementText, )), style: TextStyle( color: AppColors.primaryText, fontFamily: "Avenir", fontWeight: FontWeight.normal, fontSize: 14.sp, ), autocorrect: false, obscureText: textType == "password" ? true : false, ), ), ], ), ); } Widget forgotPassword() { return Container( margin: EdgeInsets.only(left: 25.w), width: 260.w, height: 44.h, child: GestureDetector( onTap: () {}, child: Text("Forgot Password?", style: TextStyle( color: AppColors.primaryText, fontWeight: FontWeight.normal, fontSize: 14.sp, decoration: TextDecoration.underline, decorationColor: AppColors.primaryText)), ), ); } Widget buildLogInAdnRegButton( String buttonName, String buttonType, void Function()? func) { return GestureDetector( onTap: func, child: Container( width: 325.w, height: 50.h, margin: EdgeInsets.only( left: 25.w, right: 25.w, top: buttonType == "login" ? 40.h : 20.h), decoration: BoxDecoration( color: buttonType == "login" ? AppColors.primaryElement : AppColors.primaryBackground, borderRadius: BorderRadius.circular(15.w), border: Border.all( //check for register button border color color: buttonType == "login" ? Colors.transparent : AppColors.primaryFourthElementText, ), boxShadow: [ BoxShadow( spreadRadius: 1, blurRadius: 2, offset: Offset(0, 1), color: Colors.grey.withOpacity(0.3)), ]), child: Center( child: Text( buttonName, style: TextStyle( fontSize: 16.sp, fontWeight: FontWeight.normal, color: buttonType == "login" ? AppColors.primaryBackground : AppColors.primaryText, ), )), ), ); }
0
mirrored_repositories/courseApp_flutter/lib/pages/sign_in
mirrored_repositories/courseApp_flutter/lib/pages/sign_in/bloc/sign_in_events.dart
abstract class SignInEvent { SignInEvents(); } class EmailEvent extends SignInEvent { final String email; EmailEvent(this.email); @override SignInEvents() { // TODO: implement SignInEvents throw UnimplementedError(); } } class PasswordEvent extends SignInEvent { final String password; PasswordEvent(this.password); @override SignInEvents() { // TODO: implement SignInEvents throw UnimplementedError(); } }
0
mirrored_repositories/courseApp_flutter/lib/pages/sign_in
mirrored_repositories/courseApp_flutter/lib/pages/sign_in/bloc/sign_in_blocs.dart
import 'package:course_app/pages/sign_in/bloc/sign_in_events.dart'; import 'package:course_app/pages/sign_in/bloc/sign_in_states.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class SignInBloc extends Bloc<SignInEvent, SignInState> { SignInBloc() : super(const SignInState()) { //state class on<EmailEvent>(_emailEvent); on<PasswordEvent>(_passwordEvent); } //event handler void _emailEvent(EmailEvent event, Emitter<SignInState> emit) { //print("my email is ${event.email}"); emit(state.copyWith(email: event.email)); } //event handler void _passwordEvent(PasswordEvent event, Emitter<SignInState> emit) { //print("my password is ${event.password}"); emit(state.copyWith(password: event.password)); } }
0
mirrored_repositories/courseApp_flutter/lib/pages/sign_in
mirrored_repositories/courseApp_flutter/lib/pages/sign_in/bloc/sign_in_states.dart
class SignInState { final String email; final String password; const SignInState({this.email = "", this.password = ""}); SignInState copyWith({String? email, String? password}) { return SignInState( //if it's not empty, use the signed value...if it's empty, use the previous value email: email ?? this.email, password: password ?? this.password, ); } }
0
mirrored_repositories/courseApp_flutter/lib/pages
mirrored_repositories/courseApp_flutter/lib/pages/application/application_page.dart
import 'package:course_app/pages/application/widgets/application_widget.dart'; import 'package:course_app/pages/application/bloc/app_events.dart'; import 'package:course_app/pages/application/bloc/app_states.dart'; import 'package:flutter/material.dart'; import 'package:flutter/src/widgets/framework.dart'; import 'package:flutter/src/widgets/placeholder.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../common/values/colors.dart'; import 'bloc/app_blocs.dart'; class ApplicationPage extends StatefulWidget { const ApplicationPage({super.key}); @override State<ApplicationPage> createState() => _ApplicationPageState(); } class _ApplicationPageState extends State<ApplicationPage> { int _index = 0; @override Widget build(BuildContext context) { return BlocBuilder<AppBlocs, AppState>(builder: (context, state) { return Container( color: Colors.white, child: SafeArea( child: Scaffold( body: buildPage(state.index), bottomNavigationBar: Container( width: 375.w, height: 58.h, decoration: BoxDecoration( color: AppColors.primaryElement, borderRadius: BorderRadius.only( topLeft: Radius.circular(20.h), topRight: Radius.circular(20.h)), boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.3), spreadRadius: 1, blurRadius: 1, ), ]), child: BottomNavigationBar( currentIndex: state.index, onTap: (value) { context.read<AppBlocs>().add(TriggerAppEvent(value)); }, elevation: 0, type: BottomNavigationBarType.fixed, showSelectedLabels: false, showUnselectedLabels: false, selectedItemColor: AppColors.primaryElement, unselectedItemColor: AppColors.primaryFourthElementText, items: bottonTabs, ), ), ), ), ); }); } }
0
mirrored_repositories/courseApp_flutter/lib/pages
mirrored_repositories/courseApp_flutter/lib/pages/application/application_widget.dart
import 'package:flutter/cupertino.dart'; Widget buildPage(int index) { List<Widget> _widget = [ Center(child: Text("Home")), Center(child: Text("Search")), Center(child: Text("Course")), Center(child: Text("Chat")), Center(child: Text("Profile")), ]; return _widget[index]; }
0
mirrored_repositories/courseApp_flutter/lib/pages/application
mirrored_repositories/courseApp_flutter/lib/pages/application/widgets/application_widget.dart
import 'package:course_app/pages/home/home_page.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../../common/values/colors.dart'; import '../../profile/profile.dart'; Widget buildPage(int index) { List<Widget> _widget = [ const HomePage(), Center(child: Text("Search")), Center(child: Text("Course")), Center(child: Text("Chat")), const ProfilePage(), ]; return _widget[index]; } var bottonTabs = [ BottomNavigationBarItem( label: "home", icon: SizedBox( width: 15.w, height: 15.h, child: Image.asset("assets/icons/home.png"), ), activeIcon: SizedBox( width: 15.w, height: 15.h, child: Image.asset( "assets/icons/home.png", color: AppColors.primaryElement, ), ), ), BottomNavigationBarItem( label: "search", icon: SizedBox( width: 15.w, height: 15.h, child: Image.asset("assets/icons/search2.png"), ), activeIcon: SizedBox( width: 15.w, height: 15.h, child: Image.asset( "assets/icons/search2.png", color: AppColors.primaryElement, ), ), ), BottomNavigationBarItem( label: "course", icon: SizedBox( width: 15.w, height: 15.h, child: Image.asset("assets/icons/play-circle1.png"), ), activeIcon: SizedBox( width: 15.w, height: 15.h, child: Image.asset( "assets/icons/play-circle1.png", color: AppColors.primaryElement, ), ), ), BottomNavigationBarItem( label: "chat", icon: SizedBox( width: 15.w, height: 15.h, child: Image.asset("assets/icons/message-circle.png"), ), activeIcon: SizedBox( width: 15.w, height: 15.h, child: Image.asset( "assets/icons/message-circle.png", color: AppColors.primaryElement, ), ), ), BottomNavigationBarItem( label: "profile", icon: SizedBox( width: 15.w, height: 15.h, child: Image.asset("assets/icons/person2.png"), ), activeIcon: SizedBox( width: 15.w, height: 15.h, child: Image.asset( "assets/icons/person2.png", color: AppColors.primaryElement, ), ), ), ];
0
mirrored_repositories/courseApp_flutter/lib/pages/application
mirrored_repositories/courseApp_flutter/lib/pages/application/bloc/app_states.dart
class AppState { final int index; const AppState({this.index = 0}); }
0
mirrored_repositories/courseApp_flutter/lib/pages/application
mirrored_repositories/courseApp_flutter/lib/pages/application/bloc/app_events.dart
abstract class AppEvent { const AppEvent(); } class TriggerAppEvent extends AppEvent { final int index; const TriggerAppEvent(this.index) : super(); }
0
mirrored_repositories/courseApp_flutter/lib/pages/application
mirrored_repositories/courseApp_flutter/lib/pages/application/bloc/app_blocs.dart
import 'package:course_app/pages/application/bloc/app_events.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:course_app/pages/application/bloc/app_states.dart'; class AppBlocs extends Bloc<AppEvent, AppState> { AppBlocs() : super(const AppState()) { on<TriggerAppEvent>((event, emit) { emit(AppState(index: event.index)); }); } }
0
mirrored_repositories/courseApp_flutter/lib/pages
mirrored_repositories/courseApp_flutter/lib/pages/bloc/sign_in_events.dart
abstract class SignInEvent { SignInEvents(); } class EmailEvent extends SignInEvent { final String email; EmailEvent(this.email); @override SignInEvents() { // TODO: implement SignInEvents throw UnimplementedError(); } } class PasswordEvent extends SignInEvent { final String password; PasswordEvent(this.password); @override SignInEvents() { // TODO: implement SignInEvents throw UnimplementedError(); } }
0
mirrored_repositories/courseApp_flutter/lib/pages
mirrored_repositories/courseApp_flutter/lib/pages/bloc/sign_in_blocs.dart
import 'package:course_app/pages/bloc/sign_in_events.dart'; import 'package:course_app/pages/bloc/sign_in_states.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class SignInBloc extends Bloc<SignInEvent, SignInState> { SignInBloc() : super(const SignInState()) { //state class on<EmailEvent>(_emailEvent); on<PasswordEvent>(_passwordEvent); } //event handler void _emailEvent(EmailEvent event, Emitter<SignInState> emit) { print("my email is ${event.email}"); emit(state.copyWith(email: event.email)); } //event handler void _passwordEvent(PasswordEvent event, Emitter<SignInState> emit) { print("my password is ${event.password}"); emit(state.copyWith(password: event.password)); } }
0
mirrored_repositories/courseApp_flutter/lib/pages
mirrored_repositories/courseApp_flutter/lib/pages/bloc/sign_in_states.dart
class SignInState { final String email; final String password; const SignInState({this.email = "", this.password = ""}); SignInState copyWith({String? email, String? password}) { return SignInState( //if it's not empty, use the signed value...if it's empty, use the previous value email: email ?? this.email, password: password ?? this.password, ); } }
0
mirrored_repositories/courseApp_flutter/lib/pages
mirrored_repositories/courseApp_flutter/lib/pages/profile/profile.dart
import 'package:course_app/pages/profile/widgets/profile_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter/src/widgets/framework.dart'; import 'package:flutter/src/widgets/placeholder.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; class ProfilePage extends StatefulWidget { const ProfilePage({super.key}); @override State<ProfilePage> createState() => _ProfilePageState(); } class _ProfilePageState extends State<ProfilePage> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: buildAppbar(), body: SingleChildScrollView( child: SizedBox( width: MediaQuery.of(context).size.width, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ profileIconAndEditButton(), SizedBox( height: 30.h, ), Padding( padding: EdgeInsets.only(left: 25.w), child: buildListView(context), ), ], ), ), ), ); } }
0
mirrored_repositories/courseApp_flutter/lib/pages/profile
mirrored_repositories/courseApp_flutter/lib/pages/profile/widgets/profile_widgets.dart
import 'package:course_app/common/routes/names.dart'; import 'package:course_app/common/widgets/base_text_widget.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../../common/values/colors.dart'; AppBar buildAppbar() { return AppBar( title: Container( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ SizedBox( width: 18.w, height: 12.h, child: Image.asset("assets/icons/menu.png"), ), reusableText("Profile"), SizedBox( width: 24.w, height: 24.h, child: Image.asset("assets/icons/more-vertical.png"), ), ], ), ), ); } Widget profileIconAndEditButton() { return Container( alignment: Alignment.bottomRight, padding: EdgeInsets.only(right: 6.w), width: 80.w, height: 80.h, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20.w), image: const DecorationImage( image: AssetImage("assets/icons/headpic.png"))), child: Image( width: 25.w, height: 25.h, image: const AssetImage("assets/icons/edit_3.png")), ); } //settings section button var imageInfo = <String, String>{ "Settings": "settings.png", "Payment details": "credit-card.png", "Achievements": "award.png", "Love": "heart(1).png", "Reminders": "cube.png" }; Widget buildListView(BuildContext context) { return Column( children: [ ...List.generate( imageInfo.length, (index) => GestureDetector( onTap: () => Navigator.of(context).pushNamed(AppRoutes.SETTINGS), child: Container( margin: EdgeInsets.only(bottom: 15.h), child: Row( children: [ Container( width: 40.w, height: 40.h, padding: EdgeInsets.all(10.w), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.w), color: AppColors.primaryElement), child: Image.asset( "assets/icons/${imageInfo.values.elementAt(index)}"), ), SizedBox( width: 15.w, ), Text( "${imageInfo.keys.elementAt(index)}", style: TextStyle( color: AppColors.primaryText, fontWeight: FontWeight.bold, fontSize: 16.sp, ), ), ], ), ), ), ) ], ); }
0
mirrored_repositories/courseApp_flutter/lib/pages/profile
mirrored_repositories/courseApp_flutter/lib/pages/profile/settings/settings_page.dart
import 'package:course_app/common/values/constant.dart'; import 'package:course_app/pages/application/bloc/app_events.dart'; import 'package:course_app/pages/profile/settings/bloc/settings_states.dart'; import 'package:course_app/pages/profile/settings/widgets/settings_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter/src/widgets/framework.dart'; import 'package:flutter/src/widgets/placeholder.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../../common/routes/names.dart'; import '../../../global.dart'; import '../../application/bloc/app_blocs.dart'; import 'bloc/settings_blocs.dart'; class SettingsPage extends StatefulWidget { const SettingsPage({super.key}); @override State<SettingsPage> createState() => _SettingsPageState(); } class _SettingsPageState extends State<SettingsPage> { void removeUserData() { context.read<AppBlocs>().add(TriggerAppEvent(0)); Global.storageService.remove(AppConstants.STORAGE_USER_TOKEN_KEY); Navigator.of(context) .pushNamedAndRemoveUntil(AppRoutes.SIGN_IN, (route) => false); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: buildAppBar(), body: SingleChildScrollView(child: BlocBuilder<SettingsBlocs, SettingsStates>(builder: (context, state) { return Container( child: Column( children: [ settingsButton(context, removeUserData), ], ), ); })), ); } }
0
mirrored_repositories/courseApp_flutter/lib/pages/profile/settings
mirrored_repositories/courseApp_flutter/lib/pages/profile/settings/widgets/settings_widgets.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../../../common/values/colors.dart'; import '../../../../common/widgets/base_text_widget.dart'; AppBar buildAppBar() { return AppBar( title: Container( child: Container(child: reusableText("Settings")), )); } Widget settingsButton(BuildContext context, void Function()? func) { return GestureDetector( onTap: () { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text("Confirm logout"), content: const Text("Are you sure you want to logout?"), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text("Cancel")), TextButton(onPressed: func, child: const Text("Confirm")), ], ); }); }, child: Container( height: 100.w, decoration: BoxDecoration( image: DecorationImage( fit: BoxFit.fitHeight, image: AssetImage("assets/icons/Logout.png"), ), ), ), ); }
0
mirrored_repositories/courseApp_flutter/lib/pages/profile/settings
mirrored_repositories/courseApp_flutter/lib/pages/profile/settings/bloc/settings_events.dart
abstract class SettingsEvents {} class TriggerSettings extends SettingsEvents {}
0
mirrored_repositories/courseApp_flutter/lib/pages/profile/settings
mirrored_repositories/courseApp_flutter/lib/pages/profile/settings/bloc/settings_blocs.dart
import 'package:course_app/pages/profile/settings/bloc/settings_events.dart'; import 'package:course_app/pages/profile/settings/bloc/settings_states.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class SettingsBlocs extends Bloc<SettingsEvents, SettingsStates> { SettingsBlocs() : super(SettingsStates()) { on<TriggerSettings>(_triggerSettings); } _triggerSettings(SettingsEvents event, Emitter<SettingsStates> emit) { emit(SettingsStates()); } }
0
mirrored_repositories/courseApp_flutter/lib/pages/profile/settings
mirrored_repositories/courseApp_flutter/lib/pages/profile/settings/bloc/settings_states.dart
class SettingsStates { const SettingsStates(); }
0
mirrored_repositories/courseApp_flutter/lib/pages
mirrored_repositories/courseApp_flutter/lib/pages/home/home_page.dart
import 'package:course_app/pages/home/bloc/home_page_bloc.dart'; import 'package:course_app/pages/home/bloc/home_page_states.dart'; import 'package:course_app/pages/home/widgets/home_page_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter/src/widgets/framework.dart'; import 'package:flutter/src/widgets/placeholder.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../common/values/colors.dart'; class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: buildAppBar(), body: BlocBuilder<HomePageBlocs, HomePageStates>( builder: (context, state) { return Container( margin: EdgeInsets.symmetric(vertical: 0, horizontal: 25.w), child: CustomScrollView( slivers: [ SliverToBoxAdapter( child: homePageText( "Hello", color: AppColors.primaryThirdElementText, ), ), SliverToBoxAdapter( child: homePageText( "Byeuu", top: 5, ), ), SliverPadding(padding: EdgeInsets.only(top: 20.h)), SliverToBoxAdapter( child: searchView(), ), SliverToBoxAdapter( child: slidersView(context, state), ), SliverToBoxAdapter( child: menuView(), ), SliverPadding( padding: EdgeInsets.symmetric(vertical: 18.h, horizontal: 0.w), sliver: SliverGrid( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 15, crossAxisSpacing: 15, childAspectRatio: 1.6), delegate: SliverChildBuilderDelegate(childCount: 4, (BuildContext context, int index) { return GestureDetector( onTap: () {}, child: courseGrid(), ); }), ), ) ], ), ); })); } }
0
mirrored_repositories/courseApp_flutter/lib/pages/home
mirrored_repositories/courseApp_flutter/lib/pages/home/widgets/home_page_widgets.dart
import 'package:course_app/pages/home/bloc/home_page_bloc.dart'; import 'package:course_app/pages/home/bloc/home_page_events.dart'; import 'package:course_app/pages/home/bloc/home_page_states.dart'; import 'package:course_app/pages/home/home_page.dart'; import 'package:dots_indicator/dots_indicator.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../../common/values/colors.dart'; AppBar buildAppBar() { return AppBar( title: Container( margin: EdgeInsets.only(left: 7.w, right: 7.w), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ SizedBox( width: 15.w, height: 12.h, child: Image.asset("assets/icons/menu.png"), ), GestureDetector( child: Container( width: 40.w, height: 40.h, decoration: const BoxDecoration( image: DecorationImage( image: AssetImage("assets/icons/person.png")), ), ), ), ], ), ), ); } //reuseable title text Widget homePageText(String text, {Color color = AppColors.primaryText, int top = 20}) { return Container( margin: EdgeInsets.only(top: 5.h), child: Text( text, style: TextStyle( color: color, fontSize: 24.sp, fontWeight: FontWeight.bold, ), ), ); } Widget searchView() { return Row( children: [ Container( width: 280.w, height: 40.h, decoration: BoxDecoration( color: AppColors.primaryBackground, borderRadius: BorderRadius.circular(15.h), border: Border.all( color: AppColors.primaryFourthElementText, ), ), child: Row( children: [ Container( margin: EdgeInsets.only(left: 17.w), width: 16.w, height: 16.w, child: Image.asset("assets/icons/search.png")), Container( width: 240.w, height: 40.h, child: TextField( keyboardType: TextInputType.multiline, decoration: const InputDecoration( contentPadding: EdgeInsets.fromLTRB(5, 5, 0, 5), hintText: "search your course", enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.transparent), ), disabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.transparent), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.transparent), ), hintStyle: TextStyle( color: AppColors.primarySecondaryElementText, )), style: TextStyle( color: AppColors.primaryText, fontFamily: "Avenir", fontWeight: FontWeight.normal, fontSize: 14.sp, ), autocorrect: false, obscureText: false, ), ), ], ), ), GestureDetector( child: Container( width: 40.w, height: 40.h, decoration: BoxDecoration( color: AppColors.primaryElement, borderRadius: BorderRadius.all(Radius.circular(13.w)), border: Border.all(color: AppColors.primaryElement)), child: Image.asset("assets/icons/options.png"), ), ), ], ); } Widget slidersView(BuildContext context, HomePageStates state) { return Column( children: [ Container( margin: EdgeInsets.only(top: 20.h), width: 325.w, height: 160.w, child: PageView( onPageChanged: (value) { print(value.toString()); context.read<HomePageBlocs>().add(HomePageDots(value)); }, children: [ _slidersContainer(path: "assets/icons/art.png"), _slidersContainer(path: "assets/icons/Image(1).png"), _slidersContainer(path: "assets/icons/Image(2).png"), ], ), ), Container( child: DotsIndicator( dotsCount: 3, position: state.index.toDouble(), decorator: DotsDecorator( color: AppColors.primaryThirdElementText, activeColor: AppColors.primaryElement, size: const Size.square(5.0), activeSize: const Size(17.0, 5.0), activeShape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5.0))), ), ), ], ); } Widget _slidersContainer({String path = "assets/icons/art.png"}) { return Container( margin: EdgeInsets.only(top: 20.h), width: 325.w, height: 160.w, child: PageView( children: [ Container( width: 325.w, height: 160.h, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(20.h)), image: DecorationImage(fit: BoxFit.fill, image: AssetImage(path))), ), ], ), ); } Widget menuView() { return Column( children: [ Container( width: 325.w, margin: EdgeInsets.only(top: 15.h), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ _reusableText("Choose your course"), GestureDetector( child: _reusableText("see all", color: AppColors.primaryThirdElementText, fontSize: 12), ), ], ), ), Container( margin: EdgeInsets.only(top: 20.w), child: Row( children: [ _reusableMenuText("All"), _reusableMenuText("Popular", textColor: AppColors.primaryThirdElementText, backGroundColor: Colors.white), _reusableMenuText("Newest", textColor: AppColors.primaryThirdElementText, backGroundColor: Colors.white), ], ), ), ], ); } Widget _reusableText(String text, {Color color: AppColors.primaryText, int fontSize = 16, FontWeight fontWeight = FontWeight.bold}) { return Text( text, style: TextStyle( color: color, fontWeight: fontWeight, fontSize: fontSize.sp, ), ); } Widget _reusableMenuText(String menuText, {Color textColor = AppColors.primaryElementText, Color backGroundColor = AppColors.primaryElement}) { return Container( margin: EdgeInsets.only(right: 20.w), decoration: BoxDecoration( color: backGroundColor, borderRadius: BorderRadius.circular(7.w), border: Border.all(color: backGroundColor)), padding: EdgeInsets.only(left: 15.w, right: 15.w, top: 5.h, bottom: 5.h), child: _reusableText(menuText, color: textColor, fontWeight: FontWeight.normal, fontSize: 12), ); } Widget courseGrid() { return Container( padding: EdgeInsets.all(12.w), decoration: BoxDecoration( borderRadius: BorderRadius.circular(15.w), image: const DecorationImage( fit: BoxFit.fill, image: AssetImage("assets/icons/Image(1).png")), ), child: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text("Best course for IT and Engineer", maxLines: 1, overflow: TextOverflow.fade, textAlign: TextAlign.left, softWrap: false, style: TextStyle( color: AppColors.primaryElementText, fontWeight: FontWeight.bold, fontSize: 11.sp, )), SizedBox( height: 5.h, ), Text("Flutter best course", maxLines: 1, overflow: TextOverflow.fade, textAlign: TextAlign.left, softWrap: false, style: TextStyle( color: AppColors.primaryFourthElementText, fontWeight: FontWeight.normal, fontSize: 9.sp, )), ], ), ); }
0
mirrored_repositories/courseApp_flutter/lib/pages/home
mirrored_repositories/courseApp_flutter/lib/pages/home/bloc/home_page_states.dart
class HomePageStates { const HomePageStates({this.index = 0}); final int index; HomePageStates copyWith({int? index}) { return HomePageStates( index: index ?? this.index, ); } }
0
mirrored_repositories/courseApp_flutter/lib/pages/home
mirrored_repositories/courseApp_flutter/lib/pages/home/bloc/home_page_events.dart
class HomePageEvents { const HomePageEvents(); } class HomePageDots extends HomePageEvents { final int index; HomePageDots(this.index); }
0
mirrored_repositories/courseApp_flutter/lib/pages/home
mirrored_repositories/courseApp_flutter/lib/pages/home/bloc/home_page_bloc.dart
import 'package:course_app/pages/home/bloc/home_page_events.dart'; import 'package:course_app/pages/home/bloc/home_page_states.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class HomePageBlocs extends Bloc<HomePageEvents, HomePageStates> { HomePageBlocs() : super(HomePageStates()) { on<HomePageDots>(_homePageDots); } void _homePageDots(HomePageDots event, Emitter<HomePageStates> emit) { emit(state.copyWith(index: event.index)); } }
0
mirrored_repositories/courseApp_flutter/lib/pages
mirrored_repositories/courseApp_flutter/lib/pages/register/register.dart
import 'package:course_app/pages/register/bloc/register_event.dart'; import 'package:course_app/pages/register/bloc/register_state.dart'; import 'package:course_app/pages/register/register_controller.dart'; import 'package:flutter/material.dart'; import 'package:flutter/src/widgets/framework.dart'; import 'package:flutter/src/widgets/placeholder.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../sign_in/bloc/sign_in_blocs.dart'; // import '../sign_in/bloc/sign_in_events.dart'; import '../sign_in/sign_in_controller.dart'; import '../sign_in/widgets/sign_in_widget.dart'; import 'bloc/register_bloc.dart'; class Register extends StatefulWidget { const Register({super.key}); @override State<Register> createState() => _RegisterState(); } class _RegisterState extends State<Register> { @override Widget build(BuildContext context) { return BlocBuilder<RegisterBlocs, RegisterState>(builder: (context, state) { return Container( color: Colors.white, child: SafeArea( child: Scaffold( backgroundColor: Colors.white, appBar: buildAppBar("Register"), body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: 20.h, ), Center( child: reusableText( "Enter your details below & free to sign up")), Container( margin: EdgeInsets.only( top: 36.h, ), padding: EdgeInsets.only( left: 25.w, right: 25.w, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ //username section reusableText("Username"), buildTextField("Enter your username", "name", "user", (value) { context .read<RegisterBlocs>() .add(UserNameEvent(value)); }), //email section reusableText("Email"), buildTextField( "Enter your email addres", "email", "user", (value) { context.read<RegisterBlocs>().add(EmailEvent(value)); }), //password section reusableText("Password"), buildTextField( "Enter your email password", "password", "lock", (value) { context .read<RegisterBlocs>() .add(PasswordEvent(value)); }), //re-connfirm password section reusableText("Re-enter Password"), buildTextField("Re-enter your password to confirm", "password", "lock", (value) { context .read<RegisterBlocs>() .add(RePasswordEvent(value)); }), ], ), ), Container( margin: EdgeInsets.only( left: 25.h, ), child: reusableText( "Enter your details below and free to sign up"), ), buildLogInAdnRegButton("Sign Up", "login", () { //Navigator.of(context).pushNamed("register"); RegisterController(context: context).handleEmailRegister(); }), ], ), ), ), ), ); }); } }
0
mirrored_repositories/courseApp_flutter/lib/pages
mirrored_repositories/courseApp_flutter/lib/pages/register/register_controller.dart
import 'package:course_app/common/widgets/flutter_toast.dart'; import 'package:course_app/pages/register/bloc/register_bloc.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class RegisterController { final BuildContext context; const RegisterController({required this.context}); Future<void> handleEmailRegister() async { final state = context.read<RegisterBlocs>().state; String userName = state.userName; String email = state.email; String password = state.password; String rePassword = state.rePassword; if (userName.isEmpty) { toastInfo(msg: "Username cannot be empty"); return; } if (email.isEmpty) { toastInfo(msg: "Email cannot be empty"); return; } if (password.isEmpty) { toastInfo(msg: "Password cannot be empty"); return; } if (rePassword.isEmpty) { toastInfo(msg: "Your password confirmation is wrong"); return; } try { final credential = await FirebaseAuth.instance .createUserWithEmailAndPassword(email: email, password: password); if (credential.user != null) { await credential.user?.sendEmailVerification(); await credential.user?.updateDisplayName(userName); toastInfo( msg: "An email has been sent to your registered email to activate it please check your email box"); Navigator.of(context).pop(); } } on FirebaseAuthException catch (e) { if (e.code == 'weak-password') { toastInfo(msg: 'The password provided is too weak.'); } else if (e.code == 'email-already-in-use') { toastInfo(msg: 'The account already exists for that email.'); } else if (e.code == 'invalid-email') { toastInfo(msg: 'The email address is not valid.'); } } } }
0
mirrored_repositories/courseApp_flutter/lib/pages/register
mirrored_repositories/courseApp_flutter/lib/pages/register/bloc/register_bloc.dart
import 'package:course_app/pages/register/bloc/register_event.dart'; import 'package:course_app/pages/register/bloc/register_state.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class RegisterBlocs extends Bloc<RegisterEvent, RegisterState> { RegisterBlocs() : super(const RegisterState()) { on<UserNameEvent>(_userNameEvent); on<EmailEvent>(_emailEvent); on<PasswordEvent>(_passwordEvent); on<RePasswordEvent>(_rePasswordEvent); } void _userNameEvent(UserNameEvent event, Emitter<RegisterState> emit) { emit(state.copyWith(userName: event.userName)); } void _emailEvent(EmailEvent event, Emitter<RegisterState> emit) { emit(state.copyWith(email: event.email)); } void _passwordEvent(PasswordEvent event, Emitter<RegisterState> emit) { emit(state.copyWith(password: event.password)); } void _rePasswordEvent(RePasswordEvent event, Emitter<RegisterState> emit) { emit(state.copyWith(rePassword: event.rePassword)); } }
0
mirrored_repositories/courseApp_flutter/lib/pages/register
mirrored_repositories/courseApp_flutter/lib/pages/register/bloc/register_state.dart
class RegisterState { //make the immuatble variable, so that it can't be changed after the object is created final String userName; final String email; final String password; final String rePassword; //create anoptional named parameter constructor const RegisterState( {this.email = "", this.password = "", this.rePassword = "", this.userName = ""}); RegisterState copyWith({ String? userName, String? email, String? password, String? rePassword, }) { return RegisterState( userName: userName ?? this.userName, email: email ?? this.email, password: password ?? this.password, rePassword: rePassword ?? this.rePassword); } }
0
mirrored_repositories/courseApp_flutter/lib/pages/register
mirrored_repositories/courseApp_flutter/lib/pages/register/bloc/register_event.dart
abstract class RegisterEvent { const RegisterEvent(); } class UserNameEvent extends RegisterEvent { final String userName; const UserNameEvent(this.userName); } class EmailEvent extends RegisterEvent { final String email; const EmailEvent(this.email); } class PasswordEvent extends RegisterEvent { final String password; const PasswordEvent(this.password); } class RePasswordEvent extends RegisterEvent { final String rePassword; const RePasswordEvent(this.rePassword); }
0
mirrored_repositories/courseApp_flutter/lib/pages
mirrored_repositories/courseApp_flutter/lib/pages/welcome/welcome.dart
import 'package:course_app/main.dart'; import 'package:dots_indicator/dots_indicator.dart'; import 'package:flutter/material.dart'; import 'package:flutter/src/widgets/placeholder.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../common/values/colors.dart'; import 'bloc/welcome_blocs.dart'; import 'bloc/welcome_events.dart'; import 'bloc/welcome_states.dart'; class Welcome extends StatefulWidget { const Welcome({Key? key}) : super(key: key); @override State<Welcome> createState() => _WelcomeState(); } class _WelcomeState extends State<Welcome> { PageController pageController = PageController(initialPage: 0); @override Widget build(BuildContext context) { return Container( color: Colors.white, child: Scaffold(body: BlocBuilder<WelcomeBloc, WelcomeState>( builder: (context, state) { return Container( margin: EdgeInsets.only(top: 50.h), width: 375.w, child: Stack( alignment: Alignment.topCenter, children: [ PageView( controller: pageController, onPageChanged: (index) { state.page = index; BlocProvider.of<WelcomeBloc>(context).add(WelcomeEvent()); }, children: [ _page( 1, context, "Next", "First See Learning", "Forget about a for for paper all knowledge in one learning", "assets/images/reading.png", ), _page( 2, context, "Next", "Connect with everyone", "Always keep in touch with your tutor & firend. Let's join us", "assets/images/boy.png", ), _page( 3, context, "Get Started", "Always Fascinated Learning", "Anywhere, anytime. The time is at our direction so study whenever you want", "assets/images/man.png", ), ], ), Positioned( bottom: 100.h, child: DotsIndicator( position: state.page.toDouble(), dotsCount: 3, mainAxisAlignment: MainAxisAlignment.center, decorator: DotsDecorator( color: AppColors.primaryThirdElementText, activeColor: AppColors.primaryElement, size: const Size.square(8.0), activeSize: const Size(18.0, 8.0), activeShape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5.0))), )), ], ), ); }, )), ); } Widget _page(int index, BuildContext context, String buttonName, String title, String subTitle, String imagePath) { return Column( children: [ SizedBox( width: 345.w, height: 345.w, child: Image.asset( imagePath, fit: BoxFit.cover, ), ), Container( child: Text(title, style: TextStyle( color: AppColors.primaryText, fontSize: 24.sp, fontWeight: FontWeight.normal)), ), Container( width: 375.w, padding: EdgeInsets.only(left: 30.w, right: 30.w), child: Text(subTitle, style: TextStyle( color: AppColors.primarySecondaryElementText, fontSize: 14.sp, fontWeight: FontWeight.normal)), ), GestureDetector( onTap: () { if (index < 3) { //animation pageController.animateToPage(index, duration: const Duration(milliseconds: 500), curve: Curves.easeInOut); } else { // Navigator.of(context) // .push(MaterialPageRoute(builder: (context) => MyHomePage())); Navigator.of(context) .pushNamedAndRemoveUntil("signIn", (route) => false); } }, child: Container( margin: EdgeInsets.only(top: 100.h, left: 25.w, right: 25.w), width: 325.w, height: 50.h, decoration: BoxDecoration( color: AppColors.primaryElement, borderRadius: BorderRadius.circular(15.w), boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.3), spreadRadius: 1, blurRadius: 2, offset: const Offset(0, 5), ) ]), child: Center( child: Text(buttonName, style: TextStyle( color: Colors.white, fontSize: 16.sp, fontWeight: FontWeight.normal)), ), ), ), ], ); } }
0
mirrored_repositories/courseApp_flutter/lib/pages/welcome
mirrored_repositories/courseApp_flutter/lib/pages/welcome/bloc/welcome_blocs.dart
import 'package:course_app/pages/welcome/bloc/welcome_events.dart'; import 'package:course_app/pages/welcome/bloc/welcome_states.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class WelcomeBloc extends Bloc<WelcomeEvent, WelcomeState> { WelcomeBloc() : super(WelcomeState()) { on<WelcomeEvent>((event, emit) { emit(WelcomeState(page: state.page)); }); } }
0
mirrored_repositories/courseApp_flutter/lib/pages/welcome
mirrored_repositories/courseApp_flutter/lib/pages/welcome/bloc/welcome_states.dart
class WelcomeState { int page; WelcomeState({this.page = 0}); }
0
mirrored_repositories/courseApp_flutter/lib/common
mirrored_repositories/courseApp_flutter/lib/common/widgets/flutter_toast.dart
import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:fluttertoast/fluttertoast.dart'; toastInfo({ required String msg, Color backgroundColor = Colors.black, Color textColor = Colors.white, }) { return Fluttertoast.showToast( msg: msg, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.TOP, timeInSecForIosWeb: 2, backgroundColor: backgroundColor, textColor: textColor, fontSize: 16.sp, ); }
0
mirrored_repositories/courseApp_flutter/lib/common
mirrored_repositories/courseApp_flutter/lib/common/routes/names.dart
class AppRoutes { //welcome page or onboarding static const INITIAL = '/'; //aplication page static const APPLICATION = '/application'; //sign in page static const SIGN_IN = '/sign_in'; //register page static const REGISTER = '/register'; }
0
mirrored_repositories/courseApp_flutter/lib/common
mirrored_repositories/courseApp_flutter/lib/common/routes/pages.dart
import 'package:course_app/pages/application/application_page.dart'; import 'package:course_app/pages/application/bloc/app_blocs.dart'; import 'package:course_app/pages/register/bloc/register_bloc.dart'; import 'package:course_app/pages/register/register.dart'; import 'package:course_app/pages/sign_in/bloc/sign_in_blocs.dart'; import 'package:course_app/pages/sign_in/sign_in.dart'; import 'package:course_app/pages/welcome/bloc/welcome_blocs.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../global.dart'; import '../../pages/welcome/welcome.dart'; import 'names.dart'; //unify blocProvider and routes and page class AppPages { static List<PageEntity> routes() { return [ PageEntity( route: AppRoutes.INITIAL, page: const Welcome(), bloc: BlocProvider(create: (_) => WelcomeBloc()), ), PageEntity( route: AppRoutes.SIGN_IN, page: const SignIn(), bloc: BlocProvider(create: (_) => SignInBloc()), ), PageEntity( route: AppRoutes.REGISTER, page: const Register(), bloc: BlocProvider(create: (_) => RegisterBlocs()), ), PageEntity( route: AppRoutes.APPLICATION, page: const ApplicationPage(), bloc: BlocProvider(create: (_) => AppBlocs()), ), ]; } static List<dynamic> allBlocProviders(BuildContext context) { List<dynamic> blocProviders = <dynamic>[]; for (var bloc in routes()) { blocProviders.add(bloc.bloc); } return blocProviders; } //a model that cover entire scree as we click on navigator object static MaterialPageRoute GenerateRouteSettings(RouteSettings settings) { if (settings.name != null) { //check if route is available var result = routes().where((element) => element.route == settings.name); if (result.isNotEmpty) { bool deviceFirstOpen = Global.storageService.getDeviceFirstOpen(); if (result.first.route == AppRoutes.INITIAL && deviceFirstOpen) { bool isLoggedin = Global.storageService.getIsLoggedIn(); if (isLoggedin) { return MaterialPageRoute( builder: (_) => const ApplicationPage(), settings: settings); } return MaterialPageRoute( builder: (_) => const SignIn(), settings: settings); } return MaterialPageRoute( builder: (_) => result.first.page, settings: settings); } } print("invalid route name ${settings.name}}"); return MaterialPageRoute( builder: (_) => const SignIn(), settings: settings); } } class PageEntity { String route; Widget page; dynamic bloc; PageEntity({ required this.route, required this.page, required this.bloc, }); }
0
mirrored_repositories/courseApp_flutter/lib/common
mirrored_repositories/courseApp_flutter/lib/common/values/colors.dart
import 'dart:ui'; class AppColors { /// white background static const Color primaryBackground = Color.fromARGB(255, 255, 255, 255); /// grey background static const Color primarySecondaryBackground = Color.fromARGB(255, 247, 247, 249); /// main widget color blue static const Color primaryElement = Color.fromARGB(255, 61, 61, 216); /// main text color black static const Color primaryText = Color.fromARGB(255, 0, 0, 0); // video backgroun color static const Color primary_bg = Color.fromARGB(210, 32, 47, 62); /// main widget text color white static const Color primaryElementText = Color.fromARGB(255, 255, 255, 255); // main widget text color grey static const Color primarySecondaryElementText = Color.fromARGB(255, 102, 102, 102); // main widget third color grey static const Color primaryThirdElementText = Color.fromARGB(255, 170, 170, 170); static const Color primaryFourthElementText = Color.fromARGB(255, 204, 204, 204); //state color static const Color primaryElementStatus = Color.fromARGB(255, 88, 174, 127); static const Color primaryElementBg = Color.fromARGB(255, 238, 121, 99); }
0
mirrored_repositories/courseApp_flutter/lib/common
mirrored_repositories/courseApp_flutter/lib/common/values/constant.dart
class AppConstants { static const String STORAGE_DEVICE_OPEN_FIRST_TIME = 'device_first_open'; static const String STORAGE_USER_PROFILE_KEY = 'user_profile_key'; static const String STORAGE_USER_TOKEN_KEY = 'user_token_key'; }
0
mirrored_repositories/courseApp_flutter
mirrored_repositories/courseApp_flutter/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility 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:course_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/hive_database_example
mirrored_repositories/hive_database_example/lib/boxes.dart
import 'package:hive/hive.dart'; import '../model/transaction.dart'; class Boxes { static Box<Transaction> getTransactions() => Hive.box<Transaction>('transactions'); }
0
mirrored_repositories/hive_database_example
mirrored_repositories/hive_database_example/lib/main.dart
import 'package:flutter/material.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'model/transaction.dart'; import 'page/transaction_page.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Hive.initFlutter(); Hive.registerAdapter(TransactionAdapter()); await Hive.openBox<Transaction>('transactions'); runApp(const MainApp()); } class MainApp extends StatelessWidget { static const String title = 'Hive Expense App'; const MainApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: title, theme: ThemeData(primarySwatch: Colors.indigo), home: const TransactionPage(), ); } }
0
mirrored_repositories/hive_database_example/lib
mirrored_repositories/hive_database_example/lib/page/transaction_page.dart
import 'package:flutter/material.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'package:intl/intl.dart'; import '../boxes.dart'; import '../model/transaction.dart'; import '../widget/transaction_dialog.dart'; class TransactionPage extends StatefulWidget { const TransactionPage({super.key}); @override State<TransactionPage> createState() => _TransactionPageState(); } class _TransactionPageState extends State<TransactionPage> { @override void dispose() { Hive.close(); super.dispose(); } @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: const Text('Hive Expense Tracker'), centerTitle: true, ), body: ValueListenableBuilder<Box<Transaction>>( valueListenable: Boxes.getTransactions().listenable(), builder: (context, box, _) { final transactions = box.values.toList().cast<Transaction>(); return buildContent(transactions); }, ), floatingActionButton: FloatingActionButton( child: const Icon(Icons.add), onPressed: () => showDialog( context: context, builder: (context) => TransactionDialog( onClickedDone: addTransaction, ), ), ), ); Widget buildContent(List<Transaction> transactions) { if (transactions.isEmpty) { return const Center( child: Text( 'No expenses yet!', style: TextStyle(fontSize: 24), ), ); } else { final netExpense = transactions.fold<double>( 0, (previousValue, transaction) => transaction.isExpense ? previousValue - transaction.amount : previousValue + transaction.amount, ); final newExpenseString = '\$${netExpense.toStringAsFixed(2)}'; final color = netExpense > 0 ? Colors.green : Colors.red; return Column( children: [ const SizedBox(height: 24), Text( 'Net Expense: $newExpenseString', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 20, color: color, ), ), const SizedBox(height: 24), Expanded( child: ListView.builder( padding: const EdgeInsets.all(8), itemCount: transactions.length, itemBuilder: (BuildContext context, int index) { final transaction = transactions[index]; return buildTransaction(context, transaction); }, ), ), ], ); } } Widget buildTransaction( BuildContext context, Transaction transaction, ) { final color = transaction.isExpense ? Colors.red : Colors.green; final date = DateFormat.yMMMd().format(transaction.createdDate); final amount = '\$${transaction.amount.toStringAsFixed(2)}'; return Card( color: Colors.white, child: ExpansionTile( tilePadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8), title: Text( transaction.name, maxLines: 2, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 18), ), subtitle: Text(date), trailing: Text( amount, style: TextStyle( color: color, fontWeight: FontWeight.bold, fontSize: 16), ), children: [ buildButtons(context, transaction), ], ), ); } Widget buildButtons(BuildContext context, Transaction transaction) => Row( children: [ Expanded( child: TextButton.icon( label: const Text('Edit'), icon: const Icon(Icons.edit), onPressed: () => Navigator.of(context).push( MaterialPageRoute( builder: (context) => TransactionDialog( transaction: transaction, onClickedDone: (name, amount, isExpense) => editTransaction(transaction, name, amount, isExpense), ), ), ), ), ), Expanded( child: TextButton.icon( label: const Text('Delete'), icon: const Icon(Icons.delete), onPressed: () => deleteTransaction(transaction), ), ) ], ); Future addTransaction(String name, double amount, bool isExpense) async { final transaction = Transaction() ..name = name ..createdDate = DateTime.now() ..amount = amount ..isExpense = isExpense; final box = Boxes.getTransactions(); box.add(transaction); //box.put('mykey', transaction); // final mybox = Boxes.getTransactions(); // final myTransaction = mybox.get('key'); // mybox.values; // mybox.keys; } void editTransaction( Transaction transaction, String name, double amount, bool isExpense, ) { transaction.name = name; transaction.amount = amount; transaction.isExpense = isExpense; // final box = Boxes.getTransactions(); // box.put(transaction.key, transaction); transaction.save(); } void deleteTransaction(Transaction transaction) { // final box = Boxes.getTransactions(); // box.delete(transaction.key); transaction.delete(); //setState(() => transactions.remove(transaction)); } }
0
mirrored_repositories/hive_database_example/lib
mirrored_repositories/hive_database_example/lib/model/transaction.dart
import 'package:hive/hive.dart'; part 'transaction.g.dart'; @HiveType(typeId: 0) class Transaction extends HiveObject { @HiveField(0) late String name; @HiveField(1) late DateTime createdDate; @HiveField(2) late bool isExpense = true; @HiveField(3) late double amount; }
0
mirrored_repositories/hive_database_example/lib
mirrored_repositories/hive_database_example/lib/model/transaction.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'transaction.dart'; // ************************************************************************** // TypeAdapterGenerator // ************************************************************************** class TransactionAdapter extends TypeAdapter<Transaction> { @override final int typeId = 0; @override Transaction read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return Transaction(); } @override void write(BinaryWriter writer, Transaction obj) { writer.writeByte(0); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is TransactionAdapter && runtimeType == other.runtimeType && typeId == other.typeId; }
0
mirrored_repositories/hive_database_example/lib
mirrored_repositories/hive_database_example/lib/widget/transaction_dialog.dart
import 'package:flutter/material.dart'; import '../model/transaction.dart'; class TransactionDialog extends StatefulWidget { final Transaction? transaction; final Function(String name, double amount, bool isExpense) onClickedDone; const TransactionDialog({ Key? key, this.transaction, required this.onClickedDone, }) : super(key: key); @override State<TransactionDialog> createState() => _TransactionDialogState(); } class _TransactionDialogState extends State<TransactionDialog> { final formKey = GlobalKey<FormState>(); final nameController = TextEditingController(); final amountController = TextEditingController(); bool isExpense = true; @override void initState() { super.initState(); if (widget.transaction != null) { final transaction = widget.transaction!; nameController.text = transaction.name; amountController.text = transaction.amount.toString(); isExpense = transaction.isExpense; } } @override void dispose() { nameController.dispose(); amountController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final isEditing = widget.transaction != null; final title = isEditing ? 'Edit Transaction' : 'Add Transaction'; return AlertDialog( title: Text(title), content: Form( key: formKey, child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ const SizedBox(height: 8), buildName(), const SizedBox(height: 8), buildAmount(), const SizedBox(height: 8), buildRadioButtons(), ], ), ), ), actions: <Widget>[ buildCancelButton(context), buildAddButton(context, isEditing: isEditing), ], ); } Widget buildName() => TextFormField( controller: nameController, decoration: const InputDecoration( border: OutlineInputBorder(), hintText: 'Enter Name', ), validator: (name) => name != null && name.isEmpty ? 'Enter a name' : null, ); Widget buildAmount() => TextFormField( decoration: const InputDecoration( border: OutlineInputBorder(), hintText: 'Enter Amount', ), keyboardType: TextInputType.number, validator: (amount) => amount != null && double.tryParse(amount) == null ? 'Enter a valid number' : null, controller: amountController, ); Widget buildRadioButtons() => Column( children: [ RadioListTile<bool>( title: const Text('Expense'), value: true, groupValue: isExpense, onChanged: (value) => setState(() => isExpense = value!), ), RadioListTile<bool>( title: const Text('Income'), value: false, groupValue: isExpense, onChanged: (value) => setState(() => isExpense = value!), ), ], ); Widget buildCancelButton(BuildContext context) => TextButton( child: const Text('Cancel'), onPressed: () => Navigator.of(context).pop(), ); Widget buildAddButton(BuildContext context, {required bool isEditing}) { final text = isEditing ? 'Save' : 'Add'; return TextButton( child: Text(text), onPressed: () async { final isValid = formKey.currentState!.validate(); if (isValid) { final name = nameController.text; final amount = double.tryParse(amountController.text) ?? 0; widget.onClickedDone(name, amount, isExpense); Navigator.of(context).pop(); } }, ); } }
0
mirrored_repositories/yhshop_app
mirrored_repositories/yhshop_app/lib/main.dart
import 'package:app_bloc/core/base/app_bloc_observer.dart'; import 'package:app_bloc/di/di.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'application.dart'; import 'core/utils/storage_lib.dart'; void main() async { await setup(); runApp(const Application()); } Future<void> setup() async { WidgetsFlutterBinding.ensureInitialized(); Bloc.observer = AppBlocObserver(); configureDependencies(); await Hive.initFlutter(); await LocalStorage.initialize(); SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(statusBarColor: Colors.transparent, statusBarIconBrightness: Brightness.dark)); }
0
mirrored_repositories/yhshop_app
mirrored_repositories/yhshop_app/lib/application.dart
import 'package:app_bloc/core/base/app/app_bloc.dart'; import 'package:app_bloc/core/base/app/app_event.dart'; import 'package:app_bloc/core/base/app/app_state.dart'; import 'package:app_bloc/core/base/base_event.dart'; import 'package:app_bloc/core/base/base_state.dart'; import 'package:app_bloc/core/constants/app_constants.dart'; import 'package:app_bloc/core/utils/navigation/app_navigator.dart'; import 'package:app_bloc/core/utils/theme/theme_manager.dart'; import 'package:app_bloc/di/di.dart'; import 'package:app_bloc/presentation/auth/bloc/auth_bloc.dart'; import 'package:app_bloc/presentation/auth/bloc/auth_event.dart'; import 'package:app_bloc/presentation/auth/bloc/auth_state.dart'; import 'package:app_bloc/presentation/initial/initial_page.dart'; import 'package:app_bloc/presentation/internet_status/internet_status_page.dart'; import 'package:app_bloc/presentation/intro/intro_page.dart'; import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'core/utils/navigation/page_manager.dart'; import 'core/utils/navigation/route_path.dart'; class Application extends StatefulWidget { const Application({super.key}); @override State<Application> createState() => _ApplicationState(); } class _ApplicationState extends State<Application> { @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider( create: (context) => getIt<AppBloc>()..add(AppInitialEvent())), BlocProvider( create: (context) => getIt<AuthBloc>()..add(const AuthInitialEvent())), ], child: BlocBuilder<AppBloc, AppState>( builder: (context, state) { final bloc = getIt<AppBloc>(); return MaterialApp( title: AppConstants.title, debugShowCheckedModeBanner: false, onGenerateRoute: generateRoutes, initialRoute: RoutePath.initial, themeMode: bloc.themeMode, theme: ThemeManager.light, home: StreamBuilder<ConnectivityResult>( stream: bloc.connectivityStream, builder: (context, snapshot) { final isConnected = [ ConnectivityResult.wifi, ConnectivityResult.ethernet, ConnectivityResult.mobile ].contains(snapshot.data); return Stack( fit: StackFit.expand, children: [ ApplicationContent(bloc: bloc), if (!isConnected && snapshot.connectionState != ConnectionState.waiting) const InternetStatusPage() ], ); }, ), ); }, ), ); } } class ApplicationContent extends StatefulWidget { final AppBloc bloc; const ApplicationContent({super.key, required this.bloc}); @override State<ApplicationContent> createState() => ApplicationContentState(); } class ApplicationContentState extends State<ApplicationContent> { @override void initState() { super.initState(); getIt<AppNavigator>().setContext(context); } @override Widget build(BuildContext context) { if (widget.bloc.isIntro) return const IntroPage(); return MultiBlocListener( listeners: [ BlocListener<AuthBloc, AuthState>( listener: (context, state) { if (state is AuthNotLoggedIn) { getIt<AppNavigator>().pushNamedAndRemoveUntil(RoutePath.login); return; } if (state is AuthUserChanged) { getIt<AppNavigator>().pushNamedAndRemoveUntil(RoutePath.home); return; } }, ), ], child: const InitialPage(), ); } }
0
mirrored_repositories/yhshop_app/lib/data/remote
mirrored_repositories/yhshop_app/lib/data/remote/repository/user_repository.dart
import 'package:app_bloc/core/network/failure.dart'; import 'package:app_bloc/data/models/user_model.dart'; import 'package:app_bloc/data/remote/provider/user_provider.dart'; import 'package:dartz/dartz.dart'; import 'package:injectable/injectable.dart'; @Singleton() class UserRepository implements IUserProvider { final UserProvider _userProvider; UserRepository(this._userProvider); @override Future<void> logOut() { return _userProvider.logOut(); } @override Future<Either<Failure, UserModel>> login() { return _userProvider.login(); } }
0
mirrored_repositories/yhshop_app/lib/data/remote
mirrored_repositories/yhshop_app/lib/data/remote/provider/user_provider.dart
import 'package:app_bloc/data/models/user_model.dart'; import 'package:dartz/dartz.dart'; import 'package:injectable/injectable.dart'; import '../../../core/network/failure.dart'; abstract class IUserProvider { Future<void> logOut(); Future<Either<Failure, UserModel>> login(); } @LazySingleton() class UserProvider implements IUserProvider { @override Future<void> logOut() { throw UnimplementedError(); } @override Future<Either<Failure, UserModel>> login() { throw UnimplementedError(); } }
0
mirrored_repositories/yhshop_app/lib/data
mirrored_repositories/yhshop_app/lib/data/models/user_model.dart
class UserModel { final String userId; final String? fullName; final String? email; UserModel({required this.userId, this.fullName, this.email}); }
0
mirrored_repositories/yhshop_app/lib/core
mirrored_repositories/yhshop_app/lib/core/network/failure.dart
import 'package:equatable/equatable.dart'; abstract class Failure extends Equatable { final String msg; const Failure(this.msg); @override List<Object?> get props => [msg]; }
0
mirrored_repositories/yhshop_app/lib/core
mirrored_repositories/yhshop_app/lib/core/constants/app_string.dart
import 'package:flutter/material.dart'; @immutable abstract class AppStrings { const AppStrings._(); static const String home = 'Home'; static const String search = 'Search'; static const String wishList = 'Wishlist'; static const String bag = 'Bag'; static const String profile = 'Profile'; }
0
mirrored_repositories/yhshop_app/lib/core
mirrored_repositories/yhshop_app/lib/core/constants/color_resource.dart
import 'dart:ui'; abstract class ColorResource { ColorResource._(); static const Color primary = Color(0xFF0F172A); static const Color primary400 = Color(0xFF2A3646); static const Color primary300 = Color(0xFF475569); static const Color primary200 = Color(0xFF64748B); static const Color primary100 = Color(0xFFCBD5E1); static const Color primary50 = Color(0xFFF1F5F9); static const Color secondary = Color(0xFFFF9F29); static const Color secondary400 = Color(0xFFFFB254); static const Color secondary300 = Color(0xFFFFC57F); static const Color secondary200 = Color(0xFFFFCF94); static const Color secondary100 = Color(0xFFFFD9A9); static const Color secondary50 = Color(0xFFFFF5EA); static const Color grey50 = Color(0xFFF8FAFC); static const Color grey100 = Color(0xFFF1F5F9); static const Color grey200 = Color(0xFFE2E8F0); static const Color grey300 = Color(0xFFCBD5E1); static const Color grey400 = Color(0xFF94A3B8); static const Color grey500 = Color(0xFF64748B); static const Color grey600 = Color(0xFF475569); static const Color grey700 = Color(0xFF2A3646); static const Color grey800 = Color(0xFF1B2537); static const Color grey900 = Color(0xFF0F172A); static const Color mango = Color(0xFFFF9F29); static const Color blue = Color(0xFF0062FF); static const Color purple = Color(0xFF764AF1); static const Color orderGreen = Color(0xFF1A4D2E); static const Color alertErrorBase = Color(0xFFFF4747); }
0
mirrored_repositories/yhshop_app/lib/core
mirrored_repositories/yhshop_app/lib/core/constants/app_constants.dart
abstract class AppConstants { static const String title = 'Shopline'; static const String token = ''; } abstract class Globals { Globals._(); static const double spaceSm = 8.0; static const double space = 16.0; static const double spaceMd = 24.0; static const double spaceXl = 32.0; static const double paddingSm = 12.0; static const double padding = 16.0; static const double paddingMd = 24.0; static const double radius = 16.0; static const double circle = 100.0; static const double fsSm = 11; static const double fsMd = 14; static const double fsLg = 16; static const double fsXl = 24; static const double fsXxl = 28; }
0
mirrored_repositories/yhshop_app/lib/core
mirrored_repositories/yhshop_app/lib/core/constants/api_path.dart
abstract class ApiPath { static String apiUrl = 'http://192.168.1.130/api'; static String login = '$apiUrl/login'; static String register = '$apiUrl/register'; }
0
mirrored_repositories/yhshop_app/lib/core
mirrored_repositories/yhshop_app/lib/core/constants/types.dart
typedef JsonMap = Map<String, dynamic>;
0
mirrored_repositories/yhshop_app/lib/core
mirrored_repositories/yhshop_app/lib/core/constants/icon_resource.dart
abstract class IconRes { const IconRes._(); static const String icTablerHeart = 'assets/icons/tabler_heart.svg'; static const String icSearch = 'assets/icons/search.svg'; static const String icLike = 'assets/icons/like.svg'; static const String icEmailLight = 'assets/icons/email-light.svg'; static const String icSteeringWheel = 'assets/icons/steering-wheel.svg'; static const String icShieldLock = 'assets/icons/shield-lock.svg'; static const String icSearchFill = 'assets/icons/search-fill.svg'; static const String icSortDescending = 'assets/icons/sort-descending.svg'; static const String icTag2 = 'assets/icons/tag-2.svg'; static const String icLayoutList = 'assets/icons/layout-list.svg'; static const String icReceiptTax = 'assets/icons/receipt-tax.svg'; static const String icMenu2 = 'assets/icons/menu-2.svg'; static const String icLayoutGrid = 'assets/icons/layout-grid.svg'; static const String icHome = 'assets/icons/home.svg'; static const String icShop = 'assets/icons/shop.svg'; static const String icDollarCircle = 'assets/icons/dollar-circle.svg'; static const String icMailBox = 'assets/icons/mail-box.svg'; static const String icChevronDown = 'assets/icons/chevron-down.svg'; static const String icLogout = 'assets/icons/logout.svg'; static const String icBriefcase = 'assets/icons/briefcase.svg'; static const String icMicrophone = 'assets/icons/microphone.svg'; static const String icIkeOutlined = 'assets/icons/ike-outlined.svg'; static const String icChevronUp = 'assets/icons/chevron-up.svg'; static const String icFileText = 'assets/icons/file-text.svg'; static const String icHomeFill = 'assets/icons/home-fill.svg'; static const String icQuestionCircleOutlined = 'assets/icons/question-circle-outlined.svg'; static const String icX = 'assets/icons/x.svg'; static const String icLock = 'assets/icons/lock.svg'; static const String icChevronRight = 'assets/icons/chevron-right.svg'; static const String icQrcode = 'assets/icons/qrcode.svg'; static const String icGroup = 'assets/icons/group.svg'; static const String icSettings = 'assets/icons/settings.svg'; static const String icProfileFill = 'assets/icons/profile-fill.svg'; static const String icArchive = 'assets/icons/archive.svg'; static const String icMail = 'assets/icons/mail.svg'; static const String icDownload = 'assets/icons/download.svg'; static const String icSms = 'assets/icons/sms.svg'; static const String icArrowNarrowLeft = 'assets/icons/arrow-narrow-left.svg'; static const String icCameraRotate = 'assets/icons/camera-rotate.svg'; static const String icEngine = 'assets/icons/engine.svg'; static const String icWallet = 'assets/icons/wallet.svg'; static const String icCircleCheck = 'assets/icons/circle-check.svg'; static const String icEyeOffLight = 'assets/icons/eye-off-light.svg'; static const String icDashboard = 'assets/icons/dashboard.svg'; static const String icFlash = 'assets/icons/flash.svg'; static const String icArrowNarrowUp = 'assets/icons/arrow-narrow-up.svg'; static const String icMedalStar = 'assets/icons/medal-star.svg'; static const String icEyeOff = 'assets/icons/eye-off.svg'; static const String icArrowBarUp = 'assets/icons/arrow-bar-up.svg'; static const String icStarHalf = 'assets/icons/star-half.svg'; static const String icClipboardList = 'assets/icons/clipboard-list.svg'; static const String icPlus = 'assets/icons/plus.svg'; static const String icBoltOff = 'assets/icons/bolt-off.svg'; static const String icCheck = 'assets/icons/check.svg'; static const String icGlobal = 'assets/icons/global.svg'; static const String icCard = 'assets/icons/card.svg'; static const String icCopy = 'assets/icons/copy.svg'; static const String icBag = 'assets/icons/bag.svg'; static const String icFileDownload = 'assets/icons/file-download.svg'; static const String icFlatGoogle = 'assets/icons/flat-google.svg'; static const String icScan = 'assets/icons/scan.svg'; static const String icFullnameLight = 'assets/icons/fullname-light.svg'; static const String icMessageText = 'assets/icons/message-text.svg'; static const String icMessage = 'assets/icons/message.svg'; static const String icFlatApple = 'assets/icons/flat-apple.svg'; static const String icBox = 'assets/icons/box.svg'; static const String icMessage2 = 'assets/icons/message-2.svg'; static const String icNotification = 'assets/icons/notification.svg'; static const String icHeartFill = 'assets/icons/heart-fill.svg'; static const String icCoin = 'assets/icons/coin.svg'; static const String icPasswordLight = 'assets/icons/password-light.svg'; static const String icCamera = 'assets/icons/camera.svg'; static const String icPrinter = 'assets/icons/printer.svg'; static const String icBagFill = 'assets/icons/bag-fill.svg'; static const String icDeviceMobile = 'assets/icons/device-mobile.svg'; static const String icTrash = 'assets/icons/trash.svg'; static const String icAddressBook = 'assets/icons/address-book.svg'; static const String icStar = 'assets/icons/star.svg'; static const String icFaceId = 'assets/icons/face-id.svg'; static const String icSun = 'assets/icons/sun.svg'; static const String icHome2 = 'assets/icons/home-2.svg'; static const String icEdit = 'assets/icons/edit.svg'; static const String icAlertCircle = 'assets/icons/alert-circle.svg'; static const String icShareTwo = 'assets/icons/share-two.svg'; static const String icArrowNarrowDown = 'assets/icons/arrow-narrow-down.svg'; static const String icManualGearbox = 'assets/icons/manual-gearbox.svg'; static const String icTruckDelivery = 'assets/icons/truck-delivery.svg'; static const String icTicketDiscount = 'assets/icons/ticket-discount.svg'; static const String icDiamond = 'assets/icons/diamond.svg'; static const String icClock = 'assets/icons/clock.svg'; static const String icPhone = 'assets/icons/phone.svg'; static const String icEye = 'assets/icons/eye.svg'; static const String icCar = 'assets/icons/car.svg'; static const String icProfile = 'assets/icons/profile.svg'; static const String icShare = 'assets/icons/share.svg'; static const String icMoney = 'assets/icons/money.svg'; static const String icMoodSmile = 'assets/icons/mood-smile.svg'; static const String icMapPin = 'assets/icons/map-pin.svg'; static const String icFilter = 'assets/icons/filter.svg'; static const String icArrowNarrowRight = 'assets/icons/arrow-narrow-right.svg'; static const String icCalendar = 'assets/icons/calendar.svg'; static const String icLogo = 'assets/icons/Logo.svg'; static const String icBoxTick = 'assets/icons/box-tick.svg'; static const String icBookmark = 'assets/icons/Bookmark.svg'; static const String icChecks = 'assets/icons/checks.svg'; static const String icReceiptText = 'assets/icons/receipt-text.svg'; static const String icBuilding = 'assets/icons/building.svg'; static const String icArrowsSort = 'assets/icons/arrows-sort.svg'; static const String icUsers = 'assets/icons/users.svg'; static const String icFingerprint = 'assets/icons/fingerprint.svg'; static const String icTimer = 'assets/icons/timer.svg'; static const String icMinus = 'assets/icons/minus.svg'; static const String icPlayerPlay = 'assets/icons/player-play.svg'; static const String icPhoto = 'assets/icons/photo.svg'; static const String icChevronLeft = 'assets/icons/chevron-left.svg'; static const String icMoon = 'assets/icons/moon.svg'; static const String icDotsVertical = 'assets/icons/dots-vertical.svg'; static const String icBag1 = 'assets/icons/bag1.svg'; static const String icSend2 = 'assets/icons/send-2.svg'; static const String icHeart = 'assets/icons/heart.svg'; static const String icTrendingUp = 'assets/icons/trending-up.svg'; }
0
mirrored_repositories/yhshop_app/lib/core
mirrored_repositories/yhshop_app/lib/core/constants/img_resource.dart
abstract class ImgRes { const ImgRes._(); static const String img404 = 'assets/images/404.png'; static const String imgEmptyBag = 'assets/images/Empty-bag.png'; static const String imgFaceId = 'assets/images/Face-ID.png'; static const String imgGettingStarted = 'assets/images/getting_started.png'; static const String imgIntro1 = 'assets/images/intro_1.png'; static const String imgIntro2 = 'assets/images/intro_2.png'; static const String imgIntro3 = 'assets/images/intro_3.png'; static const String imgNoConnection = 'assets/images/No-Connection.png'; static const String imgNoOrders = 'assets/images/No-Orders.png'; static const String imgPassword = 'assets/images/password.png'; static const String imgProductNotFound = 'assets/images/Product-Not-Found.png'; static const String imgServerDown = 'assets/images/server_down.png'; static const String imgSuccessPayment = 'assets/images/Success-Payment.png'; }
0
mirrored_repositories/yhshop_app/lib/core
mirrored_repositories/yhshop_app/lib/core/use_cases/base_use_cases.dart
abstract class UseCase<Type, Params> { Future<Type> execute({Params? params}); }
0
mirrored_repositories/yhshop_app/lib/core/common
mirrored_repositories/yhshop_app/lib/core/common/validators/password_validate.dart
import 'package:formz/formz.dart'; enum PasswordValidationError { empty, invalid } class PasswordValidateModel extends FormzInput<String, String?> { const PasswordValidateModel.pure() : super.pure(''); const PasswordValidateModel.dirty([super.value = '']) : super.dirty(); @override String? validator(String value) { if(value.trim() == '') return 'Password is empty'; if(value.trim().length < 6) return 'Password too short'; return null; } }
0
mirrored_repositories/yhshop_app/lib/core/common
mirrored_repositories/yhshop_app/lib/core/common/validators/fullname_validate.dart
import 'package:formz/formz.dart'; enum FullNameValidationError { empty, invalid } class FullNameValidateModel extends FormzInput<String, FullNameValidationError?> { const FullNameValidateModel.pure() : super.pure(''); const FullNameValidateModel.dirty([super.value = '']) : super.dirty(); static final RegExp numericRegExp = RegExp(r'^-?\d+(\.\d+)?$'); // @override // String? validator(String value) { // if(value.trim().isEmpty) return "Fullname is empty"; // if(numericRegExp.hasMatch(value)) return FullNameValidationError.invalid; // return null; // } @override FullNameValidationError? validator(String value) { if(value.trim().isEmpty) return FullNameValidationError.empty; if(numericRegExp.hasMatch(value)) return FullNameValidationError.invalid; return null; } } extension StringFullNameValidationError on FullNameValidationError { String? toValue() { if(FullNameValidationError.empty == this) return 'Fullname is empty'; if(FullNameValidationError.invalid == this) return 'Fullname cannot be a number'; return null; } }
0
mirrored_repositories/yhshop_app/lib/core/common
mirrored_repositories/yhshop_app/lib/core/common/validators/email_validate.dart
import 'package:formz/formz.dart'; enum EmailValidationError { empty, invalid } class EmailValidateModel extends FormzInput<String, String?> { const EmailValidateModel.pure() : super.pure(''); const EmailValidateModel.dirty([super.value = '']) : super.dirty(); static final _emailRegExp = RegExp( r'^[a-zA-Z\d.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z\d-]+(?:\.[a-zA-Z\d-]+)*$', ); @override String? validator(String value) { if(value.trim().isEmpty) return "Email is empty"; if(!_emailRegExp.hasMatch(value)) return "Email is invalid"; return null; } }
0
mirrored_repositories/yhshop_app/lib/core/common
mirrored_repositories/yhshop_app/lib/core/common/extensions/context_extension.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; enum MessageType { error, success } extension ContextExtension on BuildContext { void hideKeyboard() { FocusScope.of(this).requestFocus(FocusNode()); } bool get isTablet { var shortestSide = MediaQuery.of(this).size.shortestSide; return shortestSide >= 600; } double get paddingTop => MediaQuery.of(this).padding.top; Future<void> copyText( String text, { bool showToast = true, VoidCallback? callback, }) { var data = ClipboardData(text: text); return Clipboard.setData(data).then((_) { callback?.call(); }).catchError((_) {}); } } extension NavigatorStateExtension on NavigatorState { void pushNamedIfNotCurrent(String routeName, {Object? arguments}) { if (!isCurrent(routeName)) { pushNamed(routeName, arguments: arguments); } } bool isCurrent(String routeName) { bool isCurrent = false; popUntil((route) { if (route.settings.name == routeName) { isCurrent = true; } return true; }); return isCurrent; } } extension ModalRouteExtension on BuildContext { ModalRoute? get modalRoute => ModalRoute.of(this); RouteSettings? get routeSettings => modalRoute?.settings; String? get routeName => routeSettings?.name; T args<T>() => modalRoute?.settings.arguments as T; } extension ThemeCtxExtension on BuildContext { ThemeData get theme => Theme.of(this); TargetPlatform get platform => theme.platform; bool get isAndroid => platform == TargetPlatform.android; bool get isIOS => platform == TargetPlatform.iOS; bool get isMacOS => platform == TargetPlatform.macOS; bool get isWindows => platform == TargetPlatform.windows; bool get isFuchsia => platform == TargetPlatform.fuchsia; } extension NavigatorExtension on BuildContext { NavigatorState get navigator => Navigator.of(this); Future<T?> push<T extends Object?>(Route<T> route) => navigator.push(route); Future<T?> toPage<T extends Object?>(Widget child) => navigator.push(CupertinoPageRoute(builder: (_) => child)); Future<T?> popToPage<T extends Object?>(Widget child) { navigator.pop(); return navigator.push(CupertinoPageRoute(builder: (_) => child)); } Future<T?> pushReplacement<T extends Object?, TO extends Object?>( Route<T> route, {TO? result}) => navigator.pushReplacement(route, result: result); Future<T?> pushNamed<T extends Object?>(String routeName, {Object? arguments}) { return navigator.pushNamed(routeName, arguments: arguments); } Future<T?> pushReplacementNamed<T extends Object?, TO extends Object?>( String routeName, {TO? result, Object? arguments}) { return navigator.pushReplacementNamed(routeName, result: result, arguments: arguments); } Future<T?> popAndPushNamed<T extends Object?, TO extends Object?>( String routeName, {TO? result, Object? arguments}) { return navigator.popAndPushNamed(routeName, result: result, arguments: arguments); } Future<T?> pushNamedAndRemoveUntil<T extends Object?>( String newRouteName, RoutePredicate predicate, {Object? arguments}) { return navigator.pushNamedAndRemoveUntil(newRouteName, predicate, arguments: arguments); } Future<T?> pushAndRemoveUntil<T extends Object?>( Route<T> newRoute, RoutePredicate predicate) { return navigator.pushAndRemoveUntil(newRoute, predicate); } void replace<T extends Object?>( {required Route<dynamic> oldRoute, required Route<T> newRoute}) => navigator.replace(oldRoute: oldRoute, newRoute: newRoute); void replaceRouteBelow<T extends Object?>( {required Route<dynamic> anchorRoute, required Route<T> newRoute}) => navigator.replaceRouteBelow(anchorRoute: anchorRoute, newRoute: newRoute); bool canPop() => navigator.canPop(); Future<bool> maybePop<T extends Object?>([T? result]) => navigator.maybePop(result); void pop<T extends Object?>([T? result]) { return navigator.pop(result); } }
0
mirrored_repositories/yhshop_app/lib/core/common
mirrored_repositories/yhshop_app/lib/core/common/extensions/int_extension.dart
extension IntExts on int { bool isZero() => this == 0; }
0
mirrored_repositories/yhshop_app/lib/core
mirrored_repositories/yhshop_app/lib/core/utils/logger.dart
import 'dart:developer' as dev; import 'package:flutter/cupertino.dart'; mixin LogMixin on Object { void log(Object? msg) { dev.log(msg.toString()); } dLog(String? msg) { debugPrint(msg); } }
0
mirrored_repositories/yhshop_app/lib/core
mirrored_repositories/yhshop_app/lib/core/utils/storage_lib.dart
import 'package:flutter/foundation.dart'; import 'package:hive/hive.dart'; import 'package:path_provider/path_provider.dart'; abstract class LocalStorage { LocalStorage._(); static const String dbName = 'local.database'; static late Box _box; static Future<void> initialize() async { if (!kIsWeb && !Hive.isBoxOpen(dbName)) Hive.init((await getApplicationDocumentsDirectory()).path); _box = await Hive.openBox(dbName); } static Future<void> put(String key, dynamic value) async { return await _box.put(key, value); } static Future<void> putAll(Map<dynamic, dynamic> value) async { return await _box.putAll(value); } static dynamic get(String key) { return _box.get(key); } static List<dynamic> getAll() { return _box.values.toList(); } static Map<dynamic, dynamic> getBoxMap() { return _box.toMap(); } static Future<void> delete(String key) { return _box.delete(key); } static Future<int> clear() { return _box.clear(); } } abstract class StoreKey { StoreKey._(); static const String auth = '@auth'; static const String assetToken = '@asset_token'; static const String intro = '@intro'; }
0
mirrored_repositories/yhshop_app/lib/core/utils
mirrored_repositories/yhshop_app/lib/core/utils/theme/theme_manager.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; abstract class ThemeManager { ThemeManager._(); static ThemeData get light => ThemeData( appBarTheme: const AppBarTheme( systemOverlayStyle: SystemUiOverlayStyle.dark, backgroundColor: Colors.white, elevation: .0), fontFamily: 'PlusJakartaSans', scaffoldBackgroundColor: Colors.white, ); }
0
mirrored_repositories/yhshop_app/lib/core/utils
mirrored_repositories/yhshop_app/lib/core/utils/navigation/app_navigator.dart
import 'package:flutter/material.dart'; import 'package:injectable/injectable.dart'; @singleton class AppNavigator { BuildContext? _context; BuildContext get context => _context!; void setContext(BuildContext ctx) { _context = ctx; } Future<dynamic> push(dynamic page, {dynamic arguments}) async { if (_context == null) return; return await Navigator.push( _context!, MaterialPageRoute<void>( builder: (BuildContext context) => page, ), ); } Future<dynamic> pushNamed(String routeName, {dynamic arguments}) async { if (_context == null) return; return await Navigator.pushNamed(_context!, routeName, arguments: arguments); } Future<dynamic> pushReplacementNamed(String routeName, {dynamic arguments, dynamic result}) async { if (_context == null) return; return await Navigator.pushReplacementNamed(_context!, routeName, arguments: arguments, result: result); } Future<dynamic> pushNamedAndRemoveUntil(String routeName, {dynamic arguments}) async { if (_context == null) return; return await Navigator.pushNamedAndRemoveUntil( _context!, routeName, (Route<dynamic> route) => false, arguments: arguments, ); } void pop({dynamic result}) async { if (_context == null) return; Navigator.of(_context!).pop(); } }
0
mirrored_repositories/yhshop_app/lib/core/utils
mirrored_repositories/yhshop_app/lib/core/utils/navigation/route_path.dart
import 'package:flutter/material.dart'; @immutable abstract class RoutePath { static const String initial = '/'; static const String home = '/home'; static const String login = '/login'; static const String register = '/register'; static const String gettingStarted = '/getting-started'; static const String enterOTP = '/enter-otp'; } class TopRoute { final String path; const TopRoute(this.path); }
0
mirrored_repositories/yhshop_app/lib/core/utils
mirrored_repositories/yhshop_app/lib/core/utils/navigation/page_manager.dart
import 'package:app_bloc/core/utils/navigation/route_path.dart'; import 'package:app_bloc/presentation/enter_otp/enter_otp_page.dart'; import 'package:app_bloc/presentation/getting_started/getting_started_page.dart'; import 'package:app_bloc/presentation/home/home_page.dart'; import 'package:app_bloc/presentation/register/register_page.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../presentation/login/login_page.dart'; import '../../../presentation/initial/initial_page.dart'; Map<String, WidgetBuilder> routes = { RoutePath.initial: (_) => const InitialPage(), RoutePath.home: (_) => const HomePage(), RoutePath.gettingStarted: (_) => const GettingStartedPage(), RoutePath.login: (_) => LoginPage(), RoutePath.register: (_) => RegisterPage(), RoutePath.enterOTP: (_) => EnterOTPPage() }; Route<dynamic> generateRoutes(RouteSettings settings) { String? routeName = settings.name?.split('?').first; return CupertinoPageRoute( builder: routes[routeName] ?? (_) => const Scaffold( body: Text("empty route"), ), settings: settings); }
0
mirrored_repositories/yhshop_app/lib/core
mirrored_repositories/yhshop_app/lib/core/base/app_bloc_observer.dart
import 'package:app_bloc/core/utils/logger.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class AppBlocObserver extends BlocObserver with LogMixin { @override void onChange(BlocBase bloc, Change change) { super.onChange(bloc, change); // dLog('[BLOC_CHANGE]: $bloc'); } @override void onCreate(BlocBase bloc) { super.onCreate(bloc); dLog('[BLOC_CREATE]: $bloc'); } @override void onError(BlocBase bloc, Object error, StackTrace stackTrace) { super.onError(bloc, error, stackTrace); dLog('[BLOC_ERROR]: $error'); } @override void onTransition(Bloc bloc, Transition transition) { super.onTransition(bloc, transition); // dLog('[BLOC TRANSITION]: $transition'); } @override void onClose(BlocBase bloc) { super.onClose(bloc); // dLog('[BLOC_CLOSE]: $bloc'); } @override void onEvent(Bloc bloc, Object? event) { super.onEvent(bloc, event); // dLog('[BLOC_EVENT]: $bloc - $event'); } }
0