code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
import 'dart:async'; import 'package:github_search/github_api.dart'; import 'package:github_search/search_bloc.dart'; import 'package:github_search/search_state.dart'; import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; class MockGithubApi extends Mock implements GithubApi {} void main() { group('SearchBloc', () { test('starts with an initial no term state', () { final api = MockGithubApi(); final bloc = SearchBloc(api); expect( bloc.state, emitsInOrder([noTerm]), ); }); test('emits a loading state then result state when api call succeeds', () { final api = MockGithubApi(); final bloc = SearchBloc(api); when(api.search('T')).thenAnswer( (_) async => SearchResult([SearchResultItem('A', 'B', 'C')])); scheduleMicrotask(() { bloc.onTextChanged.add('T'); }); expect( bloc.state, emitsInOrder([noTerm, loading, populated]), ); }); test('emits a no term state when user provides an empty search term', () { final api = MockGithubApi(); final bloc = SearchBloc(api); scheduleMicrotask(() { bloc.onTextChanged.add(''); }); expect( bloc.state, emitsInOrder([noTerm, noTerm]), ); }); test('emits an empty state when no results are returned', () { final api = MockGithubApi(); final bloc = SearchBloc(api); when(api.search('T')).thenAnswer((_) async => SearchResult([])); scheduleMicrotask(() { bloc.onTextChanged.add('T'); }); expect( bloc.state, emitsInOrder([noTerm, loading, empty]), ); }); test('throws an error when the backend errors', () { final api = MockGithubApi(); final bloc = SearchBloc(api); when(api.search('T')).thenThrow(Exception()); scheduleMicrotask(() { bloc.onTextChanged.add('T'); }); expect( bloc.state, emitsInOrder([noTerm, loading, error]), ); }); test('closes the stream on dispose', () { final api = MockGithubApi(); final bloc = SearchBloc(api); scheduleMicrotask(() { bloc.dispose(); }); expect( bloc.state, emitsInOrder([noTerm, emitsDone]), ); }); }); } const noTerm = TypeMatcher<SearchNoTerm>(); const loading = TypeMatcher<SearchLoading>(); const empty = TypeMatcher<SearchEmpty>(); const populated = TypeMatcher<SearchPopulated>(); const error = TypeMatcher<SearchError>();
rxdart/example/flutter/github_search/test/search_bloc_test.dart/0
{'file_path': 'rxdart/example/flutter/github_search/test/search_bloc_test.dart', 'repo_id': 'rxdart', 'token_count': 1058}
import 'dart:async'; /// Returns a Stream that, when listening to it, calls a function you specify /// and then emits the value returned from that function. /// /// If result from invoking [callable] function: /// - Is a [Future]: when the future completes, this stream will fire one event, either /// data or error, and then close with a done-event. /// - Is a [T]: this stream emits a single data event and then completes with a done event. /// /// By default, a [FromCallableStream] is a single-subscription Stream. However, it's possible /// to make them reusable. /// This Stream is effectively equivalent to one created by /// `(() async* { yield await callable() }())` or `(() async* { yield callable(); }())`. /// /// [ReactiveX doc](http://reactivex.io/documentation/operators/from.html) /// /// ### Example /// /// FromCallableStream(() => 'Value').listen(print); // prints Value /// /// FromCallableStream(() async { /// await Future<void>.delayed(const Duration(seconds: 1)); /// return 'Value'; /// }).listen(print); // prints Value class FromCallableStream<T> extends Stream<T> { Stream<T> _stream; /// A function will be called at subscription time. final FutureOr<T> Function() callable; final bool _isReusable; /// Construct a Stream that, when listening to it, calls a function you specify /// and then emits the value returned from that function. /// [reusable] indicates whether this Stream can be listened to multiple times or not. FromCallableStream(this.callable, {bool reusable = false}) : _isReusable = reusable; @override bool get isBroadcast => _isReusable; @override StreamSubscription<T> listen( void Function(T event) onData, { Function onError, void Function() onDone, bool cancelOnError, }) { if (_isReusable || _stream == null) { try { final value = callable(); _stream = value is Future<T> ? Stream.fromFuture(value) : Stream.value(value as T); } catch (e, s) { _stream = Stream.error(e, s); } } return _stream.listen( onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError, ); } }
rxdart/lib/src/streams/from_callable.dart/0
{'file_path': 'rxdart/lib/src/streams/from_callable.dart', 'repo_id': 'rxdart', 'token_count': 744}
import 'dart:async'; import 'package:rxdart/src/rx.dart'; import 'package:rxdart/src/streams/value_stream.dart'; import 'package:rxdart/src/subjects/subject.dart'; import 'package:rxdart/src/transformers/start_with.dart'; import 'package:rxdart/src/transformers/start_with_error.dart'; import 'package:rxdart/src/utils/error_and_stacktrace.dart'; /// A special StreamController that captures the latest item that has been /// added to the controller, and emits that as the first item to any new /// listener. /// /// This subject allows sending data, error and done events to the listener. /// The latest item that has been added to the subject will be sent to any /// new listeners of the subject. After that, any new events will be /// appropriately sent to the listeners. It is possible to provide a seed value /// that will be emitted if no items have been added to the subject. /// /// BehaviorSubject is, by default, a broadcast (aka hot) controller, in order /// to fulfill the Rx Subject contract. This means the Subject's `stream` can /// be listened to multiple times. /// /// ### Example /// /// final subject = BehaviorSubject<int>(); /// /// subject.add(1); /// subject.add(2); /// subject.add(3); /// /// subject.stream.listen(print); // prints 3 /// subject.stream.listen(print); // prints 3 /// subject.stream.listen(print); // prints 3 /// /// ### Example with seed value /// /// final subject = BehaviorSubject<int>.seeded(1); /// /// subject.stream.listen(print); // prints 1 /// subject.stream.listen(print); // prints 1 /// subject.stream.listen(print); // prints 1 class BehaviorSubject<T> extends Subject<T> implements ValueStream<T> { final _Wrapper<T> _wrapper; final Stream<T> _stream; BehaviorSubject._( StreamController<T> controller, this._stream, this._wrapper, ) : super(controller, _stream); /// Constructs a [BehaviorSubject], optionally pass handlers for /// [onListen], [onCancel] and a flag to handle events [sync]. /// /// See also [StreamController.broadcast] factory BehaviorSubject({ void Function() onListen, void Function() onCancel, bool sync = false, }) { // ignore: close_sinks final controller = StreamController<T>.broadcast( onListen: onListen, onCancel: onCancel, sync: sync, ); final wrapper = _Wrapper<T>(); return BehaviorSubject<T>._( controller, Rx.defer<T>(_deferStream(wrapper, controller, sync), reusable: true), wrapper); } /// Constructs a [BehaviorSubject], optionally pass handlers for /// [onListen], [onCancel] and a flag to handle events [sync]. /// /// [seedValue] becomes the current [value] and is emitted immediately. /// /// See also [StreamController.broadcast] factory BehaviorSubject.seeded( T seedValue, { void Function() onListen, void Function() onCancel, bool sync = false, }) { // ignore: close_sinks final controller = StreamController<T>.broadcast( onListen: onListen, onCancel: onCancel, sync: sync, ); final wrapper = _Wrapper<T>.seeded(seedValue); return BehaviorSubject<T>._( controller, Rx.defer<T>(_deferStream(wrapper, controller, sync), reusable: true), wrapper, ); } static Stream<T> Function() _deferStream<T>( _Wrapper<T> wrapper, StreamController<T> controller, bool sync) => () { if (wrapper.latestIsError) { final errorAndStackTrace = wrapper.latestErrorAndStackTrace; return controller.stream.transform( StartWithErrorStreamTransformer( errorAndStackTrace.error, errorAndStackTrace.stackTrace, ), ); } else if (wrapper.latestIsValue) { return controller.stream .transform(StartWithStreamTransformer(wrapper.latestValue)); } return controller.stream; }; @override void onAdd(T event) => _wrapper.setValue(event); @override void onAddError(Object error, [StackTrace stackTrace]) => _wrapper.setError(error, stackTrace); @override ValueStream<T> get stream => this; @override bool get hasValue => _wrapper.latestIsValue; /// Get the latest value emitted by the Subject @override T get value => _wrapper.latestValue; /// Set and emit the new value set value(T newValue) => add(newValue); @override bool get hasError => _wrapper.latestIsError; @override ErrorAndStackTrace get errorAndStackTrace => _wrapper.latestErrorAndStackTrace; @override BehaviorSubject<R> createForwardingSubject<R>({ void Function() onListen, void Function() onCancel, bool sync = false, }) => BehaviorSubject( onListen: onListen, onCancel: onCancel, sync: sync, ); // Override built-in operators. @override ValueStream<T> where(bool Function(T event) test) => _forwardBehaviorSubject<T>((s) => s.where(test)); @override ValueStream<S> map<S>(S Function(T event) convert) => _forwardBehaviorSubject<S>((s) => s.map(convert)); @override ValueStream<E> asyncMap<E>(FutureOr<E> Function(T event) convert) => _forwardBehaviorSubject<E>((s) => s.asyncMap(convert)); @override ValueStream<E> asyncExpand<E>(Stream<E> Function(T event) convert) => _forwardBehaviorSubject<E>((s) => s.asyncExpand(convert)); @override ValueStream<T> handleError(Function onError, {bool Function(Object error) test}) => _forwardBehaviorSubject<T>((s) => s.handleError(onError, test: test)); @override ValueStream<S> expand<S>(Iterable<S> Function(T element) convert) => _forwardBehaviorSubject<S>((s) => s.expand(convert)); @override ValueStream<S> transform<S>(StreamTransformer<T, S> streamTransformer) => _forwardBehaviorSubject<S>((s) => s.transform(streamTransformer)); @override ValueStream<R> cast<R>() => _forwardBehaviorSubject<R>((s) => s.cast<R>()); @override ValueStream<T> take(int count) => _forwardBehaviorSubject<T>((s) => s.take(count)); @override ValueStream<T> takeWhile(bool Function(T element) test) => _forwardBehaviorSubject<T>((s) => s.takeWhile(test)); @override ValueStream<T> skip(int count) => _forwardBehaviorSubject<T>((s) => s.skip(count)); @override ValueStream<T> skipWhile(bool Function(T element) test) => _forwardBehaviorSubject<T>((s) => s.skipWhile(test)); @override ValueStream<T> distinct([bool Function(T previous, T next) equals]) => _forwardBehaviorSubject<T>((s) => s.distinct(equals)); @override ValueStream<T> timeout(Duration timeLimit, {void Function(EventSink<T> sink) onTimeout}) => _forwardBehaviorSubject<T>( (s) => s.timeout(timeLimit, onTimeout: onTimeout)); ValueStream<R> _forwardBehaviorSubject<R>( Stream<R> Function(Stream<T> s) transformerStream) { ArgumentError.checkNotNull(transformerStream, 'transformerStream'); BehaviorSubject<R> subject; StreamSubscription<R> subscription; final onListen = () => subscription = transformerStream(_stream).listen( subject.add, onError: subject.addError, onDone: subject.close, ); final onCancel = () => subscription.cancel(); return subject = createForwardingSubject( onListen: onListen, onCancel: onCancel, sync: true, ); } } class _Wrapper<T> { T latestValue; ErrorAndStackTrace latestErrorAndStackTrace; bool latestIsValue = false, latestIsError = false; /// Non-seeded constructor _Wrapper(); _Wrapper.seeded(this.latestValue) : latestIsValue = true; void setValue(T event) { latestIsValue = true; latestIsError = false; latestValue = event; latestErrorAndStackTrace = null; } void setError(Object error, [StackTrace stackTrace]) { latestIsValue = false; latestIsError = true; latestValue = null; latestErrorAndStackTrace = ErrorAndStackTrace(error, stackTrace); } }
rxdart/lib/src/subjects/behavior_subject.dart/0
{'file_path': 'rxdart/lib/src/subjects/behavior_subject.dart', 'repo_id': 'rxdart', 'token_count': 2908}
import 'dart:async'; class _EndWithStreamSink<S> implements EventSink<S> { final S _endValue; final EventSink<S> _outputSink; _EndWithStreamSink(this._outputSink, this._endValue); @override void add(S data) => _outputSink.add(data); @override void addError(e, [st]) => _outputSink.addError(e, st); @override void close() { _outputSink.add(_endValue); _outputSink.close(); } } /// Appends a value to the source [Stream] before closing. /// /// ### Example /// /// Stream.fromIterable([2]) /// .transform(EndWithStreamTransformer(1)) /// .listen(print); // prints 2, 1 class EndWithStreamTransformer<S> extends StreamTransformerBase<S, S> { /// The ending event of this [Stream] final S endValue; /// Constructs a [StreamTransformer] which appends the source [Stream] /// with [endValue] just before it closes. EndWithStreamTransformer(this.endValue); @override Stream<S> bind(Stream<S> stream) => Stream.eventTransformed( stream, (sink) => _EndWithStreamSink<S>(sink, endValue)); } /// Extends the [Stream] class with the ability to emit the given value as the /// final item before closing. extension EndWithExtension<T> on Stream<T> { /// Appends a value to the source [Stream] before closing. /// /// ### Example /// /// Stream.fromIterable([2]).endWith(1).listen(print); // prints 2, 1 Stream<T> endWith(T endValue) => transform(EndWithStreamTransformer<T>(endValue)); }
rxdart/lib/src/transformers/end_with.dart/0
{'file_path': 'rxdart/lib/src/transformers/end_with.dart', 'repo_id': 'rxdart', 'token_count': 515}
import 'dart:async'; import 'package:rxdart/src/utils/forwarding_sink.dart'; import 'package:rxdart/src/utils/forwarding_stream.dart'; class _StartWithManyStreamSink<S> implements ForwardingSink<S, S> { final Iterable<S> _startValues; var _isFirstEventAdded = false; _StartWithManyStreamSink(this._startValues); @override void add(EventSink<S> sink, S data) { _safeAddFirstEvent(sink); sink.add(data); } @override void addError(EventSink<S> sink, dynamic e, [st]) { _safeAddFirstEvent(sink); sink.addError(e, st); } @override void close(EventSink<S> sink) { _safeAddFirstEvent(sink); sink.close(); } @override FutureOr onCancel(EventSink<S> sink) {} @override void onListen(EventSink<S> sink) { scheduleMicrotask(() => _safeAddFirstEvent(sink)); } @override void onPause(EventSink<S> sink) {} @override void onResume(EventSink<S> sink) {} // Immediately setting the starting value when onListen trigger can // result in an Exception (might be a bug in dart:async?) // Therefore, scheduleMicrotask is used after onListen. // Because events could be added before scheduleMicrotask completes, // this method is ran before any other events might be added. // Once the first event(s) is/are successfully added, this method // will not trigger again. void _safeAddFirstEvent(EventSink<S> sink) { if (_isFirstEventAdded) return; _startValues.forEach(sink.add); _isFirstEventAdded = true; } } /// Prepends a sequence of values to the source [Stream]. /// /// ### Example /// /// Stream.fromIterable([3]) /// .transform(StartWithManyStreamTransformer([1, 2])) /// .listen(print); // prints 1, 2, 3 class StartWithManyStreamTransformer<S> extends StreamTransformerBase<S, S> { /// The starting events of this [Stream] final Iterable<S> startValues; /// Constructs a [StreamTransformer] which prepends the source [Stream] /// with [startValues]. StartWithManyStreamTransformer(this.startValues) { if (startValues == null) { throw ArgumentError('startValues cannot be null'); } } @override Stream<S> bind(Stream<S> stream) => forwardStream(stream, _StartWithManyStreamSink(startValues)); } /// Extends the [Stream] class with the ability to emit the given values as the /// first items. extension StartWithManyExtension<T> on Stream<T> { /// Prepends a sequence of values to the source [Stream]. /// /// ### Example /// /// Stream.fromIterable([3]).startWithMany([1, 2]) /// .listen(print); // prints 1, 2, 3 Stream<T> startWithMany(List<T> startValues) => transform(StartWithManyStreamTransformer<T>(startValues)); }
rxdart/lib/src/transformers/start_with_many.dart/0
{'file_path': 'rxdart/lib/src/transformers/start_with_many.dart', 'repo_id': 'rxdart', 'token_count': 930}
library rx_subjects; export 'src/subjects/behavior_subject.dart'; export 'src/subjects/publish_subject.dart'; export 'src/subjects/replay_subject.dart'; export 'src/subjects/subject.dart';
rxdart/lib/subjects.dart/0
{'file_path': 'rxdart/lib/subjects.dart', 'repo_id': 'rxdart', 'token_count': 69}
import 'dart:async'; import 'package:rxdart/rxdart.dart'; import 'package:rxdart/src/streams/repeat.dart'; import 'package:test/test.dart'; void main() { test('Rx.repeat', () async { const retries = 3; await expectLater(Rx.repeat(_getRepeatStream('A'), retries), emitsInOrder(<dynamic>['A0', 'A1', 'A2', emitsDone])); }); test('RepeatStream', () async { const retries = 3; await expectLater(RepeatStream(_getRepeatStream('A'), retries), emitsInOrder(<dynamic>['A0', 'A1', 'A2', emitsDone])); }); test('RepeatStream.onDone', () async { const retries = 0; await expectLater(RepeatStream(_getRepeatStream('A'), retries), emitsDone); }); test('RepeatStream.infinite.repeats', () async { await expectLater( RepeatStream(_getRepeatStream('A')), emitsThrough('A100')); }); test('RepeatStream.single.subscription', () async { const retries = 3; final stream = RepeatStream(_getRepeatStream('A'), retries); try { stream.listen(null); stream.listen(null); } catch (e) { await expectLater(e, isStateError); } }); test('RepeatStream.asBroadcastStream', () async { const retries = 3; final stream = RepeatStream(_getRepeatStream('A'), retries).asBroadcastStream(); // listen twice on same stream stream.listen(null); stream.listen(null); // code should reach here await expectLater(stream.isBroadcast, isTrue); }); test('RepeatStream.error.shouldThrow', () async { final streamWithError = RepeatStream(_getErroneusRepeatStream('A'), 2); await expectLater( streamWithError, emitsInOrder(<dynamic>[ 'A0', emitsError(TypeMatcher<Error>()), 'A0', emitsError(TypeMatcher<Error>()), emitsDone ])); }); test('RepeatStream.pause.resume', () async { StreamSubscription<String> subscription; const retries = 3; subscription = RepeatStream(_getRepeatStream('A'), retries) .listen(expectAsync1((result) { expect(result, 'A0'); subscription.cancel(); })); subscription.pause(); subscription.resume(); }); } Stream<String> Function(int) _getRepeatStream(String symbol) => (int repeatIndex) async* { yield await Future.delayed( const Duration(milliseconds: 20), () => '$symbol$repeatIndex'); }; Stream<String> Function(int) _getErroneusRepeatStream(String symbol) => (int repeatIndex) { return Stream.value('A0') // Emit the error .concatWith([Stream<String>.error(Error())]); };
rxdart/test/streams/repeat_test.dart/0
{'file_path': 'rxdart/test/streams/repeat_test.dart', 'repo_id': 'rxdart', 'token_count': 1012}
import 'dart:async'; import 'package:rxdart/rxdart.dart'; import 'package:test/test.dart'; /// yield immediately, then every 100ms Stream<int> getStream(int n) async* { var k = 1; yield 0; while (k < n) { yield await Future<Null>.delayed(const Duration(milliseconds: 100)) .then((_) => k++); } } void main() { test('Rx.bufferTime', () async { await expectLater( getStream(4).bufferTime(const Duration(milliseconds: 160)), emitsInOrder(<dynamic>[ const [0, 1], const [2, 3], emitsDone ])); }); test('Rx.bufferTime.shouldClose', () async { final controller = StreamController<int>()..add(0)..add(1)..add(2)..add(3); scheduleMicrotask(controller.close); await expectLater( controller.stream.bufferTime(const Duration(seconds: 3)).take(1), emitsInOrder(<dynamic>[ const [0, 1, 2, 3], // done emitsDone ])); }); test('Rx.bufferTime.reusable', () async { final transformer = BufferStreamTransformer<int>( (_) => Stream<void>.periodic(const Duration(milliseconds: 160))); await expectLater( getStream(4).transform(transformer), emitsInOrder(<dynamic>[ const [0, 1], const [2, 3], // done emitsDone ])); await expectLater( getStream(4).transform(transformer), emitsInOrder(<dynamic>[ const [0, 1], const [2, 3], // done emitsDone ])); }); test('Rx.bufferTime.asBroadcastStream', () async { final stream = getStream(4) .asBroadcastStream() .bufferTime(const Duration(milliseconds: 160)); // listen twice on same stream await expectLater( stream, emitsInOrder(<dynamic>[ const [0, 1], const [2, 3], emitsDone ])); await expectLater(stream, emitsInOrder(<dynamic>[emitsDone])); }); test('Rx.bufferTime.error.shouldThrowA', () async { await expectLater( Stream<void>.error(Exception()) .bufferTime(const Duration(milliseconds: 160)), emitsError(isException)); }); test('Rx.bufferTime.error.shouldThrowB', () { expect(() => Stream.fromIterable(const [1, 2, 3, 4]).bufferTime(null), throwsArgumentError); }); }
rxdart/test/transformers/backpressure/buffer_time_test.dart/0
{'file_path': 'rxdart/test/transformers/backpressure/buffer_time_test.dart', 'repo_id': 'rxdart', 'token_count': 986}
import 'dart:async'; import 'package:test/test.dart'; void main() { test('Rx.distinct', () async { const expected = 1; final stream = Stream.fromIterable(const [expected, expected]).distinct(); stream.listen(expectAsync1((actual) { expect(actual, expected); })); }); test('Rx.distinct accidental broadcast', () async { final controller = StreamController<int>(); final stream = controller.stream.distinct(); stream.listen(null); expect(() => stream.listen(null), throwsStateError); controller.add(1); }); }
rxdart/test/transformers/distinct_test.dart/0
{'file_path': 'rxdart/test/transformers/distinct_test.dart', 'repo_id': 'rxdart', 'token_count': 197}
import 'dart:async'; import 'package:rxdart/rxdart.dart'; import 'package:test/test.dart'; void main() { test('Rx.min', () async { await expectLater(_getStream().min(), completion(0)); expect( await Stream.fromIterable(<num>[1, 2, 3, 3.5]).min(), 1, ); }); test('Rx.min.empty.shouldThrow', () { expect( () => Stream<int>.empty().min(), throwsStateError, ); }); test('Rx.min.error.shouldThrow', () { expect( () => Stream.value(1).concatWith( [Stream.error(Exception('This is exception'))], ).min(), throwsException, ); }); test('Rx.min.errorComparator.shouldThrow', () { expect( () => _getStream().min((a, b) => throw Exception()), throwsException, ); }); test('Rx.min.with.comparator', () async { await expectLater( Stream.fromIterable(['one', 'two', 'three']) .min((a, b) => a.length - b.length), completion('one'), ); }); test('Rx.min.without.comparator.Comparable', () async { const expected = _Class2(-1); expect( await Stream.fromIterable(const [ _Class2(0), _Class2(3), _Class2(2), expected, _Class2(2), ]).min(), expected, ); }); test('Rx.min.without.comparator.not.Comparable', () async { expect( () => Stream.fromIterable(const [ _Class1(0), _Class1(3), _Class1(2), _Class1(3), _Class1(2), ]).min(), throwsStateError, ); }); } Stream<int> _getStream() => Stream<int>.fromIterable(const <int>[2, 3, 3, 5, 2, 9, 1, 2, 0]); class _Class1 { final int value; const _Class1(this.value); @override bool operator ==(Object other) => identical(this, other) || other is _Class1 && runtimeType == other.runtimeType && value == other.value; @override int get hashCode => value.hashCode; @override String toString() => '_Class{value: $value}'; } class _Class2 implements Comparable<_Class2> { final int value; const _Class2(this.value); @override String toString() => '_Class2{value: $value}'; @override bool operator ==(Object other) => identical(this, other) || other is _Class2 && runtimeType == other.runtimeType && value == other.value; @override int get hashCode => value.hashCode; @override int compareTo(_Class2 other) => value.compareTo(other.value); }
rxdart/test/transformers/min_test.dart/0
{'file_path': 'rxdart/test/transformers/min_test.dart', 'repo_id': 'rxdart', 'token_count': 1072}
import 'dart:async'; import 'package:rxdart/rxdart.dart'; import 'package:test/test.dart'; Stream<Object> _getStream() { final controller = StreamController<dynamic>(); Timer(const Duration(milliseconds: 100), () => controller.add(1)); Timer(const Duration(milliseconds: 200), () => controller.add('2')); Timer( const Duration(milliseconds: 300), () => controller.add(const {'3': 3})); Timer(const Duration(milliseconds: 400), () { controller.add(const {'4': '4'}); }); Timer(const Duration(milliseconds: 500), () { controller.add(5.0); controller.close(); }); return controller.stream; } void main() { test('Rx.whereType', () async { _getStream().whereType<Map<String, int>>().listen(expectAsync1((result) { expect(result, isMap); }, count: 1)); }); test('Rx.whereType.polymorphism', () async { _getStream().whereType<num>().listen(expectAsync1((result) { expect(result is num, true); }, count: 2)); }); test('Rx.whereType.null.values', () async { await expectLater( Stream.fromIterable([null, 1, null, 'two', 3]).whereType<String>(), emitsInOrder(const <String>['two'])); }); test('Rx.whereType.asBroadcastStream', () async { final stream = _getStream().asBroadcastStream().whereType<int>(); // listen twice on same stream stream.listen(null); stream.listen(null); // code should reach here await expectLater(true, true); }); test('Rx.whereType.error.shouldThrow', () async { final streamWithError = Stream<void>.error(Exception()).whereType<num>(); streamWithError.listen(null, onError: expectAsync2((Exception e, StackTrace s) { expect(e, isException); })); }); test('Rx.whereType.pause.resume', () async { StreamSubscription<int> subscription; final stream = Stream.value(1).whereType<int>(); subscription = stream.listen(expectAsync1((value) { expect(value, 1); subscription.cancel(); }, count: 1)); subscription.pause(); subscription.resume(); }); test('Rx.whereType accidental broadcast', () async { final controller = StreamController<int>(); final stream = controller.stream.whereType<int>(); stream.listen(null); expect(() => stream.listen(null), throwsStateError); controller.add(1); }); }
rxdart/test/transformers/where_type_test.dart/0
{'file_path': 'rxdart/test/transformers/where_type_test.dart', 'repo_id': 'rxdart', 'token_count': 868}
include: package:analysis_defaults/flutter.yaml
samples/add_to_app/multiple_flutters/multiple_flutters_module/analysis_options.yaml/0
{'file_path': 'samples/add_to_app/multiple_flutters/multiple_flutters_module/analysis_options.yaml', 'repo_id': 'samples', 'token_count': 14}
include: package:analysis_defaults/flutter.yaml
samples/android_splash_screen/analysis_options.yaml/0
{'file_path': 'samples/android_splash_screen/analysis_options.yaml', 'repo_id': 'samples', 'token_count': 15}
include: package:analysis_defaults/flutter.yaml
samples/animations/analysis_options.yaml/0
{'file_path': 'samples/animations/analysis_options.yaml', 'repo_id': 'samples', 'token_count': 15}
// Copyright 2019 The Flutter team. 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:ui' as ui; import 'package:flutter/material.dart'; class CarouselDemo extends StatelessWidget { CarouselDemo({super.key}); static String routeName = 'misc/carousel'; static const List<String> fileNames = [ 'assets/eat_cape_town_sm.jpg', 'assets/eat_new_orleans_sm.jpg', 'assets/eat_sydney_sm.jpg', ]; final List<Widget> images = fileNames.map((file) => Image.asset(file, fit: BoxFit.cover)).toList(); @override Widget build(context) { return Scaffold( appBar: AppBar( title: const Text('Carousel Demo'), ), body: Center( child: Padding( padding: const EdgeInsets.all(16), child: AspectRatio( aspectRatio: 1, child: Carousel(itemBuilder: widgetBuilder), ), ), ), ); } Widget widgetBuilder(BuildContext context, int index) { return images[index % images.length]; } } typedef OnCurrentItemChangedCallback = void Function(int currentItem); class Carousel extends StatefulWidget { final IndexedWidgetBuilder itemBuilder; const Carousel({super.key, required this.itemBuilder}); @override State<Carousel> createState() => _CarouselState(); } class _CarouselState extends State<Carousel> { late final PageController _controller; late int _currentPage; bool _pageHasChanged = false; @override void initState() { super.initState(); _currentPage = 0; _controller = PageController( viewportFraction: .85, initialPage: _currentPage, ); } @override Widget build(context) { var size = MediaQuery.of(context).size; return PageView.builder( onPageChanged: (value) { setState(() { _pageHasChanged = true; _currentPage = value; }); }, controller: _controller, scrollBehavior: ScrollConfiguration.of(context).copyWith( dragDevices: { ui.PointerDeviceKind.touch, ui.PointerDeviceKind.mouse, }, ), itemBuilder: (context, index) => AnimatedBuilder( animation: _controller, builder: (context, child) { var result = _pageHasChanged ? _controller.page! : _currentPage * 1.0; // The horizontal position of the page between a 1 and 0 var value = result - index; value = (1 - (value.abs() * .5)).clamp(0.0, 1.0); return Center( child: SizedBox( height: Curves.easeOut.transform(value) * size.height, width: Curves.easeOut.transform(value) * size.width, child: child, ), ); }, child: widget.itemBuilder(context, index), ), ); } @override void dispose() { _controller.dispose(); super.dispose(); } }
samples/animations/lib/src/misc/carousel.dart/0
{'file_path': 'samples/animations/lib/src/misc/carousel.dart', 'repo_id': 'samples', 'token_count': 1217}
// Copyright 2023 The Flutter team. 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:animations/src/basics/basics.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; Widget createAnimatedBuilderDemoScreen() => const MaterialApp( home: AnimatedBuilderDemo(), ); void main() { group('AnimatedBuilder Tests', () { testWidgets('AnimatedBuilder changes button color', (tester) async { await tester.pumpWidget(createAnimatedBuilderDemoScreen()); // Get the initial color of the button. ElevatedButton button = tester.widget(find.byType(ElevatedButton)); MaterialStateProperty<Color?>? initialColor = button.style!.backgroundColor; // Tap the button. await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); // Get the updated color of the button. button = tester.widget(find.byType(ElevatedButton)); MaterialStateProperty<Color?>? updatedColor = button.style!.backgroundColor; // Check if the color has changed. expect(initialColor, isNot(updatedColor)); }); testWidgets('AnimatedBuilder animates button color', (tester) async { await tester.pumpWidget(createAnimatedBuilderDemoScreen()); // Get the initial color of the button. ElevatedButton button = tester.widget(find.byType(ElevatedButton)); MaterialStateProperty<Color?>? initialColor = button.style!.backgroundColor; // Tap the button to trigger the animation but don't wait for it to finish. await tester.tap(find.byType(ElevatedButton)); await tester.pump(); await tester.pump(const Duration(milliseconds: 400)); // Check that the color has changed but not to the final color. button = tester.widget(find.byType(ElevatedButton)); MaterialStateProperty<Color?>? changedColor = button.style!.backgroundColor; expect(initialColor, isNot(changedColor)); // Wait for the animation to finish. await tester.pump(const Duration(milliseconds: 400)); // Check that the color has changed to the final color. button = tester.widget(find.byType(ElevatedButton)); MaterialStateProperty<Color?>? finalColor = button.style!.backgroundColor; expect(changedColor, isNot(finalColor)); }); }); }
samples/animations/test/basics/animated_builder_test.dart/0
{'file_path': 'samples/animations/test/basics/animated_builder_test.dart', 'repo_id': 'samples', 'token_count': 842}
import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart'; import 'package:test/test.dart'; // Manual test: // $ dart bin/server.dart // $ curl -X POST -d '{"by": 1}' -H "Content-Type: application/json" localhost:8080/ void main() { final port = '8080'; final host = 'http://0.0.0.0:$port'; late Process p; group( 'Integration test should', () { setUp(() async { p = await Process.start( 'dart', ['run', 'bin/server.dart'], environment: {'PORT': port}, ); // Wait for server to start and print to stdout. await p.stdout.first; }); tearDown(() => p.kill()); test('Increment', () async { final response = await post(Uri.parse('$host/'), body: '{"by": 1}'); expect(response.statusCode, 200); expect(response.body, '{"value":1}'); }); test('Get', () async { final response = await get(Uri.parse('$host/')); expect(response.statusCode, 200); final resp = json.decode(response.body) as Map; expect(resp.containsKey('value'), true); }); }, onPlatform: <String, dynamic>{ 'windows': [ Skip('Failing on Windows CI'), ] }, ); }
samples/code_sharing/server/test/server_test.dart/0
{'file_path': 'samples/code_sharing/server/test/server_test.dart', 'repo_id': 'samples', 'token_count': 555}
include: package:analysis_defaults/flutter.yaml
samples/experimental/federated_plugin/federated_plugin/analysis_options.yaml/0
{'file_path': 'samples/experimental/federated_plugin/federated_plugin/analysis_options.yaml', 'repo_id': 'samples', 'token_count': 15}
include: package:analysis_defaults/flutter.yaml
samples/experimental/federated_plugin/federated_plugin_platform_interface/analysis_options.yaml/0
{'file_path': 'samples/experimental/federated_plugin/federated_plugin_platform_interface/analysis_options.yaml', 'repo_id': 'samples', 'token_count': 15}
include: package:analysis_defaults/flutter.yaml
samples/experimental/federated_plugin/federated_plugin_windows/analysis_options.yaml/0
{'file_path': 'samples/experimental/federated_plugin/federated_plugin_windows/analysis_options.yaml', 'repo_id': 'samples', 'token_count': 15}
// Copyright 2021 The Flutter team. 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:equatable/equatable.dart'; import 'package:hive/hive.dart'; import 'package:linting_tool/model/rule.dart'; part 'profile.g.dart'; @HiveType(typeId: 1) class RulesProfile extends Equatable { @HiveField(0) final String name; @HiveField(1) final List<Rule> rules; const RulesProfile({ required this.name, required this.rules, }); @override List<Object?> get props => [name]; }
samples/experimental/linting_tool/lib/model/profile.dart/0
{'file_path': 'samples/experimental/linting_tool/lib/model/profile.dart', 'repo_id': 'samples', 'token_count': 199}
android_sdk_config: add_gradle_deps: true add_gradle_sources: true android_example: 'example/' output: c: library_name: health_connect path: src/health_connect/ dart: path: lib/health_connect.dart structure: single_file classes: - 'androidx.health.connect.client.HealthConnectClient' - 'androidx.health.connect.client.PermissionController' - 'androidx.health.connect.client.records.StepsRecord' - 'androidx.health.connect.client.time' - 'android.content.Context' - 'android.content.Intent' - 'android.app.Activity' - 'java.time.Instant' - 'androidx.health.connect.client.request' - 'androidx.health.connect.client.aggregate.AggregationResult' - 'androidx.health.connect.client.aggregate.AggregateMetric'
samples/experimental/pedometer/jnigen.yaml/0
{'file_path': 'samples/experimental/pedometer/jnigen.yaml', 'repo_id': 'samples', 'token_count': 268}
// Copyright 2023 The Flutter team. 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:flutter/material.dart'; import '../page_content/pages_flow.dart'; void main() { runApp(const TypePuzzle()); } class TypePuzzle extends StatelessWidget { const TypePuzzle({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Type Jam', theme: ThemeData( primarySwatch: Colors.grey, useMaterial3: true, ), home: const Scaffold( appBar: null, body: PagesFlow(), ), ); } }
samples/experimental/varfont_shader_puzzle/lib/main.dart/0
{'file_path': 'samples/experimental/varfont_shader_puzzle/lib/main.dart', 'repo_id': 'samples', 'token_count': 267}
// Copyright 2020, the Flutter 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 '../api/api.dart'; import 'day_helpers.dart'; /// The total value of one or more [Entry]s on a given day. class EntryTotal { final DateTime day; int value; EntryTotal(this.day, this.value); } /// Returns a list of [EntryTotal] objects. Each [EntryTotal] is the sum of /// the values of all the entries on a given day. List<EntryTotal> entryTotalsByDay(List<Entry>? entries, int daysAgo, {DateTime? today}) { today ??= DateTime.now(); return _entryTotalsByDay(entries, daysAgo, today).toList(); } Iterable<EntryTotal> _entryTotalsByDay( List<Entry>? entries, int daysAgo, DateTime today) sync* { var start = today.subtract(Duration(days: daysAgo)); var entriesByDay = _entriesInRange(start, today, entries); for (var i = 0; i < entriesByDay.length; i++) { var list = entriesByDay[i]; var entryTotal = EntryTotal(start.add(Duration(days: i)), 0); for (var entry in list) { entryTotal.value += entry.value; } yield entryTotal; } } /// Groups entries by day between [start] and [end]. The result is a list of /// lists. The outer list represents the number of days since [start], and the /// inner list is the group of entries on that day. List<List<Entry>> _entriesInRange( DateTime start, DateTime end, List<Entry>? entries) => _entriesInRangeImpl(start, end, entries).toList(); Iterable<List<Entry>> _entriesInRangeImpl( DateTime start, DateTime end, List<Entry>? entries) sync* { start = start.atMidnight; end = end.atMidnight; var d = start; while (d.compareTo(end) <= 0) { var es = <Entry>[]; for (var entry in entries!) { if (d.isSameDay(entry.time.atMidnight)) { es.add(entry); } } yield es; d = d.add(const Duration(days: 1)); } }
samples/experimental/web_dashboard/lib/src/utils/chart_utils.dart/0
{'file_path': 'samples/experimental/web_dashboard/lib/src/utils/chart_utils.dart', 'repo_id': 'samples', 'token_count': 701}
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // TODO: Install a Google Maps API key that has Google Maps Web Services enabled // See https://developers.google.com/places/web-service/get-api-key const String googleMapsApiKey = 'ADD_A_KEY_HERE';
samples/flutter_maps_firestore/lib/api_key.dart/0
{'file_path': 'samples/flutter_maps_firestore/lib/api_key.dart', 'repo_id': 'samples', 'token_count': 102}
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:google_mobile_ads/google_mobile_ads.dart'; import 'package:logging/logging.dart'; class PreloadedBannerAd { static final _log = Logger('PreloadedBannerAd'); /// Something like [AdSize.mediumRectangle]. final AdSize size; final AdRequest _adRequest; BannerAd? _bannerAd; final String adUnitId; final _adCompleter = Completer<BannerAd>(); PreloadedBannerAd({ required this.size, required this.adUnitId, AdRequest? adRequest, }) : _adRequest = adRequest ?? const AdRequest(); Future<BannerAd> get ready => _adCompleter.future; Future<void> load() { assert(Platform.isAndroid || Platform.isIOS, 'AdMob currently does not support ${Platform.operatingSystem}'); _bannerAd = BannerAd( // This is a test ad unit ID from // https://developers.google.com/admob/android/test-ads. When ready, // you replace this with your own, production ad unit ID, // created in https://apps.admob.com/. adUnitId: adUnitId, size: size, request: _adRequest, listener: BannerAdListener( onAdLoaded: (ad) { _log.info(() => 'Ad loaded: ${_bannerAd.hashCode}'); _adCompleter.complete(_bannerAd); }, onAdFailedToLoad: (ad, error) { _log.warning('Banner failedToLoad: $error'); _adCompleter.completeError(error); ad.dispose(); }, onAdImpression: (ad) { _log.info('Ad impression registered'); }, onAdClicked: (ad) { _log.info('Ad click registered'); }, ), ); return _bannerAd!.load(); } void dispose() { _log.info('preloaded banner ad being disposed'); _bannerAd?.dispose(); } }
samples/game_template/lib/src/ads/preloaded_banner_ad.dart/0
{'file_path': 'samples/game_template/lib/src/ads/preloaded_banner_ad.dart', 'repo_id': 'samples', 'token_count': 782}
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'api/item.dart'; /// This is the widget responsible for building the item in the list, /// once we have the actual data [item]. class ItemTile extends StatelessWidget { final Item item; const ItemTile({required this.item, super.key}); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(8.0), child: ListTile( leading: AspectRatio( aspectRatio: 1, child: Container( color: item.color, ), ), title: Text(item.name, style: Theme.of(context).textTheme.titleLarge), trailing: Text('\$ ${(item.price / 100).toStringAsFixed(2)}'), ), ); } } /// This is the widget responsible for building the "still loading" item /// in the list (represented with "..." and a crossed square). class LoadingItemTile extends StatelessWidget { const LoadingItemTile({super.key}); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(8.0), child: ListTile( leading: const AspectRatio( aspectRatio: 1, child: Placeholder(), ), title: Text('...', style: Theme.of(context).textTheme.titleLarge), trailing: const Text('\$ ...'), ), ); } }
samples/infinite_list/lib/src/item_tile.dart/0
{'file_path': 'samples/infinite_list/lib/src/item_tile.dart', 'repo_id': 'samples', 'token_count': 561}
// Copyright 2020 The Flutter team. 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:device_info/device_info.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; void main() { runApp(const Demo()); } // The same content is shown for both the main app target and in the App // Clip. class Demo extends StatefulWidget { const Demo({super.key}); @override State<Demo> createState() => _DemoState(); } class _DemoState extends State<Demo> { String deviceInfo = ''; @override void initState() { DeviceInfoPlugin().iosInfo.then((info) { setState(() { deviceInfo = '${info.name} on ${info.systemName} version ' '${info.systemVersion}'; }); }); super.initState(); } @override Widget build(BuildContext context) { return CupertinoApp( home: CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar( middle: Text('App Clip'), ), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(deviceInfo), const Padding(padding: EdgeInsets.only(top: 18)), const FlutterLogo(size: 128), ], ), ), ), ); } }
samples/ios_app_clip/lib/main.dart/0
{'file_path': 'samples/ios_app_clip/lib/main.dart', 'repo_id': 'samples', 'token_count': 572}
include: package:analysis_defaults/flutter.yaml
samples/navigation_and_routing/analysis_options.yaml/0
{'file_path': 'samples/navigation_and_routing/analysis_options.yaml', 'repo_id': 'samples', 'token_count': 15}
// Copyright 2020 The Flutter team. 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:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:platform_channels/src/counter_method_channel.dart'; /// The widget demonstrates how to use [MethodChannel] to invoke platform methods. /// It has two [FilledButton]s to increment and decrement the value of /// [count], and a [Text] widget to display its value. class MethodChannelDemo extends StatefulWidget { const MethodChannelDemo({super.key}); @override State<MethodChannelDemo> createState() => _MethodChannelDemoState(); } class _MethodChannelDemoState extends State<MethodChannelDemo> { int count = 0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('MethodChannel Demo'), ), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Value of count is $count', style: Theme.of(context).textTheme.headlineSmall, ), const SizedBox( height: 16, ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ // Whenever users press the FilledButton, it invokes // Counter.increment method to increment the value of count. FilledButton.icon( onPressed: () async { try { final value = await Counter.increment(counterValue: count); setState(() => count = value); } catch (error) { if (!context.mounted) return; showErrorMessage( context, (error as PlatformException).message!, ); } }, icon: const Icon(Icons.add), label: const Text('Increment'), ), // Whenever users press the FilledButton, it invokes // Counter.decrement method to decrement the value of count. FilledButton.icon( onPressed: () async { try { final value = await Counter.decrement(counterValue: count); setState(() => count = value); } catch (error) { if (!context.mounted) return; showErrorMessage( context, (error as PlatformException).message!, ); } }, icon: const Icon(Icons.remove), label: const Text('Decrement'), ) ], ) ], ), ); } void showErrorMessage(BuildContext context, String errorMessage) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(errorMessage), ), ); } }
samples/platform_channels/lib/src/method_channel_demo.dart/0
{'file_path': 'samples/platform_channels/lib/src/method_channel_demo.dart', 'repo_id': 'samples', 'token_count': 1478}
// Copyright 2020 The Flutter team. 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:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'song_detail_tab.dart'; import 'utils.dart'; import 'widgets.dart'; class SongsTab extends StatefulWidget { static const title = 'Songs'; static const androidIcon = Icon(Icons.music_note); static const iosIcon = Icon(CupertinoIcons.music_note); const SongsTab({super.key, this.androidDrawer}); final Widget? androidDrawer; @override State<SongsTab> createState() => _SongsTabState(); } class _SongsTabState extends State<SongsTab> { static const _itemsLength = 50; final _androidRefreshKey = GlobalKey<RefreshIndicatorState>(); late List<MaterialColor> colors; late List<String> songNames; @override void initState() { _setData(); super.initState(); } void _setData() { colors = getRandomColors(_itemsLength); songNames = getRandomNames(_itemsLength); } Future<void> _refreshData() { return Future.delayed( // This is just an arbitrary delay that simulates some network activity. const Duration(seconds: 2), () => setState(() => _setData()), ); } Widget _listBuilder(BuildContext context, int index) { if (index >= _itemsLength) return Container(); // Show a slightly different color palette. Show poppy-ier colors on iOS // due to lighter contrasting bars and tone it down on Android. final color = defaultTargetPlatform == TargetPlatform.iOS ? colors[index] : colors[index].shade400; return SafeArea( top: false, bottom: false, child: Hero( tag: index, child: HeroAnimatingSongCard( song: songNames[index], color: color, heroAnimation: const AlwaysStoppedAnimation(0), onPressed: () => Navigator.of(context).push<void>( MaterialPageRoute( builder: (context) => SongDetailTab( id: index, song: songNames[index], color: color, ), ), ), ), ), ); } void _togglePlatform() { if (defaultTargetPlatform == TargetPlatform.iOS) { debugDefaultTargetPlatformOverride = TargetPlatform.android; } else { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; } // This rebuilds the application. This should obviously never be // done in a real app but it's done here since this app // unrealistically toggles the current platform for demonstration // purposes. WidgetsBinding.instance.reassembleApplication(); } // =========================================================================== // Non-shared code below because: // - Android and iOS have different scaffolds // - There are different items in the app bar / nav bar // - Android has a hamburger drawer, iOS has bottom tabs // - The iOS nav bar is scrollable, Android is not // - Pull-to-refresh works differently, and Android has a button to trigger it too // // And these are all design time choices that doesn't have a single 'right' // answer. // =========================================================================== Widget _buildAndroid(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text(SongsTab.title), actions: [ IconButton( icon: const Icon(Icons.refresh), onPressed: () async => await _androidRefreshKey.currentState!.show(), ), IconButton( icon: const Icon(Icons.shuffle), onPressed: _togglePlatform, ), ], ), drawer: widget.androidDrawer, body: RefreshIndicator( key: _androidRefreshKey, onRefresh: _refreshData, child: ListView.builder( padding: const EdgeInsets.symmetric(vertical: 12), itemCount: _itemsLength, itemBuilder: _listBuilder, ), ), ); } Widget _buildIos(BuildContext context) { return CustomScrollView( slivers: [ CupertinoSliverNavigationBar( trailing: CupertinoButton( padding: EdgeInsets.zero, onPressed: _togglePlatform, child: const Icon(CupertinoIcons.shuffle), ), ), CupertinoSliverRefreshControl( onRefresh: _refreshData, ), SliverSafeArea( top: false, sliver: SliverPadding( padding: const EdgeInsets.symmetric(vertical: 12), sliver: SliverList( delegate: SliverChildBuilderDelegate( _listBuilder, childCount: _itemsLength, ), ), ), ), ], ); } @override Widget build(context) { return PlatformWidget( androidBuilder: _buildAndroid, iosBuilder: _buildIos, ); } }
samples/platform_design/lib/songs_tab.dart/0
{'file_path': 'samples/platform_design/lib/songs_tab.dart', 'repo_id': 'samples', 'token_count': 2010}
# Run with tooling from https://github.com/flutter/codelabs/tree/main/tooling/codelab_rebuild name: Provider Shopper rebuild script steps: - name: Remove runners rmdirs: - android - ios - linux - macos - web - windows - name: Flutter recreate flutter: create --org dev.flutter . - name: Update dependencies flutter: pub upgrade --major-versions - name: Build iOS simulator bundle platforms: [ macos ] flutter: build ios --simulator
samples/provider_shopper/codelab_rebuild.yaml/0
{'file_path': 'samples/provider_shopper/codelab_rebuild.yaml', 'repo_id': 'samples', 'token_count': 185}
// Copyright 2019 The Flutter team. 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:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:provider/provider.dart'; import 'package:provider_shopper/models/cart.dart'; import 'package:provider_shopper/models/catalog.dart'; class MyCatalog extends StatelessWidget { const MyCatalog({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: CustomScrollView( slivers: [ _MyAppBar(), const SliverToBoxAdapter(child: SizedBox(height: 12)), SliverList( delegate: SliverChildBuilderDelegate( (context, index) => _MyListItem(index)), ), ], ), ); } } class _AddButton extends StatelessWidget { final Item item; const _AddButton({required this.item}); @override Widget build(BuildContext context) { // The context.select() method will let you listen to changes to // a *part* of a model. You define a function that "selects" (i.e. returns) // the part you're interested in, and the provider package will not rebuild // this widget unless that particular part of the model changes. // // This can lead to significant performance improvements. var isInCart = context.select<CartModel, bool>( // Here, we are only interested whether [item] is inside the cart. (cart) => cart.items.contains(item), ); return TextButton( onPressed: isInCart ? null : () { // If the item is not in cart, we let the user add it. // We are using context.read() here because the callback // is executed whenever the user taps the button. In other // words, it is executed outside the build method. var cart = context.read<CartModel>(); cart.add(item); }, style: ButtonStyle( overlayColor: MaterialStateProperty.resolveWith<Color?>((states) { if (states.contains(MaterialState.pressed)) { return Theme.of(context).primaryColor; } return null; // Defer to the widget's default. }), ), child: isInCart ? const Icon(Icons.check, semanticLabel: 'ADDED') : const Text('ADD'), ); } } class _MyAppBar extends StatelessWidget { @override Widget build(BuildContext context) { return SliverAppBar( title: Text('Catalog', style: Theme.of(context).textTheme.displayLarge), floating: true, actions: [ IconButton( icon: const Icon(Icons.shopping_cart), onPressed: () => context.go('/catalog/cart'), ), ], ); } } class _MyListItem extends StatelessWidget { final int index; const _MyListItem(this.index); @override Widget build(BuildContext context) { var item = context.select<CatalogModel, Item>( // Here, we are only interested in the item at [index]. We don't care // about any other change. (catalog) => catalog.getByPosition(index), ); var textTheme = Theme.of(context).textTheme.titleLarge; return Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), child: LimitedBox( maxHeight: 48, child: Row( children: [ AspectRatio( aspectRatio: 1, child: Container( color: item.color, ), ), const SizedBox(width: 24), Expanded( child: Text(item.name, style: textTheme), ), const SizedBox(width: 24), _AddButton(item: item), ], ), ), ); } }
samples/provider_shopper/lib/screens/catalog.dart/0
{'file_path': 'samples/provider_shopper/lib/screens/catalog.dart', 'repo_id': 'samples', 'token_count': 1606}
// Copyright 2018 The Flutter team. 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:flutter/cupertino.dart'; import 'package:go_router/go_router.dart'; import 'package:provider/provider.dart'; import 'package:veggieseasons/data/app_state.dart'; import 'package:veggieseasons/data/preferences.dart'; import 'package:veggieseasons/data/veggie.dart'; import 'package:veggieseasons/styles.dart'; import 'package:veggieseasons/widgets/close_button.dart'; import 'package:veggieseasons/widgets/trivia.dart'; class ServingInfoChart extends StatelessWidget { const ServingInfoChart(this.veggie, this.prefs, {super.key}); final Veggie veggie; final Preferences prefs; // Creates a [Text] widget to display a veggie's "percentage of your daily // value of this vitamin" data adjusted for the user's preferred calorie // target. Widget _buildVitaminText(int standardPercentage, Future<int> targetCalories) { return FutureBuilder<int>( future: targetCalories, builder: (context, snapshot) { final target = snapshot.data ?? 2000; final percent = standardPercentage * 2000 ~/ target; return Text( '$percent% DV', style: CupertinoTheme.of(context).textTheme.textStyle, textAlign: TextAlign.end, ); }, ); } @override Widget build(BuildContext context) { final themeData = CupertinoTheme.of(context); return Column( children: [ const SizedBox(height: 16), Align( alignment: Alignment.centerLeft, child: Padding( padding: const EdgeInsets.only( left: 9, bottom: 4, ), child: Text( 'Serving info', style: CupertinoTheme.of(context).textTheme.textStyle, ), ), ), Container( decoration: BoxDecoration( border: Border.all(color: Styles.servingInfoBorderColor), ), padding: const EdgeInsets.all(8), child: Column( children: [ Table( children: [ TableRow( children: [ TableCell( child: Text( 'Serving size:', style: Styles.detailsServingLabelText(themeData), ), ), TableCell( child: Text( veggie.servingSize, textAlign: TextAlign.end, style: CupertinoTheme.of(context).textTheme.textStyle, ), ), ], ), TableRow( children: [ TableCell( child: Text( 'Calories:', style: Styles.detailsServingLabelText(themeData), ), ), TableCell( child: Text( '${veggie.caloriesPerServing} kCal', style: CupertinoTheme.of(context).textTheme.textStyle, textAlign: TextAlign.end, ), ), ], ), TableRow( children: [ TableCell( child: Text( 'Vitamin A:', style: Styles.detailsServingLabelText(themeData), ), ), TableCell( child: _buildVitaminText( veggie.vitaminAPercentage, prefs.desiredCalories, ), ), ], ), TableRow( children: [ TableCell( child: Text( 'Vitamin C:', style: Styles.detailsServingLabelText(themeData), ), ), TableCell( child: _buildVitaminText( veggie.vitaminCPercentage, prefs.desiredCalories, ), ), ], ), ], ), Padding( padding: const EdgeInsets.only(top: 16), child: FutureBuilder( future: prefs.desiredCalories, builder: (context, snapshot) { return Text( 'Percent daily values based on a diet of ' '${snapshot.data ?? '2,000'} calories.', style: Styles.detailsServingNoteText(themeData), ); }, ), ), ], ), ) ], ); } } class InfoView extends StatelessWidget { final int? id; const InfoView(this.id, {super.key}); @override Widget build(BuildContext context) { final appState = Provider.of<AppState>(context); final prefs = Provider.of<Preferences>(context); final veggie = appState.getVeggie(id); final themeData = CupertinoTheme.of(context); return Padding( padding: const EdgeInsets.all(24), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Row( mainAxisSize: MainAxisSize.max, children: [ FutureBuilder<Set<VeggieCategory>>( future: prefs.preferredCategories, builder: (context, snapshot) { return Text( veggie.categoryName!.toUpperCase(), style: (snapshot.hasData && snapshot.data!.contains(veggie.category)) ? Styles.detailsPreferredCategoryText(themeData) : themeData.textTheme.textStyle, ); }, ), const Spacer(), for (Season season in veggie.seasons) ...[ const SizedBox(width: 12), Padding( padding: Styles.seasonIconPadding[season]!, child: Icon( Styles.seasonIconData[season], semanticLabel: seasonNames[season], color: Styles.seasonColors[season], ), ), ], ], ), const SizedBox(height: 8), Text( veggie.name, style: Styles.detailsTitleText(themeData), ), const SizedBox(height: 8), Text( veggie.shortDescription, style: CupertinoTheme.of(context).textTheme.textStyle, ), ServingInfoChart(veggie, prefs), const SizedBox(height: 24), Row( mainAxisSize: MainAxisSize.min, children: [ CupertinoSwitch( value: veggie.isFavorite, onChanged: (value) { appState.setFavorite(id, value); }, ), const SizedBox(width: 8), Text( 'Save to Garden', style: CupertinoTheme.of(context).textTheme.textStyle, ), ], ), ], ), ); } } class DetailsScreen extends StatefulWidget { final int? id; final String? restorationId; const DetailsScreen({this.id, this.restorationId, super.key}); @override State<DetailsScreen> createState() => _DetailsScreenState(); } class _DetailsScreenState extends State<DetailsScreen> with RestorationMixin { final RestorableInt _selectedViewIndex = RestorableInt(0); @override String? get restorationId => widget.restorationId; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_selectedViewIndex, 'tab'); } @override void dispose() { _selectedViewIndex.dispose(); super.dispose(); } Widget _buildHeader(BuildContext context, AppState model) { final veggie = model.getVeggie(widget.id); return SizedBox( height: 150, child: Stack( children: [ Positioned( right: 0, left: 0, child: Image.asset( veggie.imageAssetPath, fit: BoxFit.cover, semanticLabel: 'A background image of ${veggie.name}', ), ), Positioned( top: 16, left: 16, child: SafeArea( child: CloseButton(() { context.pop(); }), ), ), ], ), ); } @override Widget build(BuildContext context) { final appState = Provider.of<AppState>(context); return UnmanagedRestorationScope( bucket: bucket, child: CupertinoPageScaffold( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ Expanded( child: ListView( restorationId: 'list', children: [ _buildHeader(context, appState), const SizedBox(height: 20), CupertinoSegmentedControl<int>( children: const { 0: Text( 'Facts & Info', ), 1: Text( 'Trivia', ) }, groupValue: _selectedViewIndex.value, onValueChanged: (value) { setState(() => _selectedViewIndex.value = value); }, ), _selectedViewIndex.value == 0 ? InfoView(widget.id) : TriviaView(id: widget.id, restorationId: 'trivia'), ], ), ), ], ), ), ); } }
samples/veggieseasons/lib/screens/details.dart/0
{'file_path': 'samples/veggieseasons/lib/screens/details.dart', 'repo_id': 'samples', 'token_count': 5931}
/// An extension to the [bloc state management library](https://pub.dev/packages/bloc) /// which integrations [sealed_unions](https://pub.dev/packages/sealed_unions). /// /// Get started at [bloclibrary.dev](https://bloclibrary.dev) 🚀 library sealed_flutter_bloc; export 'package:sealed_unions/sealed_unions.dart'; export 'src/sealed_bloc_builder/sealed_bloc_builder.dart';
sealed_flutter_bloc/lib/sealed_flutter_bloc.dart/0
{'file_path': 'sealed_flutter_bloc/lib/sealed_flutter_bloc.dart', 'repo_id': 'sealed_flutter_bloc', 'token_count': 130}
import 'package:bloc/bloc.dart'; import 'package:sealed_unions/sealed_unions.dart'; enum HelperEvent4 { event2, event3, event4 } class HelperState4 extends Union4Impl<State1, State2, State3, State4> { HelperState4._(Union4<State1, State2, State3, State4> union) : super(union); factory HelperState4.first() => HelperState4._(unions.first(State1())); factory HelperState4.second() => HelperState4._(unions.second(State2())); factory HelperState4.third() => HelperState4._(unions.third(State3())); factory HelperState4.fourth() => HelperState4._(unions.fourth(State4())); static final Quartet<State1, State2, State3, State4> unions = const Quartet<State1, State2, State3, State4>(); } class State1 {} class State2 {} class State3 {} class State4 {} class HelperBloc4 extends Bloc<HelperEvent4, HelperState4> { HelperBloc4() : super(HelperState4.first()) { on<HelperEvent4>((event, emit) { switch (event) { case HelperEvent4.event2: return emit(HelperState4.second()); case HelperEvent4.event3: return emit(HelperState4.third()); case HelperEvent4.event4: return emit(HelperState4.fourth()); } }); } }
sealed_flutter_bloc/test/helpers/helper_bloc4.dart/0
{'file_path': 'sealed_flutter_bloc/test/helpers/helper_bloc4.dart', 'repo_id': 'sealed_flutter_bloc', 'token_count': 472}
export './post_bloc.dart'; export './post_event.dart'; export './post_state.dart'; export './simple_bloc_delegate.dart';
sealed_flutter_bloc_samples/sealed_flutter_infinite_list/lib/bloc/bloc.dart/0
{'file_path': 'sealed_flutter_bloc_samples/sealed_flutter_infinite_list/lib/bloc/bloc.dart', 'repo_id': 'sealed_flutter_bloc_samples', 'token_count': 49}
import 'dart:async'; import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class AppBlocObserver extends BlocObserver { @override void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) { super.onChange(bloc, change); log('onChange(${bloc.runtimeType}, $change)'); } @override void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) { log('onError(${bloc.runtimeType}, $error, $stackTrace)'); super.onError(bloc, error, stackTrace); } } Future<void> bootstrap(FutureOr<Widget> Function() builder) async { FlutterError.onError = (details) { log(details.exceptionAsString(), stackTrace: details.stack); }; Bloc.observer = AppBlocObserver(); await runZonedGuarded( () async => runApp(await builder()), (error, stackTrace) => log( '$error $stackTrace', stackTrace: stackTrace, ), ); }
shopping-ui-BLoC/lib/bootstrap.dart/0
{'file_path': 'shopping-ui-BLoC/lib/bootstrap.dart', 'repo_id': 'shopping-ui-BLoC', 'token_count': 357}
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:nested/nested.dart'; import 'package:shopping_ui/data/models/shoe.dart'; import 'package:shopping_ui/presentation/blocs/cart_bloc/cart_bloc.dart'; import 'package:shopping_ui/presentation/providers/cart_provider.dart'; import 'package:shopping_ui/presentation/widgets/cart_item_widget.dart'; class CartListWidget extends StatefulWidget { const CartListWidget({super.key}); @override State<CartListWidget> createState() => _CartListWidgetState(); } /// This is the state of the _CartListWidget widget. /// It holds a list of [Shoe] items and a [GlobalKey] for the /// [AnimatedList] widget. class _CartListWidgetState extends State<CartListWidget> { final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>(); final List<Shoe> _items = []; @override Widget build(BuildContext context) { return Nested( // Nest this widget in the [CartPage] widget children: [ BlocListener<CartBloc, CartState>( // Listen to changes in the [CartBloc] state listener: (context, state) { if (state is CartItemAdded) { // If a new item has been added to the cart _addItem(state.shoe); // Add the new item to the [_items] list context.read<CartProvider>().updateCartItems( _items, ); // Update the cart items in the [CartProvider] context .read<CartBloc>() .add(ResetCartBlocEvent()); // Reset the [CartBloc] state } else if (state is CartItemRemoved) { // If an item has been removed from the cart context.read<CartProvider>().updateCartItems( _items, ); // Update the cart items in the [CartProvider] context .read<CartBloc>() .add(ResetCartBlocEvent()); // Reset the [CartBloc] state } else if (state is CartInitial) {} }, ) ], child: ScrollConfiguration( // Configure scrolling behavior of the [AnimatedList] behavior: ScrollConfiguration.of(context).copyWith( scrollbars: false, // Hide the scrollbar ), child: AnimatedList( // The list of [CartItemWidget]s in the cart key: _listKey, initialItemCount: _items.length, itemBuilder: (context, index, animation) { return CartItemWidget( // Return a [CartItemWidget] for each item in [_items] _items[index], animation, onRemoveItem: () => _removeItem( _items[index], ), // When the remove button is pressed, remove the item from // the cart ); }, ), ), ); } /// This method adds a [Shoe] item to the [_items] list and inserts a new [ /// CartItemWidget] into the [AnimatedList]. void _addItem(Shoe shoe) { final index = _items.length; _items.add(shoe); _listKey.currentState!.insertItem(index); } /// This method removes a [Shoe] item from the [_items] list and removes the /// corresponding [CartItemWidget] from the [AnimatedList]. void _removeItem(Shoe shoe) { final index = _items.indexOf(shoe); _items.removeAt(index); context.read<CartBloc>().add( RemoveItemFromCartEvent( shoe: shoe, ), ); // Remove the item from the cart in the [CartBloc] _listKey.currentState!.removeItem( // Remove the [CartItemWidget] from the [AnimatedList] index, (context, animation) { return CartItemWidget(shoe, animation); }, ); } }
shopping-ui-BLoC/lib/presentation/widgets/cart_list_widget.dart/0
{'file_path': 'shopping-ui-BLoC/lib/presentation/widgets/cart_list_widget.dart', 'repo_id': 'shopping-ui-BLoC', 'token_count': 1622}
export 'models/models.dart'; export 'weather_service.dart';
simple_weather/lib/service/service.dart/0
{'file_path': 'simple_weather/lib/service/service.dart', 'repo_id': 'simple_weather', 'token_count': 20}
import 'package:flutter/material.dart'; import '../../widgets/label.dart'; import './game_modal.dart'; class PauseGame extends StatelessWidget { final VoidCallback resumeGame; PauseGame({this.resumeGame}); @override Widget build(ctx) { return GameModal( title: Label(label: 'Pause', fontSize: 45, fontColor: Color(0xFF94b0c2)), primaryButtonLabel: 'Resume', primaryButtonPress: resumeGame, secondaryButtonLabel: 'Home', secondaryButtonPress: () { Navigator.of(ctx).pushReplacementNamed("/title"); }, ); } }
snake-chef/snake_chef/lib/game/widgets/pause_game.dart/0
{'file_path': 'snake-chef/snake_chef/lib/game/widgets/pause_game.dart', 'repo_id': 'snake-chef', 'token_count': 219}
import 'package:flame/flame.dart'; import 'package:flame/spritesheet.dart'; import 'package:flame/sprite.dart'; import 'package:flame_fire_atlas/flame_fire_atlas.dart'; class WidgetsAssets { static SpriteSheet _buttons; static FireAtlas _sliderAtlas; static Future<void> load() async { await Flame.images.loadAll(["buttons.png"]); _buttons = SpriteSheet( imageName: "buttons.png", textureHeight: 20, textureWidth: 60, columns: 2, rows: 8); _sliderAtlas = await FireAtlas.fromAsset('atlases/slider.fa'); } } class SlideSprites { static Sprite leftTile() => WidgetsAssets._sliderAtlas.getSprite('left'); static Sprite rightTile() => WidgetsAssets._sliderAtlas.getSprite('right'); static Sprite middleTile() => WidgetsAssets._sliderAtlas.getSprite('middle'); static Sprite bullet() => WidgetsAssets._sliderAtlas.getSprite('bullet'); } class ButtonSprites { static Sprite primaryButton() => WidgetsAssets._buttons.getSprite(0, 0); static Sprite primaryButtonPressed() => WidgetsAssets._buttons.getSprite(1, 0); static Sprite secondaryButton() => WidgetsAssets._buttons.getSprite(0, 1); static Sprite secondaryButtonPressed() => WidgetsAssets._buttons.getSprite(1, 1); static Sprite dpadButton() => WidgetsAssets._buttons.getSprite(2, 0); static Sprite dpadButtonPressed() => WidgetsAssets._buttons.getSprite(3, 0); static Sprite onButton() => WidgetsAssets._buttons.getSprite(2, 1); static Sprite onButtonPressed() => WidgetsAssets._buttons.getSprite(3, 1); static Sprite offButton() => WidgetsAssets._buttons.getSprite(4, 0); static Sprite offButtonPressed() => WidgetsAssets._buttons.getSprite(5, 0); static Sprite bronzeButton() => WidgetsAssets._buttons.getSprite(4, 1); static Sprite bronzeButtonPressed() => WidgetsAssets._buttons.getSprite(5, 1); static Sprite plainButton() => WidgetsAssets._buttons.getSprite(6, 0); static Sprite plainButtonPressed() => WidgetsAssets._buttons.getSprite(7, 0); }
snake-chef/snake_chef/lib/widgets/assets.dart/0
{'file_path': 'snake-chef/snake_chef/lib/widgets/assets.dart', 'repo_id': 'snake-chef', 'token_count': 709}
/** * server.dart * * Purpose: * * Description: * * History: * 26/07/2017, Created by jumperchen * * Copyright (C) 2017 Potix Corporation. All Rights Reserved. */ import 'package:socket_io/socket_io.dart'; main() { // Dart server var io = new Server(); io.on('connection', (Socket client) { print('connection default namespace'); client.on('msg', (data) { print('data from default => $data'); client.emit('fromServer', "$data"); }); }); io.listen(3000); }
socket.io-client-dart/test/server.dart/0
{'file_path': 'socket.io-client-dart/test/server.dart', 'repo_id': 'socket.io-client-dart', 'token_count': 180}
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:solar_system/scenes/home_scene.dart'; class App extends StatelessWidget { const App({ super.key, }); @override Widget build(BuildContext context) { return MaterialApp( title: 'Solar System', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, textTheme: GoogleFonts.latoTextTheme(), ), home: const HomeScene(), ); } }
solar-system/lib/app.dart/0
{'file_path': 'solar-system/lib/app.dart', 'repo_id': 'solar-system', 'token_count': 203}
import 'package:authentication_ui/widgets/k_button.dart'; import 'package:authentication_ui/widgets/social_button.dart'; import 'package:flutter/material.dart'; import '../widgets/k_form_field.dart'; import 'sign_in_screen.dart'; class SignUpScreen extends StatefulWidget { const SignUpScreen({ super.key, }); @override State<SignUpScreen> createState() => _SignUpScreenState(); } class _SignUpScreenState extends State<SignUpScreen> { @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 35, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox( height: 63, ), const Text( 'Create Account', style: TextStyle( fontWeight: FontWeight.w500, fontSize: 24, color: Colors.black, ), ), const SizedBox( height: 5, ), const Text( 'Connect with your Friends Today!', style: TextStyle( fontWeight: FontWeight.w400, fontSize: 13, color: Color(0xFF959AA1), ), ), const SizedBox( height: 45, ), const KFormField( hintText: 'Enter your email', label: 'Email Address', ), const SizedBox( height: 10, ), const KFormField( hintText: 'Enter your mobile number', label: 'Mobile Number', ), const SizedBox( height: 10, ), const KFormField( hintText: 'Enter your password', label: 'Password', ), const SizedBox( height: 23, ), Row( children: [ SizedBox( height: 24, width: 24, child: IconButton( onPressed: () {}, padding: EdgeInsets.zero, icon: const Icon( Icons.check_box, color: Color(0xFF00726D), ), ), ), const SizedBox( width: 10, ), const Text( 'I agree to the terms and conditions', style: TextStyle( color: Colors.black, fontWeight: FontWeight.w500, fontSize: 13, ), ), ], ), const SizedBox( height: 19, ), const KButton( buttonText: 'Sign Up', ), const SizedBox( height: 60, ), Row( children: const [ Expanded( child: Divider(), ), SizedBox( width: 25, ), Text( 'Or Login with', style: TextStyle( color: Colors.black, fontWeight: FontWeight.w500, ), ), SizedBox( width: 25, ), Expanded( child: Divider(), ), ], ), const SizedBox( height: 20, ), Row( children: const [ Expanded( child: SocialButton( iconPath: 'assets/svgs/facebook.svg', title: 'Facebook', ), ), SizedBox( width: 22, ), Expanded( child: SocialButton( iconPath: 'assets/svgs/google.svg', title: 'Google', ), ), ], ), const SizedBox( height: 40, ), Center( child: InkWell( onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (_) => const SignInScreen(), ), ); }, child: RichText( text: const TextSpan( text: 'Already have an account? ', style: TextStyle( color: Color(0xFFA2A6AC), fontSize: 15, fontWeight: FontWeight.w400, ), children: [ TextSpan( text: 'Log In', style: TextStyle( color: Color(0xFF00726D), fontSize: 15, fontWeight: FontWeight.w600, ), ) ], ), ), ), ), ], ), ), ), ); } }
speedcode_authentication-ui/lib/screens/sign_up_screen.dart/0
{'file_path': 'speedcode_authentication-ui/lib/screens/sign_up_screen.dart', 'repo_id': 'speedcode_authentication-ui', 'token_count': 3914}
// Copyright (c) 2014, Google Inc. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import '../common.dart'; part 'console_full.g.dart'; /// A generator for a hello world command-line application. class ConsoleFullGenerator extends DefaultGenerator { ConsoleFullGenerator() : super('console-full', 'Console Application', 'A command-line application sample.', categories: const ['dart', 'console']) { for (var file in decodeConcatenatedData(_data)) { addTemplateFile(file); } setEntrypoint(getFile('bin/__projectName__.dart')); } @override String getInstallInstructions() => '${super.getInstallInstructions()}\n' 'run your app using `dart ${entrypoint.path}`.'; }
stagehand/lib/src/generators/console_full.dart/0
{'file_path': 'stagehand/lib/src/generators/console_full.dart', 'repo_id': 'stagehand', 'token_count': 281}
# Copyright (c) 2014, Google Inc. Please see the AUTHORS file for details. # All rights reserved. Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. name: stagehand description: > A scaffolding generator for your Dart projects. Stagehand helps you get set up! # After changing the version, run `pub run build_runner build`. version: 3.3.9 homepage: https://github.com/dart-lang/stagehand environment: # Make sure this Dart SDK version is no higher than the stable Flutter Dart # SDK version to prevent errors when using Stagehand from inside VSCode's # Dart and Flutter plugins. For more detail, please see: # https://github.com/dart-lang/stagehand/issues/617 # # Also make sure this minimmum sdk version is reflected in `.travis.yml`. sdk: '>=2.8.1 <3.0.0' # Add the bin/stagehand.dart script to the scripts pub installs. executables: stagehand: dependencies: args: ^1.5.0 http: ^0.12.0 path: ^1.7.0 pedantic: ^1.9.0 usage: ^3.4.0 dev_dependencies: build: ^1.1.0 build_config: ^0.4.0 build_runner: ^1.6.0 build_version: ^2.0.0 glob: ^1.1.5 grinder: ^0.8.0 source_gen: ^0.9.0 test: ^1.6.0 yaml: ^2.1.2
stagehand/pubspec.yaml/0
{'file_path': 'stagehand/pubspec.yaml', 'repo_id': 'stagehand', 'token_count': 439}
name: __projectName__ description: A simple command-line application. # version: 1.0.0 # homepage: https://www.example.com environment: sdk: '>=2.8.1 <3.0.0' #dependencies: # path: ^1.7.0 dev_dependencies: pedantic: ^1.9.0
stagehand/templates/console-simple/pubspec.yaml/0
{'file_path': 'stagehand/templates/console-simple/pubspec.yaml', 'repo_id': 'stagehand', 'token_count': 96}
name: example description: A new Flutter project. version: 1.0.1 publish_to: none environment: sdk: ">=2.16.0 <4.0.0" dependencies: flutter: sdk: flutter flutter_state_notifier: ^1.0.0 provider: ^6.0.0 state_notifier: ^1.0.0 dev_dependencies: flutter_test: sdk: flutter mockito: ^5.0.0 dependency_overrides: flutter_state_notifier: path: ../../flutter_state_notifier state_notifier: path: ../ flutter: uses-material-design: true
state_notifier/packages/state_notifier/example/pubspec.yaml/0
{'file_path': 'state_notifier/packages/state_notifier/example/pubspec.yaml', 'repo_id': 'state_notifier', 'token_count': 207}
import 'dart:async'; import 'dart:convert'; import 'dart:math'; import 'package:logging/logging.dart'; import 'package:meta/meta.dart'; import 'package:rxdart/rxdart.dart'; import 'package:stream_chat/src/api/connection_status.dart'; import 'package:stream_chat/src/api/web_socket_channel_stub.dart' if (dart.library.html) 'web_socket_channel_html.dart' if (dart.library.io) 'web_socket_channel_io.dart'; import 'package:stream_chat/src/models/event.dart'; import 'package:stream_chat/src/models/user.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; /// Typedef which exposes an [Event] as the only parameter. typedef EventHandler = void Function(Event); /// Typedef used for connecting to a websocket. Method returns a /// [WebSocketChannel] and accepts a connection [url] and an optional /// [Iterable] of `protocols`. typedef ConnectWebSocket = WebSocketChannel Function(String url, {Iterable<String> protocols}); // TODO: parse error even // TODO: if parsing an error into an event fails we should not hide the // TODO: original error /// A WebSocket connection that reconnects upon failure. class WebSocket { /// Creates a new websocket /// To connect the WS call [connect] WebSocket({ @required this.baseUrl, this.user, this.connectParams, this.connectPayload, this.handler, this.logger, this.connectFunc = connectWebSocket, this.reconnectionMonitorInterval = 1, this.healthCheckInterval = 20, this.reconnectionMonitorTimeout = 40, }) { final qs = Map<String, String>.from(connectParams); final data = Map<String, dynamic>.from(connectPayload); data['user_details'] = user.toJson(); qs['json'] = json.encode(data); if (baseUrl.startsWith('https')) { _path = baseUrl.replaceFirst('https://', ''); _path = Uri.https(_path, 'connect', qs) .toString() .replaceFirst('https', 'wss'); } else if (baseUrl.startsWith('http')) { _path = baseUrl.replaceFirst('http://', ''); _path = Uri.http(_path, 'connect', qs).toString().replaceFirst('http', 'ws'); } else { _path = Uri.https(baseUrl, 'connect', qs) .toString() .replaceFirst('https', 'wss'); } } /// WS base url final String baseUrl; /// User performing the WS connection final User user; /// Querystring connection parameters final Map<String, String> connectParams; /// WS connection payload final Map<String, dynamic> connectPayload; /// Functions that will be called every time a new event is received from the /// connection final EventHandler handler; /// A WS specific logger instance final Logger logger; /// Connection function /// Used only for testing purpose @visibleForTesting final ConnectWebSocket connectFunc; /// Interval of the reconnection monitor timer /// This checks that it received a new event in the last /// [reconnectionMonitorTimeout] seconds, otherwise it considers the /// connection unhealthy and reconnects the WS final int reconnectionMonitorInterval; /// Interval of the health event sending timer /// This sends a health event every [healthCheckInterval] seconds in order to /// make the server aware that the client is still listening final int healthCheckInterval; /// The timeout that uses the reconnection monitor timer to consider the /// connection unhealthy final int reconnectionMonitorTimeout; final _connectionStatusController = BehaviorSubject.seeded(ConnectionStatus.disconnected); set _connectionStatus(ConnectionStatus status) => _connectionStatusController.add(status); /// The current connection status value ConnectionStatus get connectionStatus => _connectionStatusController.value; /// This notifies of connection status changes Stream<ConnectionStatus> get connectionStatusStream => _connectionStatusController.stream; String _path; int _retryAttempt = 1; WebSocketChannel _channel; Timer _healthCheck, _reconnectionMonitor; DateTime _lastEventAt; bool _manuallyDisconnected = false, _connecting = false, _reconnecting = false; Event _decodeEvent(String source) => Event.fromJson(json.decode(source)); Completer<Event> _connectionCompleter = Completer<Event>(); /// Connect the WS using the parameters passed in the constructor Future<Event> connect() { _manuallyDisconnected = false; if (_connecting) { logger.severe('already connecting'); return null; } _connecting = true; _connectionStatus = ConnectionStatus.connecting; logger.info('connecting to $_path'); _channel = connectFunc(_path); _channel.stream.listen( (data) { final jsonData = json.decode(data); if (jsonData['error'] != null) { return _onConnectionError(jsonData['error']); } _onData(data); }, onError: (error, stacktrace) { _onConnectionError(error, stacktrace); }, onDone: () { _onDone(); }, ); return _connectionCompleter.future; } void _onDone() { _connecting = false; if (_manuallyDisconnected) { return; } logger.info('connection closed | closeCode: ${_channel.closeCode} | ' 'closedReason: ${_channel.closeReason}'); if (!_reconnecting) { _reconnect(); } } void _onData(data) { final event = _decodeEvent(data); logger.info('received new event: $data'); if (_lastEventAt == null) { logger.info('connection estabilished'); _connecting = false; _reconnecting = false; _lastEventAt = DateTime.now(); _connectionStatus = ConnectionStatus.connected; _retryAttempt = 1; if (!_connectionCompleter.isCompleted) { _connectionCompleter.complete(event); } _startReconnectionMonitor(); _startHealthCheck(); } handler(event); _lastEventAt = DateTime.now(); } Future<void> _onConnectionError(error, [stacktrace]) async { logger..severe('error connecting')..severe(error); if (stacktrace != null) { logger.severe(stacktrace); } _connecting = false; if (!_reconnecting) { _connectionStatus = ConnectionStatus.disconnected; } if (!_connectionCompleter.isCompleted) { _cancelTimers(); _connectionCompleter.completeError(error, stacktrace); } else if (!_reconnecting) { return _reconnect(); } } void _reconnectionTimer(_) { final now = DateTime.now(); if (_lastEventAt != null && now.difference(_lastEventAt).inSeconds > reconnectionMonitorTimeout) { _channel.sink.close(); } } void _startReconnectionMonitor() { _reconnectionMonitor = Timer.periodic( Duration(seconds: reconnectionMonitorInterval), _reconnectionTimer, ); _reconnectionTimer(_reconnectionMonitor); } void _reconnectTimer() async { if (!_reconnecting) { return; } if (_connecting) { logger.info('already connecting'); return; } logger.info('reconnecting..'); _cancelTimers(); try { await connect(); } catch (e) { logger.log(Level.SEVERE, e.toString()); } await Future.delayed( Duration(seconds: min(_retryAttempt * 5, 25)), () { _reconnectTimer(); _retryAttempt++; }, ); } Future<void> _reconnect() async { logger.info('reconnect'); if (!_reconnecting) { _reconnecting = true; _connectionStatus = ConnectionStatus.connecting; } _reconnectTimer(); } void _cancelTimers() { _lastEventAt = null; if (_healthCheck != null) { _healthCheck.cancel(); } if (_reconnectionMonitor != null) { _reconnectionMonitor.cancel(); } } void _healthCheckTimer(_) { logger.info('sending health.check'); _channel.sink.add("{'type': 'health.check'}"); } void _startHealthCheck() { logger.info('start health check monitor'); _healthCheck = Timer.periodic( Duration(seconds: healthCheckInterval), _healthCheckTimer, ); _healthCheckTimer(_healthCheck); } /// Disconnects the WS and releases eventual resources Future<void> disconnect() async { if (_manuallyDisconnected) { return; } logger.info('disconnecting'); _connectionCompleter = Completer(); _cancelTimers(); _reconnecting = false; _manuallyDisconnected = true; _connectionStatus = ConnectionStatus.disconnected; await _connectionStatusController.close(); return _channel.sink.close(); } }
stream-chat-flutter/packages/stream_chat/lib/src/api/websocket.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat/lib/src/api/websocket.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 3046}
import 'package:json_annotation/json_annotation.dart'; import 'package:stream_chat/src/models/command.dart'; part 'channel_config.g.dart'; /// The class that contains the information about the configuration of a channel @JsonSerializable() class ChannelConfig { /// Constructor used for json serialization ChannelConfig({ this.automod, this.commands, this.connectEvents, this.createdAt, this.updatedAt, this.maxMessageLength, this.messageRetention, this.mutes, this.name, this.reactions, this.readEvents, this.replies, this.search, this.typingEvents, this.uploads, this.urlEnrichment, }); /// Create a new instance from a json factory ChannelConfig.fromJson(Map<String, dynamic> json) => _$ChannelConfigFromJson(json); /// Moderation configuration final String automod; /// List of available commands final List<Command> commands; /// True if the channel should send connect events final bool connectEvents; /// Date of channel creation final DateTime createdAt; /// Date of last channel update final DateTime updatedAt; /// Max channel message length final int maxMessageLength; /// Duration of message retention final String messageRetention; /// True if users can be muted final bool mutes; /// Name of the channel final String name; /// True if reaction are active for this channel final bool reactions; /// True if readEvents are active for this channel final bool readEvents; /// True if reply message are active for this channel final bool replies; /// True if it's possible to perform a search in this channel final bool search; /// True if typing events should be sent for this channel final bool typingEvents; /// True if it's possible to upload files to this channel final bool uploads; /// True if urls appears as attachments final bool urlEnrichment; /// Serialize to json Map<String, dynamic> toJson() => _$ChannelConfigToJson(this); }
stream-chat-flutter/packages/stream_chat/lib/src/models/channel_config.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat/lib/src/models/channel_config.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 589}
import 'package:json_annotation/json_annotation.dart'; import 'package:stream_chat/src/models/channel_model.dart'; import 'package:stream_chat/src/models/serialization.dart'; import 'package:stream_chat/src/models/user.dart'; part 'mute.g.dart'; /// The class that contains the information about a muted user @JsonSerializable() class Mute { /// Constructor used for json serialization Mute({this.user, this.channel, this.createdAt, this.updatedAt}); /// Create a new instance from a json factory Mute.fromJson(Map<String, dynamic> json) => _$MuteFromJson(json); /// The user that performed the muting action @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) final User user; /// The target user @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) final ChannelModel channel; /// The date in which the use was muted @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) final DateTime createdAt; /// The date of the last update @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) final DateTime updatedAt; /// Serialize to json Map<String, dynamic> toJson() => _$MuteToJson(this); }
stream-chat-flutter/packages/stream_chat/lib/src/models/mute.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat/lib/src/models/mute.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 374}
import 'package:stream_chat/src/client.dart'; /// Current package version /// Used in [StreamChatClient] to build the `x-stream-client` header // ignore: constant_identifier_names const PACKAGE_VERSION = '1.5.0';
stream-chat-flutter/packages/stream_chat/lib/version.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat/lib/version.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 66}
import 'dart:convert'; import 'package:test/test.dart'; import 'package:stream_chat/src/models/member.dart'; import 'package:stream_chat/src/models/user.dart'; void main() { group('src/models/member', () { const jsonExample = ''' { "user": { "id": "bbb19d9a-ee50-45bc-84e5-0584e79d0c9e", "role": "user", "created_at": "2020-01-28T22:17:30.826259Z", "updated_at": "2020-01-28T22:17:31.101222Z", "banned": false, "online": false, "name": "Robin Papa", "image": "https://pbs.twimg.com/profile_images/669512187778498560/L7wQctBt.jpg" }, "role": "member", "created_at": "2020-01-28T22:17:30.95443Z", "updated_at": "2020-01-28T22:17:30.95443Z" } '''; test('should parse json correctly', () { final member = Member.fromJson(json.decode(jsonExample)); expect(member.user, isA<User>()); expect(member.role, 'member'); expect(member.createdAt, DateTime.parse("2020-01-28T22:17:30.95443Z")); expect(member.updatedAt, DateTime.parse("2020-01-28T22:17:30.95443Z")); }); }); }
stream-chat-flutter/packages/stream_chat/test/src/models/member_test.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat/test/src/models/member_test.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 617}
import 'package:flutter/material.dart'; import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart'; import '../stream_chat_theme.dart'; import '../utils.dart'; class AttachmentTitle extends StatelessWidget { const AttachmentTitle({ Key key, @required this.attachment, @required this.messageTheme, }) : super(key: key); final MessageTheme messageTheme; final Attachment attachment; @override Widget build(BuildContext context) { return GestureDetector( onTap: () { if (attachment.titleLink != null) { launchURL(context, attachment.titleLink); } }, child: Padding( padding: const EdgeInsets.all(8.0), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Text( attachment.title, overflow: TextOverflow.ellipsis, style: messageTheme.messageText.copyWith( color: StreamChatTheme.of(context).colorTheme.accentBlue, fontWeight: FontWeight.bold, ), ), if (attachment.titleLink != null || attachment.ogScrapeUrl != null) Text( Uri.parse(attachment.titleLink ?? attachment.ogScrapeUrl) .authority .split('.') .reversed .take(2) .toList() .reversed .join('.'), style: messageTheme.messageText, ), ], ), ), ); } }
stream-chat-flutter/packages/stream_chat_flutter/lib/src/attachment/attachment_title.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/lib/src/attachment/attachment_title.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 824}
import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import 'package:video_player/video_player.dart'; import 'attachment/attachment.dart'; class ChannelMediaDisplayScreen extends StatefulWidget { /// The sorting used for the channels matching the filters. /// Sorting is based on field and direction, multiple sorting options can be provided. /// You can sort based on last_updated, last_message_at, updated_at, created_at or member_count. /// Direction can be ascending or descending. final List<SortOption> sortOptions; /// Pagination parameters /// limit: the number of users to return (max is 30) /// offset: the offset (max is 1000) /// message_limit: how many messages should be included to each channel final PaginationParams paginationParams; /// The builder used when the file list is empty. final WidgetBuilder emptyBuilder; final ShowMessageCallback onShowMessage; const ChannelMediaDisplayScreen({ this.sortOptions, this.paginationParams, this.emptyBuilder, this.onShowMessage, }); @override _ChannelMediaDisplayScreenState createState() => _ChannelMediaDisplayScreenState(); } class _ChannelMediaDisplayScreenState extends State<ChannelMediaDisplayScreen> { Map<String, VideoPlayerController> controllerCache = {}; @override void initState() { super.initState(); final messageSearchBloc = MessageSearchBloc.of(context); messageSearchBloc.search( filter: { 'cid': { r'$in': [StreamChannel.of(context).channel.cid], } }, messageFilter: { 'attachments.type': { r'$in': ['image', 'video'] }, }, sort: widget.sortOptions, pagination: widget.paginationParams, ); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: StreamChatTheme.of(context).colorTheme.white, appBar: AppBar( brightness: Theme.of(context).brightness, elevation: 1, centerTitle: true, title: Text( 'Photos & Videos', style: TextStyle( color: StreamChatTheme.of(context).colorTheme.black, fontSize: 16.0, ), ), leading: Center( child: InkWell( onTap: () { Navigator.of(context).pop(); }, child: Container( width: 24.0, height: 24.0, child: StreamSvgIcon.left( color: StreamChatTheme.of(context).colorTheme.black, size: 24.0, ), ), ), ), backgroundColor: StreamChatTheme.of(context).colorTheme.white, ), body: _buildMediaGrid(), ); } Widget _buildMediaGrid() { final messageSearchBloc = MessageSearchBloc.of(context); return StreamBuilder<List<GetMessageResponse>>( builder: (context, snapshot) { if (snapshot.data == null) { return Center( child: const CircularProgressIndicator(), ); } if (snapshot.data.isEmpty) { if (widget.emptyBuilder != null) { return widget.emptyBuilder(context); } return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ StreamSvgIcon.pictures( size: 136.0, color: StreamChatTheme.of(context).colorTheme.greyGainsboro, ), SizedBox(height: 16.0), Text( 'No Media', style: TextStyle( fontSize: 14.0, color: StreamChatTheme.of(context).colorTheme.black, ), ), SizedBox(height: 8.0), Text( 'Photos or video sent in this chat will \nappear here', textAlign: TextAlign.center, style: TextStyle( fontSize: 14.0, color: StreamChatTheme.of(context) .colorTheme .black .withOpacity(0.5), ), ), ], ), ); } final media = <_AssetPackage>[]; for (var item in snapshot.data) { item.message.attachments .where((e) => (e.type == 'image' || e.type == 'video') && e.ogScrapeUrl == null) .forEach((e) { VideoPlayerController controller; if (e.type == 'video') { var cachedController = controllerCache[e.assetUrl]; if (cachedController == null) { controller = VideoPlayerController.network(e.assetUrl); controller.initialize(); controllerCache[e.assetUrl] = controller; } else { controller = cachedController; } } media.add(_AssetPackage(e, item.message, controller)); }); } return LazyLoadScrollView( onEndOfPage: () => messageSearchBloc.loadMore( filter: { 'cid': { r'$in': [StreamChannel.of(context).channel.cid] } }, messageFilter: { 'attachments.type': { r'$in': ['image', 'video'] }, }, sort: widget.sortOptions, pagination: widget.paginationParams.copyWith( offset: messageSearchBloc.messageResponses?.length ?? 0, ), ), child: GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3), itemBuilder: (context, position) { var channel = StreamChannel.of(context).channel; return Padding( padding: const EdgeInsets.all(1.0), child: InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => StreamChannel( channel: channel, child: FullScreenMedia( mediaAttachments: media.map((e) => e.attachment).toList(), startIndex: position, message: media[position].message, sentAt: media[position].message.createdAt, userName: media[position].message.user.name, onShowMessage: widget.onShowMessage, ), ), ), ); }, child: media[position].attachment.type == 'image' ? IgnorePointer( child: ImageAttachment( attachment: media[position].attachment, message: media[position].message, showTitle: false, size: Size( MediaQuery.of(context).size.width * 0.8, MediaQuery.of(context).size.height * 0.3, ), ), ) : VideoPlayer(media[position].videoPlayer), ), ); }, itemCount: media.length, ), ); }, stream: messageSearchBloc.messagesStream, ); } @override void dispose() { super.dispose(); for (var c in controllerCache.values) { c.dispose(); } } } class _AssetPackage { Attachment attachment; Message message; VideoPlayerController videoPlayer; _AssetPackage(this.attachment, this.message, this.videoPlayer); }
stream-chat-flutter/packages/stream_chat_flutter/lib/src/channel_media_display_screen.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/lib/src/channel_media_display_screen.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 4200}
import 'dart:convert'; import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:stream_chat_flutter/src/message_action.dart'; import 'package:stream_chat_flutter/src/reaction_picker.dart'; import 'package:stream_chat_flutter/src/stream_svg_icon.dart'; import 'package:stream_chat_flutter/src/utils.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import 'extension.dart'; import 'message_input.dart'; import 'message_widget.dart'; import 'stream_chat.dart'; import 'stream_chat_theme.dart'; class MessageActionsModal extends StatefulWidget { final Widget Function(BuildContext, Message) editMessageInputBuilder; final void Function(Message) onThreadReplyTap; final void Function(Message) onReplyTap; final Message message; final MessageTheme messageTheme; final bool showReactions; final bool showDeleteMessage; final bool showCopyMessage; final bool showEditMessage; final bool showResendMessage; final bool showReplyMessage; final bool showThreadReplyMessage; final bool showFlagButton; final bool reverse; final ShapeBorder messageShape; final ShapeBorder attachmentShape; final DisplayWidget showUserAvatar; final BorderRadius attachmentBorderRadiusGeometry; /// List of custom actions final List<MessageAction> customActions; const MessageActionsModal({ Key key, @required this.message, @required this.messageTheme, this.showReactions = true, this.showDeleteMessage = true, this.showEditMessage = true, this.onReplyTap, this.onThreadReplyTap, this.showCopyMessage = true, this.showReplyMessage = true, this.showResendMessage = true, this.showThreadReplyMessage = true, this.showFlagButton = true, this.showUserAvatar = DisplayWidget.show, this.editMessageInputBuilder, this.messageShape, this.attachmentShape, this.reverse = false, this.customActions = const [], this.attachmentBorderRadiusGeometry, }) : super(key: key); @override _MessageActionsModalState createState() => _MessageActionsModalState(); } class _MessageActionsModalState extends State<MessageActionsModal> { bool _showActions = true; @override Widget build(BuildContext context) { return _showMessageOptionsModal(); } Widget _showMessageOptionsModal() { final size = MediaQuery.of(context).size; final user = StreamChat.of(context).user; final roughMaxSize = 2 * size.width / 3; var messageTextLength = widget.message.text.length; if (widget.message.quotedMessage != null) { var quotedMessageLength = widget.message.quotedMessage.text.length + 40; if (widget.message.quotedMessage.attachments?.isNotEmpty == true) { quotedMessageLength += 40; } if (quotedMessageLength > messageTextLength) { messageTextLength = quotedMessageLength; } } final roughSentenceSize = messageTextLength * widget.messageTheme.messageText.fontSize * 1.2; final divFactor = widget.message.attachments?.isNotEmpty == true ? 1 : (roughSentenceSize == 0 ? 1 : (roughSentenceSize / roughMaxSize)); final hasFileAttachment = widget.message.attachments?.any((it) => it.type == 'file') == true; return GestureDetector( behavior: HitTestBehavior.translucent, onTap: () => Navigator.maybePop(context), child: Stack( children: [ Positioned.fill( child: BackdropFilter( filter: ImageFilter.blur( sigmaX: 10, sigmaY: 10, ), child: Container( color: StreamChatTheme.of(context).colorTheme.overlay, ), ), ), if (_showActions) TweenAnimationBuilder<double>( tween: Tween(begin: 0.0, end: 1.0), duration: Duration(milliseconds: 300), curve: Curves.easeInOutBack, builder: (context, val, snapshot) { return Transform.scale( scale: val, child: Center( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: widget.reverse ? CrossAxisAlignment.end : CrossAxisAlignment.start, children: <Widget>[ if (widget.showReactions && (widget.message.status == MessageSendingStatus.sent || widget.message.status == null)) Align( alignment: Alignment( user.id == widget.message.user.id ? (divFactor > 1.0 ? 0.0 : (1.0 - divFactor)) : (divFactor > 1.0 ? 0.0 : -(1.0 - divFactor)), 0.0), child: ReactionPicker( message: widget.message, messageTheme: widget.messageTheme, ), ), SizedBox(height: 8), IgnorePointer( child: MessageWidget( key: Key('MessageWidget'), reverse: widget.reverse, attachmentBorderRadiusGeometry: widget.attachmentBorderRadiusGeometry, message: widget.message.copyWith( text: widget.message.text.length > 200 ? '${widget.message.text.substring(0, 200)}...' : widget.message.text, ), messageTheme: widget.messageTheme, showReactions: false, showUsername: false, showThreadReplyIndicator: false, showReplyMessage: false, showUserAvatar: widget.showUserAvatar, attachmentPadding: EdgeInsets.all( hasFileAttachment ? 4 : 2, ), showTimestamp: false, translateUserAvatar: false, padding: const EdgeInsets.all(0), textPadding: EdgeInsets.symmetric( vertical: 8.0, horizontal: widget.message.text.isOnlyEmoji ? 0 : 16.0, ), showReactionPickerIndicator: widget.showReactions && (widget.message.status == MessageSendingStatus.sent || widget.message.status == null), showInChannelIndicator: false, showSendingIndicator: false, shape: widget.messageShape, attachmentShape: widget.attachmentShape, ), ), SizedBox(height: 8), Padding( padding: EdgeInsets.only( left: widget.reverse ? 0 : 40, ), child: SizedBox( width: MediaQuery.of(context).size.width * 0.75, child: Material( color: StreamChatTheme.of(context) .colorTheme .whiteSnow, clipBehavior: Clip.hardEdge, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ if (widget.showReplyMessage && (widget.message.status == MessageSendingStatus.sent || widget.message.status == null) && widget.message.parentId == null) _buildReplyButton(context), if (widget.showThreadReplyMessage && (widget.message.status == MessageSendingStatus.sent || widget.message.status == null) && widget.message.parentId == null) _buildThreadReplyButton(context), if (widget.showResendMessage) _buildResendMessage(context), if (widget.showEditMessage) _buildEditMessage(context), if (widget.showCopyMessage) _buildCopyButton(context), if (widget.showFlagButton) _buildFlagButton(context), if (widget.showDeleteMessage) _buildDeleteButton(context), ...widget.customActions.map((action) { return _buildCustomAction( context, action, ); }) ].insertBetween( Container( height: 1, color: StreamChatTheme.of(context) .colorTheme .greyWhisper, ), ), ), ), ), ), ], ), ), ), ), ); }, ), ], ), ); } InkWell _buildCustomAction( BuildContext context, MessageAction messageAction, ) { return InkWell( onTap: () { messageAction.onTap?.call(widget.message); }, child: Padding( padding: const EdgeInsets.symmetric(vertical: 11.0, horizontal: 16.0), child: Row( children: [ messageAction.leading ?? Offstage(), const SizedBox(width: 16), messageAction.title ?? Offstage(), ], ), ), ); } void _showFlagDialog() async { final client = StreamChat.of(context).client; final answer = await showConfirmationDialog( context, title: 'Flag Message', icon: StreamSvgIcon.flag( color: StreamChatTheme.of(context).colorTheme.accentRed, size: 24.0, ), question: 'Do you want to send a copy of this message to a\nmoderator for further investigation?', okText: 'FLAG', cancelText: 'CANCEL', ); final theme = StreamChatTheme.of(context); if (answer == true) { try { await client.flagMessage(widget.message.id); await showInfoDialog( context, icon: StreamSvgIcon.flag( color: theme.colorTheme.accentRed, size: 24.0, ), details: 'The message has been reported to a moderator.', title: 'Message flagged', okText: 'OK', ); } catch (err) { if (json.decode(err?.body ?? {})['code'] == 4) { await showInfoDialog( context, icon: StreamSvgIcon.flag( color: theme.colorTheme.accentRed, size: 24.0, ), details: 'The message has been reported to a moderator.', title: 'Message flagged', okText: 'OK', ); } else { _showErrorAlert(); } } } } void _showDeleteDialog() async { setState(() { _showActions = false; }); var answer = await showConfirmationDialog( context, title: 'Delete message', icon: StreamSvgIcon.flag( color: StreamChatTheme.of(context).colorTheme.accentRed, size: 24.0, ), question: 'Are you sure you want to permanently delete this\nmessage?', okText: 'DELETE', cancelText: 'CANCEL', ); if (answer) { try { Navigator.pop(context); await StreamChannel.of(context).channel.deleteMessage(widget.message); } catch (err) { _showErrorAlert(); } } else { setState(() { _showActions = true; }); } } void _showErrorAlert() { showInfoDialog( context, icon: StreamSvgIcon.error( color: StreamChatTheme.of(context).colorTheme.accentRed, size: 24.0, ), details: 'The operation couldn\'t be completed.', title: 'Something went wrong', okText: 'OK', ); } Widget _buildReplyButton(BuildContext context) { return InkWell( onTap: () { Navigator.pop(context); if (widget.onReplyTap != null) { widget.onReplyTap(widget.message); } }, child: Padding( padding: const EdgeInsets.symmetric(vertical: 11.0, horizontal: 16.0), child: Row( children: [ StreamSvgIcon.reply( color: StreamChatTheme.of(context).primaryIconTheme.color, ), const SizedBox(width: 16), Text( 'Reply', style: StreamChatTheme.of(context).textTheme.body, ), ], ), ), ); } Widget _buildFlagButton(BuildContext context) { return InkWell( onTap: () => _showFlagDialog(), child: Padding( padding: const EdgeInsets.symmetric(vertical: 11.0, horizontal: 16.0), child: Row( children: [ StreamSvgIcon.iconFlag( color: StreamChatTheme.of(context).primaryIconTheme.color, ), const SizedBox(width: 16), Text( 'Flag Message', style: StreamChatTheme.of(context).textTheme.body, ), ], ), ), ); } Widget _buildDeleteButton(BuildContext context) { final isDeleteFailed = widget.message.status == MessageSendingStatus.failed_delete; return InkWell( onTap: () => _showDeleteDialog(), child: Padding( padding: const EdgeInsets.symmetric(vertical: 11.0, horizontal: 16.0), child: Row( children: [ StreamSvgIcon.delete( color: Colors.red, ), const SizedBox(width: 16), Text( isDeleteFailed ? 'Retry Deleting Message' : 'Delete Message', style: StreamChatTheme.of(context) .textTheme .body .copyWith(color: Colors.red), ), ], ), ), ); } Widget _buildCopyButton(BuildContext context) { return InkWell( onTap: () async { await Clipboard.setData(ClipboardData(text: widget.message.text)); Navigator.pop(context); }, child: Padding( padding: const EdgeInsets.symmetric(vertical: 11.0, horizontal: 16.0), child: Row( children: [ StreamSvgIcon.copy( size: 24, color: StreamChatTheme.of(context).primaryIconTheme.color, ), const SizedBox(width: 16), Text( 'Copy Message', style: StreamChatTheme.of(context).textTheme.body, ), ], ), ), ); } Widget _buildEditMessage(BuildContext context) { return InkWell( onTap: () async { Navigator.pop(context); _showEditBottomSheet(context); }, child: Padding( padding: const EdgeInsets.symmetric(vertical: 11.0, horizontal: 16.0), child: Row( children: [ StreamSvgIcon.edit( color: StreamChatTheme.of(context).primaryIconTheme.color, ), const SizedBox(width: 16), Text( 'Edit Message', style: StreamChatTheme.of(context).textTheme.body, ), ], ), ), ); } Widget _buildResendMessage(BuildContext context) { final isUpdateFailed = widget.message.status == MessageSendingStatus.failed_update; return InkWell( onTap: () { Navigator.pop(context); final channel = StreamChannel.of(context).channel; if (isUpdateFailed) { channel.updateMessage(widget.message); } else { channel.sendMessage(widget.message); } }, child: Padding( padding: const EdgeInsets.symmetric(vertical: 11.0, horizontal: 16.0), child: Row( children: [ StreamSvgIcon.circleUp( color: StreamChatTheme.of(context).colorTheme.accentBlue, ), const SizedBox(width: 16), Text( isUpdateFailed ? 'Resend Edited Message' : 'Resend', style: StreamChatTheme.of(context).textTheme.body, ), ], ), ), ); } void _showEditBottomSheet(BuildContext context) { final channel = StreamChannel.of(context).channel; showModalBottomSheet( context: context, elevation: 2, clipBehavior: Clip.hardEdge, isScrollControlled: true, backgroundColor: StreamChatTheme.of(context).messageInputTheme.inputBackground, shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(16), topRight: Radius.circular(16), ), ), builder: (context) { return StreamChannel( channel: channel, child: Flex( direction: Axis.vertical, mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: <Widget>[ Padding( padding: const EdgeInsets.fromLTRB(8, 8, 8, 0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: StreamSvgIcon.edit( color: StreamChatTheme.of(context) .colorTheme .greyGainsboro, ), ), Text( 'Edit Message', style: TextStyle(fontWeight: FontWeight.bold), ), IconButton( visualDensity: VisualDensity.compact, icon: StreamSvgIcon.closeSmall(), onPressed: Navigator.of(context).pop, ), ], ), ), widget.editMessageInputBuilder != null ? widget.editMessageInputBuilder(context, widget.message) : MessageInput( editMessage: widget.message, preMessageSending: (m) { FocusScope.of(context).unfocus(); Navigator.pop(context); return m; }, ), ], ), ); }, ); } Widget _buildThreadReplyButton(BuildContext context) { return InkWell( onTap: () { Navigator.pop(context); if (widget.onThreadReplyTap != null) { widget.onThreadReplyTap(widget.message); } }, child: Padding( padding: const EdgeInsets.symmetric(vertical: 11.0, horizontal: 16.0), child: Row( children: [ StreamSvgIcon.thread( color: StreamChatTheme.of(context).primaryIconTheme.color, ), const SizedBox(width: 16), Text( 'Thread Reply', style: StreamChatTheme.of(context).textTheme.body, ), ], ), ), ); } }
stream-chat-flutter/packages/stream_chat_flutter/lib/src/message_actions_modal.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/lib/src/message_actions_modal.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 12366}
import 'package:flutter/material.dart'; class StreamNeumorphicButton extends StatelessWidget { final Widget child; final Color backgroundColor; const StreamNeumorphicButton({ Key key, @required this.child, this.backgroundColor = Colors.white, }) : super(key: key); @override Widget build(BuildContext context) { return Container( margin: EdgeInsets.all(8.0), height: 40, width: 40, decoration: BoxDecoration( color: backgroundColor, shape: BoxShape.circle, boxShadow: [ BoxShadow( color: Colors.grey[700], offset: Offset(0, 1.0), blurRadius: 0.5, spreadRadius: 0, ), BoxShadow( color: Colors.white, offset: Offset.zero, blurRadius: 0.5, spreadRadius: 0, ), ], ), child: child, ); } }
stream-chat-flutter/packages/stream_chat_flutter/lib/src/stream_neumorphic_button.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/lib/src/stream_neumorphic_button.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 444}
export 'src/back_button.dart'; export 'src/channel_header.dart'; export 'src/channel_image.dart'; export 'src/channel_list_header.dart'; export 'src/channel_list_view.dart'; export 'src/channel_name.dart'; export 'src/channel_preview.dart'; export 'src/date_divider.dart'; export 'src/deleted_message.dart'; export 'src/message_action.dart'; export 'src/attachment/attachment.dart'; export 'src/full_screen_media.dart'; export 'src/image_header.dart'; export 'src/image_footer.dart'; export 'src/message_input.dart'; export 'src/message_list_view.dart'; export 'src/message_text.dart'; export 'src/message_widget.dart'; export 'src/reaction_picker.dart'; export 'src/sending_indicator.dart'; export 'src/stream_chat_theme.dart'; export 'src/stream_neumorphic_button.dart'; export 'src/stream_svg_icon.dart'; export 'src/system_message.dart'; export 'src/thread_header.dart'; export 'src/typing_indicator.dart'; export 'src/user_avatar.dart'; export 'src/user_item.dart'; export 'src/user_item.dart'; export 'src/user_list_view.dart'; export 'src/user_list_view.dart'; export 'src/utils.dart'; export 'src/message_search_item.dart'; export 'src/message_search_list_view.dart'; export 'src/unread_indicator.dart'; export 'src/option_list_tile.dart'; export 'src/channel_file_display_screen.dart'; export 'src/channel_media_display_screen.dart'; export 'src/info_tile.dart'; export 'src/stream_chat.dart'; export 'src/connection_status_builder.dart'; export 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart';
stream-chat-flutter/packages/stream_chat_flutter/lib/stream_chat_flutter.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat_flutter/lib/stream_chat_flutter.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 570}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'message_dao.dart'; // ************************************************************************** // DaoGenerator // ************************************************************************** mixin _$MessageDaoMixin on DatabaseAccessor<MoorChatDatabase> { $MessagesTable get messages => attachedDatabase.messages; $UsersTable get users => attachedDatabase.users; }
stream-chat-flutter/packages/stream_chat_persistence/lib/src/dao/message_dao.g.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat_persistence/lib/src/dao/message_dao.g.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 99}
import 'package:moor/moor.dart'; import 'package:stream_chat_persistence/src/converter/map_converter.dart'; /// Represents a [Channels] table in [MoorChatDatabase]. @DataClassName('ChannelEntity') class Channels extends Table { /// The id of this channel TextColumn get id => text()(); /// The type of this channel TextColumn get type => text()(); /// The cid of this channel TextColumn get cid => text()(); /// The channel configuration data TextColumn get config => text().map(MapConverter<Object>())(); /// True if this channel entity is frozen BoolColumn get frozen => boolean().withDefault(const Constant(false))(); /// The date of the last message DateTimeColumn get lastMessageAt => dateTime().nullable()(); /// The date of channel creation DateTimeColumn get createdAt => dateTime().nullable()(); /// The date of the last channel update DateTimeColumn get updatedAt => dateTime().nullable()(); /// The date of channel deletion DateTimeColumn get deletedAt => dateTime().nullable()(); /// The count of this channel members IntColumn get memberCount => integer().nullable()(); /// The id of the user that created this channel TextColumn get createdById => text().nullable()(); /// Map of custom channel extraData TextColumn get extraData => text().nullable().map(MapConverter<Object>())(); @override Set<Column> get primaryKey => {cid}; }
stream-chat-flutter/packages/stream_chat_persistence/lib/src/entity/channels.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat_persistence/lib/src/entity/channels.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 392}
import 'package:stream_chat/stream_chat.dart'; import 'package:stream_chat_persistence/src/db/moor_chat_database.dart'; /// Useful mapping functions for [ReadEntity] extension ReadEntityX on ReadEntity { /// Maps a [ReadEntity] into [Read] Read toRead({User user}) => Read( user: user, lastRead: lastRead, unreadMessages: unreadMessages, ); } /// Useful mapping functions for [Read] extension ReadX on Read { /// Maps a [Read] into [ReadEntity] ReadEntity toEntity({String cid}) => ReadEntity( lastRead: lastRead, userId: user?.id, channelCid: cid, unreadMessages: unreadMessages, ); }
stream-chat-flutter/packages/stream_chat_persistence/lib/src/mapper/read_mapper.dart/0
{'file_path': 'stream-chat-flutter/packages/stream_chat_persistence/lib/src/mapper/read_mapper.dart', 'repo_id': 'stream-chat-flutter', 'token_count': 259}
include: package:very_good_analysis/analysis_options.5.0.0.yaml linter: rules: public_member_api_docs: false analyzer: exclude: - lib/firebase_options_dev.dart - lib/firebase_options_prod.dart
super_dash/analysis_options.yaml/0
{'file_path': 'super_dash/analysis_options.yaml', 'repo_id': 'super_dash', 'token_count': 85}
import 'dart:async'; import 'package:flame/components.dart'; import 'package:super_dash/game/game.dart'; class ItemEffect extends SpriteAnimationComponent with HasGameRef<SuperDashGame> { ItemEffect({ required this.type, super.position, }) : super(removeOnFinish: true, priority: 22); final ItemType type; @override FutureOr<void> onLoad() async { await super.onLoad(); if (type == ItemType.egg) { animation = await gameRef.loadSpriteAnimation( 'anim/spritesheet_fx_large.png', SpriteAnimationData.sequenced( amount: 14, amountPerRow: 7, textureSize: Vector2.all(192), stepTime: .042, loop: false, ), ); size = Vector2.all(192); anchor = Anchor.center; } else if (type == ItemType.goldenFeather) { animation = await gameRef.loadSpriteAnimation( 'anim/spritesheet_poof_orange.png', SpriteAnimationData.sequenced( amount: 20, amountPerRow: 5, textureSize: Vector2.all(192), stepTime: .042, loop: false, ), ); size = Vector2.all(192); anchor = Anchor.center; } else { animation = await gameRef.loadSpriteAnimation( 'anim/spritesheet_fx_small.png', SpriteAnimationData.sequenced( amount: 9, amountPerRow: 3, textureSize: Vector2.all(64), stepTime: .042, loop: false, ), ); size = Vector2.all(64); } } @override void update(double dt) { super.update(dt); final player = gameRef.player; if (player == null) return; position = player.position; } }
super_dash/lib/game/components/item_effect.dart/0
{'file_path': 'super_dash/lib/game/components/item_effect.dart', 'repo_id': 'super_dash', 'token_count': 768}
export 'game_background.dart'; export 'score_label.dart'; export 'tap_to_jump_overlay.dart';
super_dash/lib/game/widgets/widgets.dart/0
{'file_path': 'super_dash/lib/game/widgets/widgets.dart', 'repo_id': 'super_dash', 'token_count': 35}
part of 'score_bloc.dart'; sealed class ScoreEvent extends Equatable { const ScoreEvent(); @override List<Object> get props => []; } final class ScoreSubmitted extends ScoreEvent { const ScoreSubmitted(); } final class ScoreInitialsUpdated extends ScoreEvent { const ScoreInitialsUpdated({required this.character, required this.index}); final String character; final int index; } final class ScoreInitialsSubmitted extends ScoreEvent { const ScoreInitialsSubmitted(); } final class ScoreLeaderboardRequested extends ScoreEvent { const ScoreLeaderboardRequested(); }
super_dash/lib/score/bloc/score_event.dart/0
{'file_path': 'super_dash/lib/score/bloc/score_event.dart', 'repo_id': 'super_dash', 'token_count': 158}
export 'buttons.dart';
super_dash/lib/score/score_overview/widgets/widgets.dart/0
{'file_path': 'super_dash/lib/score/score_overview/widgets/widgets.dart', 'repo_id': 'super_dash', 'token_count': 9}
import 'package:app_ui/src/layout/breakpoints.dart'; import 'package:flutter/material.dart'; /// Extension on [BuildContext] to provide information about the layout. extension BuildContextLayoutX on BuildContext { /// Whether the device is small. bool get isSmall { final mediaQuery = MediaQuery.of(this); return mediaQuery.size.width < AppBreakpoints.small.size && mediaQuery.orientation == Orientation.portrait; } }
super_dash/packages/app_ui/lib/src/layout/context.dart/0
{'file_path': 'super_dash/packages/app_ui/lib/src/layout/context.dart', 'repo_id': 'super_dash', 'token_count': 135}
/// {@template leaderboard_exception} /// Base exception for leaderboard repository failures. /// {@endtemplate} abstract class LeaderboardException implements Exception { /// {@macro leaderboard_exception} const LeaderboardException(this.error, this.stackTrace); /// The error that was caught. final Object error; /// The Stacktrace associated with the [error]. final StackTrace stackTrace; } /// {@template leaderboard_deserialization_exception} /// Exception thrown when leaderboard data cannot be deserialized in the /// expected way. /// {@endtemplate} class LeaderboardDeserializationException extends LeaderboardException { /// {@macro leaderboard_deserialization_exception} const LeaderboardDeserializationException(super.error, super.stackTrace); } /// {@template fetch_top_10_leaderboard_exception} /// Exception thrown when failure occurs while fetching top 10 leaderboard. /// {@endtemplate} class FetchTop10LeaderboardException extends LeaderboardException { /// {@macro fetch_top_10_leaderboard_exception} const FetchTop10LeaderboardException(super.error, super.stackTrace); } /// {@template fetch_leaderboard_exception} /// Exception thrown when failure occurs while fetching the leaderboard. /// {@endtemplate} class FetchLeaderboardException extends LeaderboardException { /// {@macro fetch_top_10_leaderboard_exception} const FetchLeaderboardException(super.error, super.stackTrace); } /// {@template add_leaderboard_entry_exception} /// Exception thrown when failure occurs while adding entry to leaderboard. /// {@endtemplate} class AddLeaderboardEntryException extends LeaderboardException { /// {@macro add_leaderboard_entry_exception} const AddLeaderboardEntryException(super.error, super.stackTrace); }
super_dash/packages/leaderboard_repository/lib/src/models/exceptions.dart/0
{'file_path': 'super_dash/packages/leaderboard_repository/lib/src/models/exceptions.dart', 'repo_id': 'super_dash', 'token_count': 472}
import 'dart:ui'; import 'package:bloc_test/bloc_test.dart'; import 'package:flame/cache.dart'; import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flame_tiled/flame_tiled.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leap/leap.dart'; import 'package:mocktail/mocktail.dart'; import 'package:super_dash/audio/audio.dart'; import 'package:super_dash/game/game.dart'; class _MockImage extends Mock implements Image {} class _MockImages extends Mock implements Images {} class _MockTileset extends Mock implements Tileset {} class _MockGameBloc extends MockBloc<GameEvent, GameState> implements GameBloc {} class _MockAudioController extends Mock implements AudioController {} class _MockLeapMap extends Mock implements LeapMap {} class _MockObjectGroup extends Mock implements ObjectGroup {} class _TestSuperDashGame extends SuperDashGame { _TestSuperDashGame({this.layerObjects = const []}) : super( gameBloc: _MockGameBloc(), audioController: _MockAudioController(), ); final List<TiledObject> layerObjects; @override Future<void> onLoad() async { // Noop } @override Images get images { final instance = _MockImages(); final imageInstance = _MockImage(); when(() => imageInstance.width).thenReturn(100); when(() => imageInstance.height).thenReturn(100); when(() => instance.load(any())).thenAnswer((_) async => imageInstance); return instance; } LeapMap? _leapMap; @override LeapMap get leapMap { if (_leapMap == null) { final map = _MockLeapMap(); final objectGroup = _MockObjectGroup(); when(() => objectGroup.objects).thenReturn(layerObjects); when(() => map.getTileLayer<ObjectGroup>(any())).thenReturn(objectGroup); _leapMap = map; } return _leapMap!; } } class _ReferenceComponent extends PositionComponent {} class _SpawnedComponent extends PositionComponent { _SpawnedComponent({required this.tiledObject}); final TiledObject tiledObject; } void main() { group('ObjectGroupProximitySpawner', () { setUpAll(() { registerFallbackValue(Component()); }); final objects = [ TiledObject( id: 1, x: 400, ), TiledObject( id: 2, x: 800, ), ]; testWithGame( 'can be added to a game', _TestSuperDashGame.new, (game) async { final reference = _ReferenceComponent(); await game.world.ensureAdd(reference); await game.ensureAdd( ObjectGroupProximityBuilder<_ReferenceComponent>( proximity: 200, tileLayerName: '', tileset: _MockTileset(), componentBuilder: ({ required TiledObject tiledObject, }) => PositionComponent(), ), ); }, ); testWithGame( 'spawn an object when the reference is far enough', () => _TestSuperDashGame(layerObjects: objects), (game) async { final reference = _ReferenceComponent(); await game.world.ensureAdd(reference); final proximityBuilder = ObjectGroupProximityBuilder<_ReferenceComponent>( proximity: 200, tileLayerName: '', tileset: _MockTileset(), componentBuilder: _SpawnedComponent.new, ); await game.ensureAdd(proximityBuilder); reference.x = 201; proximityBuilder.update(0); await game.ready(); verify(() => game.leapMap.add(any())).called(1); }, ); testWithGame( "doesn't spanw the component again", () => _TestSuperDashGame(layerObjects: objects), (game) async { final reference = _ReferenceComponent(); await game.world.ensureAdd(reference); final proximityBuilder = ObjectGroupProximityBuilder<_ReferenceComponent>( proximity: 200, tileLayerName: '', tileset: _MockTileset(), componentBuilder: _SpawnedComponent.new, ); await game.ensureAdd(proximityBuilder); reference.x = 201; proximityBuilder.update(0); await game.ready(); verify(() => game.leapMap.add(any())).called(1); proximityBuilder.update(0); await game.ready(); verifyNever(() => game.leapMap.add(any())); }, ); }); }
super_dash/test/game/components/object_group_proximity_spawner_test.dart/0
{'file_path': 'super_dash/test/game/components/object_group_proximity_spawner_test.dart', 'repo_id': 'super_dash', 'token_count': 1795}
import 'package:flutter/material.dart'; import '../../models/challenge.dart'; import '../../repository/challenges_repository.dart'; class ListScreen extends StatelessWidget { const ListScreen({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Challenges')), body: Container( child: ListView( children: ChallengeRepository().allChallenges().map((challenge) { return ChallengeListElement(challenge: challenge); }).toList(), ), ), ); } } class ChallengeListElement extends StatelessWidget { const ChallengeListElement({ Key key, this.challenge, }) : super(key: key); final Challenge challenge; String difficultyImagePath() { switch (this.challenge.difficultyLevel) { case 1: return 'assets/images/icons/dash-baby.png'; case 2: return 'assets/images/icons/dash.png'; case 3: return 'assets/images/icons/dash-expert.png'; default: return ''; } } @override Widget build(BuildContext context) { return GestureDetector( child: Container( padding: EdgeInsets.fromLTRB(16, 6, 16, 6), decoration: BoxDecoration( border: Border( bottom: BorderSide(color: Colors.grey), ), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Image.asset(difficultyImagePath(), height: 60, width: 60), Expanded( child: Text( challenge.title, style: TextStyle(fontSize: 20.0), ), ), Icon(Icons.arrow_forward_ios), ], ), ), onTap: () { Navigator.of(context).pushNamed('/game/${challenge.id}'); }, ); } }
super_flutter_maker/game/lib/screens/list_screen/list_screen.dart/0
{'file_path': 'super_flutter_maker/game/lib/screens/list_screen/list_screen.dart', 'repo_id': 'super_flutter_maker', 'token_count': 851}
Map<String, T> deriveMapFromMap<T>(dynamic data, T Function(dynamic) mapper) => Map<String, dynamic>.from((data as Map<String, dynamic>?) ?? <String, dynamic>{}).map( (String key, dynamic value) => MapEntry<String, T>(key, mapper(value)), );
tailor_made/lib/data/repositories/derive_map_from_data.dart/0
{'file_path': 'tailor_made/lib/data/repositories/derive_map_from_data.dart', 'repo_id': 'tailor_made', 'token_count': 93}
export 'entities/account_entity.dart'; export 'entities/auth_exception.dart'; export 'entities/contact_entity.dart'; export 'entities/create_contact_data.dart'; export 'entities/create_image_data.dart'; export 'entities/create_job_data.dart'; export 'entities/create_payment_data.dart'; export 'entities/image_entity.dart'; export 'entities/image_file_reference.dart'; export 'entities/image_operation.dart'; export 'entities/job_entity.dart'; export 'entities/measure_entity.dart'; export 'entities/measure_group.dart'; export 'entities/payment_entity.dart'; export 'entities/payment_operation.dart'; export 'entities/reference_entity.dart'; export 'entities/setting_entity.dart'; export 'entities/stats_entity.dart'; export 'entities/stats_item_entity.dart';
tailor_made/lib/domain/entities.dart/0
{'file_path': 'tailor_made/lib/domain/entities.dart', 'repo_id': 'tailor_made', 'token_count': 262}
import 'package:equatable/equatable.dart'; class ReferenceEntity with EquatableMixin { const ReferenceEntity({required this.id, required this.path}); final String id; final String path; @override List<Object> get props => <Object>[id, path]; }
tailor_made/lib/domain/entities/reference_entity.dart/0
{'file_path': 'tailor_made/lib/domain/entities/reference_entity.dart', 'repo_id': 'tailor_made', 'token_count': 76}
// File generated by FlutterFire CLI. // ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; import 'package:flutter/foundation.dart' show defaultTargetPlatform, kIsWeb, TargetPlatform; /// Default [FirebaseOptions] for use with your Firebase apps. /// /// Example: /// ```dart /// import 'firebase_options.dev.dart'; /// // ... /// await Firebase.initializeApp( /// options: DefaultFirebaseOptions.currentPlatform, /// ); /// ``` class DefaultFirebaseOptions { static FirebaseOptions get currentPlatform { if (kIsWeb) { throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for web - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); } switch (defaultTargetPlatform) { case TargetPlatform.android: return android; case TargetPlatform.iOS: return ios; case TargetPlatform.macOS: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for macos - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); case TargetPlatform.windows: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for windows - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); case TargetPlatform.linux: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for linux - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); default: throw UnsupportedError( 'DefaultFirebaseOptions are not supported for this platform.', ); } } static const FirebaseOptions android = FirebaseOptions( apiKey: 'AIzaSyBbjeMRGPPLsgfOkpDtFkTlWj0mlZVEfGI', appId: '1:825955979349:android:634e018eea5139984884dc', messagingSenderId: '825955979349', projectId: 'tailormade-debug', databaseURL: 'https://tailormade-debug.firebaseio.com', storageBucket: 'tailormade-debug.appspot.com', ); static const FirebaseOptions ios = FirebaseOptions( apiKey: 'AIzaSyDfcLDICnkmOCAx3l9Tg1hD5eBogrmtgX4', appId: '1:825955979349:ios:3f8c0f411c823bd8', messagingSenderId: '825955979349', projectId: 'tailormade-debug', databaseURL: 'https://tailormade-debug.firebaseio.com', storageBucket: 'tailormade-debug.appspot.com', androidClientId: '825955979349-34l4hfqdl1cf2frd7sb65768ej32l04u.apps.googleusercontent.com', iosClientId: '825955979349-llfp7aheo7il83p3ltltncfmi60bsbeg.apps.googleusercontent.com', iosBundleId: 'io.github.jogboms.tailormade.dev', ); }
tailor_made/lib/firebase_options.dev.dart/0
{'file_path': 'tailor_made/lib/firebase_options.dev.dart', 'repo_id': 'tailor_made', 'token_count': 1061}
import 'package:flutter/material.dart'; import 'package:flutter_masked_text2/flutter_masked_text2.dart'; import 'package:tailor_made/presentation/utils.dart'; import 'package:tailor_made/presentation/widgets.dart'; import '../../theme.dart'; class PaymentsCreatePage extends StatefulWidget { const PaymentsCreatePage({ super.key, required this.limit, }); final double limit; @override State<PaymentsCreatePage> createState() => _PaymentsCreatePageState(); } class _PaymentsCreatePageState extends State<PaymentsCreatePage> { final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); bool _autovalidate = false; double _price = 0.0; String _notes = ''; final MoneyMaskedTextController _controller = MoneyMaskedTextController( decimalSeparator: '.', thousandSeparator: ',', ); @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final L10n l10n = context.l10n; return Scaffold( appBar: CustomAppBar( title: Text(l10n.createPaymentPageTitle), ), body: SafeArea( top: false, child: SingleChildScrollView( child: Form( key: _formKey, autovalidateMode: _autovalidate ? AutovalidateMode.always : AutovalidateMode.disabled, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ // TODO(jogboms): fix currency _Header(title: l10n.paymentPageTitle, trailing: l10n.currencyCaption('Naira', '₦')), Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0), child: TextFormField( controller: _controller, textInputAction: TextInputAction.next, keyboardType: const TextInputType.numberWithOptions(decimal: true), decoration: InputDecoration( isDense: true, hintText: l10n.amountPlaceholder, ), validator: (String? value) { if (_controller.numberValue > widget.limit) { return l10n.amountRemainderMessage(AppMoney(widget.limit).formatted); } return (_controller.numberValue > 0) ? null : l10n.inputPriceMessage; }, onSaved: (String? value) => _price = _controller.numberValue, ), ), _Header(title: l10n.additionalNotesLabel), Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0), child: TextFormField( keyboardType: TextInputType.text, maxLines: 6, decoration: InputDecoration( isDense: true, hintText: l10n.additionalNotesPlaceholder, ), onSaved: (String? value) => _notes = value!.trim(), onFieldSubmitted: (String value) => _handleSubmit(l10n), ), ), Padding( padding: const EdgeInsets.fromLTRB(16, 16, 16, 50), child: PrimaryButton( onPressed: () => _handleSubmit(l10n), child: Text(l10n.finishCaption), ), ), const SizedBox(height: 32.0) ], ), ), ), ), ); } void _handleSubmit(L10n l10n) async { final FormState? form = _formKey.currentState; if (form == null) { return; } if (!form.validate()) { _autovalidate = true; AppSnackBar.of(context).info(l10n.fixFormErrors); } else { form.save(); Navigator.pop( context, (price: _price, notes: _notes), ); } } } class _Header extends StatelessWidget { const _Header({ required this.title, this.trailing = '', }); final String title; final String trailing; @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final ColorScheme colorScheme = theme.colorScheme; final TextStyle textStyle = theme.textTheme.bodySmallLight; return Container( color: colorScheme.outlineVariant.withOpacity(.14), margin: const EdgeInsets.only(top: 8.0), padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0), alignment: AlignmentDirectional.centerStart, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text(title.toUpperCase(), style: textStyle), Text(trailing, style: textStyle), ], ), ); } }
tailor_made/lib/presentation/screens/payments/payments_create.dart/0
{'file_path': 'tailor_made/lib/presentation/screens/payments/payments_create.dart', 'repo_id': 'tailor_made', 'token_count': 2366}
# include: package:very_good_analysis/analysis_options.4.0.0.yaml
talk-stream-backend/packages/auth_data_source/analysis_options.yaml/0
{'file_path': 'talk-stream-backend/packages/auth_data_source/analysis_options.yaml', 'repo_id': 'talk-stream-backend', 'token_count': 24}
name: auth_data_source description: My new Dart package version: 0.1.0+1 publish_to: none environment: sdk: ">=2.19.0 <3.0.0" dev_dependencies: build_runner: ^2.3.3 mocktail: ^0.3.0 test: ^1.19.2 very_good_analysis: ^4.0.0 dependencies: collection: ^1.17.1 equatable: ^2.0.5 json_annotation: ^4.8.0 json_serializable: ^6.6.1 meta: ^1.9.0 uuid: ^3.0.7
talk-stream-backend/packages/auth_data_source/pubspec.yaml/0
{'file_path': 'talk-stream-backend/packages/auth_data_source/pubspec.yaml', 'repo_id': 'talk-stream-backend', 'token_count': 182}
name: chat_data_source description: My new Dart package version: 0.1.0+1 publish_to: none environment: sdk: ">=2.19.0 <3.0.0" dev_dependencies: build_runner: ^2.3.3 mocktail: ^0.3.0 test: ^1.19.2 very_good_analysis: ^4.0.0 dependencies: equatable: ^2.0.5 auth_data_source: path: ../auth_data_source json_serializable: ^6.6.1 json_annotation: ^4.8.0 meta: ^1.9.0
talk-stream-backend/packages/chat_data_source/pubspec.yaml/0
{'file_path': 'talk-stream-backend/packages/chat_data_source/pubspec.yaml', 'repo_id': 'talk-stream-backend', 'token_count': 182}
class AppString{ static const String talkStream = 'TalkStream'; static const String signIn = 'Sign In'; static const String talkStreamDescription = 'TalkStream is a versatile chat app' ' that offers a ' 'seamless messaging experience for both personal and ' 'professional use. It was built using Dart Frog and Flutter.'; static const String signUp = 'Sign Up'; static const String createAccount = 'Create an account.'; static const String email = 'Email'; static const String enterEmail = 'Enter your email'; static const String password = 'Password'; static const String enterPassword = 'Enter your password'; static const String username = 'Username'; static const String enterUsername = 'Enter your username'; static const String noAccount = "Don't have an account? "; static const String signUpHere = 'Sign Up here.'; static const String name = 'Name'; static const String enterName = 'Enter your name'; static const String selectPicture = 'Please select a profile image'; }
talk-stream/lib/app/src/constants/string_constant.dart/0
{'file_path': 'talk-stream/lib/app/src/constants/string_constant.dart', 'repo_id': 'talk-stream', 'token_count': 266}
// ignore_for_file: public_member_api_docs, sort_constructors_first part of 'signup_cubit.dart'; @immutable abstract class SignupState {} class SignupInitial extends SignupState {} class SignupLoading extends SignupState {} class SignupLoaded extends SignupState {} class SignupError extends SignupState { final String errorMessage; SignupError({ required this.errorMessage, }); }
talk-stream/lib/auth/cubits/signup_state.dart/0
{'file_path': 'talk-stream/lib/auth/cubits/signup_state.dart', 'repo_id': 'talk-stream', 'token_count': 122}
part of 'chat_details_socket_cubit.dart'; abstract class ChatDetailsSocketState extends Equatable {} class ChatDetailsSocketInitial extends ChatDetailsSocketState { @override List<Object?> get props => []; } class NewMessageReceived extends ChatDetailsSocketState { NewMessageReceived({ required this.message, }); final Message message; @override List<Object?> get props => [message]; }
talk-stream/lib/chat/cubits/chat_details_socket_state.dart/0
{'file_path': 'talk-stream/lib/chat/cubits/chat_details_socket_state.dart', 'repo_id': 'talk-stream', 'token_count': 119}
import 'package:flutter/material.dart'; import 'package:talk_stream/app/view/widgets/margins/x_margin.dart'; import 'package:talk_stream/app/view/widgets/margins/y_margin.dart'; class ChatItemWidget extends StatelessWidget { const ChatItemWidget({ super.key, this.profileImage, this.title, this.description, this.time, this.count, this.onTap, }); final ImageProvider? profileImage; final String? title; final String? description; final String? time; final String? count; final VoidCallback? onTap; @override Widget build(BuildContext context) { return InkWell( onTap: onTap, child: Container( padding: const EdgeInsets.all( 20, ), decoration: BoxDecoration( border: Border.all( color: const Color(0xFFF2F2F2), ), borderRadius: BorderRadius.circular(16), ), child: Row( children: [ CircleAvatar( backgroundColor: Colors.grey, backgroundImage: profileImage, ), const XMargin(10), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( title ?? '', style: const TextStyle( color: Color(0xFF121212), fontWeight: FontWeight.w500, ), ), Text( description ?? '', style: const TextStyle( color: Colors.grey, fontWeight: FontWeight.w400, ), ), ], ), ), Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ if (time != null) Text( time ?? '2:58PM', style: TextStyle( color: const Color(0xFF1F1F1F).withOpacity(0.7), fontWeight: FontWeight.w500, fontSize: 12, ), ), const YMargin(5), if (count != null) const CircleAvatar( backgroundColor: Colors.black, radius: 10, child: Center( child: Text( '2', style: TextStyle( color: Colors.white, fontWeight: FontWeight.w500, fontSize: 12, ), ), ), ), ], ) ], ), ), ); } }
talk-stream/lib/chat/view/widgets/chat_item_widget.dart/0
{'file_path': 'talk-stream/lib/chat/view/widgets/chat_item_widget.dart', 'repo_id': 'talk-stream', 'token_count': 1732}
// ignore_for_file: public_member_api_docs, sort_constructors_first import 'dart:convert'; import 'package:dartz/dartz.dart'; import 'package:mongo_dart/mongo_dart.dart'; import 'package:team_ship_dart_frog/data/models/client_error.dart'; import 'package:team_ship_dart_frog/data/models/location.dart'; import 'package:team_ship_dart_frog/data/models/user.dart'; class SignupParams { final String? fullName; final String? nickName; final String? email; final String? password; final String? avatarUrl; final String? bio; final Location? location; final String? phoneNumber; final String? githubUsername; final String? twitterUsername; final String? createdAt; final String? updatedAt; SignupParams({ required this.fullName, required this.nickName, required this.email, required this.password, this.avatarUrl, this.bio, this.location, this.phoneNumber, required this.githubUsername, this.twitterUsername, this.createdAt, this.updatedAt, }); Map<String, dynamic> toMap() { return <String, dynamic>{ 'fullName': fullName, 'nickName': nickName, 'email': email, 'password': base64Encode(password!.codeUnits), 'avatarUrl': avatarUrl, 'bio': bio, 'location': location?.toMap(), 'phoneNumber': phoneNumber, 'githubUsername': githubUsername, 'twitterUsername': twitterUsername, 'createdAt': createdAt, 'updatedAt': updatedAt, }; } factory SignupParams.fromMap(Map<String, dynamic> map) { return SignupParams( fullName: map['fullName'] != null ? map['fullName'] as String : null, nickName: map['nickName'] != null ? map['nickName'] as String : null, email: map['email'] != null ? map['email'] as String : null, password: map['password'] != null ? map['password'] as String : null, avatarUrl: map['avatarUrl'] != null ? map['avatarUrl'] as String : null, bio: map['bio'] != null ? map['bio'] as String : null, location: map['location'] != null ? Location.fromMap(map['location'] as Map<String, dynamic>) : null, phoneNumber: map['phoneNumber'] != null ? map['phoneNumber'] as String : null, githubUsername: map['githubUsername'] != null ? map['githubUsername'] as String : null, twitterUsername: map['twitterUsername'] != null ? map['twitterUsername'] as String : null, createdAt: map['createdAt'] != null ? map['createdAt'] as String : null, updatedAt: map['updatedAt'] != null ? map['updatedAt'] as String : null, ); } String toJson() => json.encode(toMap()); factory SignupParams.fromJson(String source) => SignupParams.fromMap(json.decode(source) as Map<String, dynamic>); Future<bool> _userExists(DbCollection collection) async { return await collection.findOne(where.eq('email', email)) != null; } Future<Either<ClientError, User>> createUser( DbCollection collection, ) async { final usrExists = await _userExists(collection); if (usrExists) { return left( ClientError( message: 'User already exists', ), ); } final result = await collection.insertOne(toMap()); if (result.hasWriteErrors) { return left( ClientError( message: 'Error creating user', ), ); } else { return right( User.fromMap(result.document ?? {}).copyWith( id: result.id.toString(), ), ); } } /// Either<ClientError, bool> validateForm() { if (fullName == null || fullName!.isEmpty) { return left( ClientError( message: 'Full name is required', ), ); } else if (nickName == null || nickName!.isEmpty) { return left( ClientError( message: 'Nick name is required', ), ); } else if (email == null || email!.isEmpty) { return left( ClientError( message: 'Email is required', ), ); } else if (password == null || password!.isEmpty) { return left( ClientError( message: 'Password is required', ), ); } else if (password!.length < 6) { return left( ClientError( message: 'Password must be at least 6 characters', ), ); } else if (!RegExp(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,}$') .hasMatch(password!) == false) { return left( ClientError( message: 'Password must contain at least one uppercase letter, one ' 'lowercase letter and one number', ), ); } else if (githubUsername == null || githubUsername!.isEmpty) { return left( ClientError( message: 'Github username is required', ), ); } return right(true); } }
teamship-dart-frog/lib/data/params/signup_params.dart/0
{'file_path': 'teamship-dart-frog/lib/data/params/signup_params.dart', 'repo_id': 'teamship-dart-frog', 'token_count': 2022}
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:team_ship_dart_frog/data/models/client_data.dart'; import 'package:team_ship_dart_frog/data/models/user.dart'; import 'package:team_ship_dart_frog/middlewares/bearer_auth_middleware.dart'; import 'package:team_ship_dart_frog/server/db_connection.dart'; Future<Response> onRequest(RequestContext context) async { final method = context.request.method; final user = context.read<User>(); final token = context.read<Token>(); final db = await connection.db; final collection = db.collection('projects'); if (method != HttpMethod.get) { return Response( statusCode: HttpStatus.methodNotAllowed, body: 'Method not allowed', ); } final projects = await collection .find( // where.eq('creator', user.toMap()), ) .toList(); return Response( body: ClientData( message: 'Projects found', data: { 'projects': projects, 'count': projects.length, }, token: token, ).toJson(), ); }
teamship-dart-frog/routes/api/v1/project/get_all.dart/0
{'file_path': 'teamship-dart-frog/routes/api/v1/project/get_all.dart', 'repo_id': 'teamship-dart-frog', 'token_count': 412}
// Copyright (c) 2022, 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. @TestOn('vm') import 'package:test/test.dart'; void main() { group('spawnHybridUri():', () { test('loads uris relative to the test file', () async { expect( spawnHybridUri(Uri.parse('../util/emits_numbers.dart')) .stream .toList(), completion(equals([1, 2, 3]))); }); }); }
test/integration_tests/spawn_hybrid/test/subdir/hybrid_test.dart/0
{'file_path': 'test/integration_tests/spawn_hybrid/test/subdir/hybrid_test.dart', 'repo_id': 'test', 'token_count': 221}
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:checks/context.dart'; extension NumChecks on Check<num> { void operator >(num other) { context.expect(() => ['is greater than ${literal(other)}'], (actual) { if (actual > other) return null; return Rejection( actual: literal(actual), which: ['Is not greater than ${literal(other)}']); }); } void operator <(num other) { context.expect(() => ['is less than ${literal(other)}'], (actual) { if (actual < other) return null; return Rejection( actual: literal(actual), which: ['Is not less than ${literal(other)}']); }); } }
test/pkgs/checks/lib/src/extensions/math.dart/0
{'file_path': 'test/pkgs/checks/lib/src/extensions/math.dart', 'repo_id': 'test', 'token_count': 305}
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:test_api/src/backend/runtime.dart'; // ignore: implementation_imports // ignore: implementation_imports import 'package:test_core/src/executable.dart' as executable; import 'package:test_core/src/runner/hack_register_platform.dart'; // ignore: implementation_imports import 'runner/browser/platform.dart'; import 'runner/node/platform.dart'; void main(List<String> args) async { registerPlatformPlugin([Runtime.nodeJS], () => NodePlatform()); registerPlatformPlugin([ Runtime.chrome, Runtime.firefox, Runtime.safari, Runtime.internetExplorer ], () => BrowserPlatform.start()); await executable.main(args); }
test/pkgs/test/lib/src/executable.dart/0
{'file_path': 'test/pkgs/test/lib/src/executable.dart', 'repo_id': 'test', 'token_count': 255}
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:io'; import 'package:io/io.dart'; import 'package:path/path.dart' as p; import 'package:source_span/source_span.dart'; import 'package:yaml/yaml.dart'; /// User-provided settings for invoking an executable. class ExecutableSettings { /// Additional arguments to pass to the executable. final List<String> arguments; /// The path to the executable on Linux. /// /// This may be an absolute path or a basename, in which case it will be /// looked up on the system path. It may not be relative. final String? _linuxExecutable; /// The path to the executable on Mac OS. /// /// This may be an absolute path or a basename, in which case it will be /// looked up on the system path. It may not be relative. final String? _macOSExecutable; /// The path to the executable on Windows. /// /// This may be an absolute path; a basename, in which case it will be looked /// up on the system path; or a relative path, in which case it will be looked /// up relative to the paths in the `LOCALAPPDATA`, `PROGRAMFILES`, and /// `PROGRAMFILES(X64)` environment variables. final String? _windowsExecutable; /// The path to the executable for the current operating system. String get executable { if (Platform.isMacOS) return _macOSExecutable!; if (!Platform.isWindows) return _linuxExecutable!; final windowsExecutable = _windowsExecutable!; if (p.isAbsolute(windowsExecutable)) return windowsExecutable; if (p.basename(windowsExecutable) == windowsExecutable) { return windowsExecutable; } var prefixes = [ Platform.environment['LOCALAPPDATA'], Platform.environment['PROGRAMFILES'], Platform.environment['PROGRAMFILES(X86)'] ]; for (var prefix in prefixes) { if (prefix == null) continue; var path = p.join(prefix, windowsExecutable); if (File(path).existsSync()) return path; } // If we can't find a path that works, return one that doesn't. This will // cause an "executable not found" error to surface. return p.join( prefixes.firstWhere((prefix) => prefix != null, orElse: () => '.')!, _windowsExecutable); } /// Whether to invoke the browser in headless mode. /// /// This is currently only supported by Chrome. bool get headless => _headless ?? true; final bool? _headless; /// Parses settings from a user-provided YAML mapping. factory ExecutableSettings.parse(YamlMap settings) { List<String>? arguments; var argumentsNode = settings.nodes['arguments']; if (argumentsNode != null) { var value = argumentsNode.value; if (value is String) { try { arguments = shellSplit(value); } on FormatException catch (error) { throw SourceSpanFormatException(error.message, argumentsNode.span); } } else { throw SourceSpanFormatException( 'Must be a string.', argumentsNode.span); } } String? linuxExecutable; String? macOSExecutable; String? windowsExecutable; var executableNode = settings.nodes['executable']; if (executableNode != null) { var value = executableNode.value; if (value is String) { // Don't check this on Windows because people may want to set relative // paths in their global config. if (!Platform.isWindows) { _assertNotRelative(executableNode as YamlScalar); } linuxExecutable = value; macOSExecutable = value; windowsExecutable = value; } else if (executableNode is YamlMap) { linuxExecutable = _getExecutable(executableNode.nodes['linux']); macOSExecutable = _getExecutable(executableNode.nodes['mac_os']); windowsExecutable = _getExecutable(executableNode.nodes['windows'], allowRelative: true); } else { throw SourceSpanFormatException( 'Must be a map or a string.', executableNode.span); } } var headless = true; var headlessNode = settings.nodes['headless']; if (headlessNode != null) { var value = headlessNode.value; if (value is bool) { headless = value; } else { throw SourceSpanFormatException( 'Must be a boolean.', headlessNode.span); } } return ExecutableSettings( arguments: arguments, linuxExecutable: linuxExecutable, macOSExecutable: macOSExecutable, windowsExecutable: windowsExecutable, headless: headless); } /// Asserts that [executableNode] is a string or `null` and returns it. /// /// If [allowRelative] is `false` (the default), asserts that the value isn't /// a relative path. static String? _getExecutable(YamlNode? executableNode, {bool allowRelative = false}) { if (executableNode == null || executableNode.value == null) return null; if (executableNode.value is! String) { throw SourceSpanFormatException('Must be a string.', executableNode.span); } if (!allowRelative) _assertNotRelative(executableNode as YamlScalar); return executableNode.value as String; } /// Throws a [SourceSpanFormatException] if [executableNode]'s value is a /// relative POSIX path that's not just a plain basename. /// /// We loop up basenames on the PATH and we can resolve absolute paths, but we /// have no way of interpreting relative paths. static void _assertNotRelative(YamlScalar executableNode) { var executable = executableNode.value as String; if (!p.posix.isRelative(executable)) return; if (p.posix.basename(executable) == executable) return; throw SourceSpanFormatException( 'Linux and Mac OS executables may not be relative paths.', executableNode.span); } ExecutableSettings( {Iterable<String>? arguments, String? linuxExecutable, String? macOSExecutable, String? windowsExecutable, bool? headless}) : arguments = arguments == null ? const [] : List.unmodifiable(arguments), _linuxExecutable = linuxExecutable, _macOSExecutable = macOSExecutable, _windowsExecutable = windowsExecutable, _headless = headless; /// Merges [this] with [other], with [other]'s settings taking priority. ExecutableSettings merge(ExecutableSettings other) => ExecutableSettings( arguments: arguments.toList()..addAll(other.arguments), headless: other._headless ?? _headless, linuxExecutable: other._linuxExecutable ?? _linuxExecutable, macOSExecutable: other._macOSExecutable ?? _macOSExecutable, windowsExecutable: other._windowsExecutable ?? _windowsExecutable); }
test/pkgs/test/lib/src/runner/executable_settings.dart/0
{'file_path': 'test/pkgs/test/lib/src/runner/executable_settings.dart', 'repo_id': 'test', 'token_count': 2369}
// Copyright (c) 2015, 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. @TestOn('firefox') import 'package:test/src/runner/browser/dom.dart' as dom; import 'package:test/test.dart'; void main() { // Regression test for #274. Firefox doesn't compute styles within hidden // iframes (https://bugzilla.mozilla.org/show_bug.cgi?id=548397), so we have // to do some special stuff to make sure tests that care about that work. test('getComputedStyle() works', () { expect(dom.window.getComputedStyle(dom.document.body!), isNotNull); }); }
test/pkgs/test/test/runner/browser/firefox_html_test.dart/0
{'file_path': 'test/pkgs/test/test/runner/browser/firefox_html_test.dart', 'repo_id': 'test', 'token_count': 213}
// Copyright (c) 2016, 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. @TestOn('vm') import 'dart:convert'; import 'package:test/test.dart'; import 'package:test_core/src/util/exit_codes.dart' as exit_codes; import 'package:test_descriptor/test_descriptor.dart' as d; import '../../io.dart'; void main() { setUpAll(precompileTestExecutable); test('adds the specified tags', () async { await d .file( 'dart_test.yaml', jsonEncode({ 'add_tags': ['foo', 'bar'] })) .create(); await d.file('test.dart', ''' import 'package:test/test.dart'; void main() { test("test", () {}); } ''').create(); var test = await runTest(['--exclude-tag', 'foo', 'test.dart']); expect(test.stdout, emitsThrough(contains('No tests ran.'))); await test.shouldExit(79); test = await runTest(['--exclude-tag', 'bar', 'test.dart']); expect(test.stdout, emitsThrough(contains('No tests ran.'))); await test.shouldExit(79); test = await runTest(['test.dart']); expect(test.stdout, emitsThrough(contains('+1: All tests passed!'))); await test.shouldExit(0); }); group('tags', () { test("doesn't warn for tags that exist in the configuration", () async { await d .file( 'dart_test.yaml', jsonEncode({ 'tags': {'foo': null} })) .create(); await d.file('test.dart', ''' import 'package:test/test.dart'; void main() { test("test", () {}); } ''').create(); var test = await runTest(['test.dart']); expect(test.stdout, neverEmits(contains('Warning: Tags were used'))); await test.shouldExit(0); }); test('applies tag-specific configuration only to matching tests', () async { await d .file( 'dart_test.yaml', jsonEncode({ 'tags': { 'foo': {'timeout': '0s'} } })) .create(); await d.file('test.dart', ''' import 'dart:async'; import 'package:test/test.dart'; void main() { test("test 1", () => Future.delayed(Duration.zero), tags: ['foo']); test("test 2", () => Future.delayed(Duration.zero)); } ''').create(); var test = await runTest(['test.dart']); expect(test.stdout, containsInOrder(['-1: test 1 [E]', '+1 -1: Some tests failed.'])); await test.shouldExit(1); }); test('supports tag selectors', () async { await d .file( 'dart_test.yaml', jsonEncode({ 'tags': { 'foo && bar': {'timeout': '0s'} } })) .create(); await d.file('test.dart', ''' import 'dart:async'; import 'package:test/test.dart'; void main() { test("test 1", () => Future.delayed(Duration.zero), tags: ['foo']); test("test 2", () => Future.delayed(Duration.zero), tags: ['bar']); test("test 3", () => Future.delayed(Duration.zero), tags: ['foo', 'bar']); } ''').create(); var test = await runTest(['test.dart']); expect(test.stdout, containsInOrder(['+2 -1: test 3 [E]', '+2 -1: Some tests failed.'])); await test.shouldExit(1); }); test('allows tag inheritance via add_tags', () async { await d .file( 'dart_test.yaml', jsonEncode({ 'tags': { 'foo': null, 'bar': { 'add_tags': ['foo'] } } })) .create(); await d.file('test.dart', ''' import 'package:test/test.dart'; void main() { test("test 1", () {}, tags: ['bar']); test("test 2", () {}); } ''').create(); var test = await runTest(['test.dart', '--tags', 'foo']); expect(test.stdout, emitsThrough(contains('+1: All tests passed!'))); await test.shouldExit(0); }); // Regression test for #503. test('skips tests whose tags are marked as skip', () async { await d .file( 'dart_test.yaml', jsonEncode({ 'tags': { 'foo': {'skip': 'some reason'} } })) .create(); await d.file('test.dart', ''' import 'dart:async'; import 'package:test/test.dart'; void main() { test("test 1", () => throw 'bad', tags: ['foo']); } ''').create(); var test = await runTest(['test.dart']); expect( test.stdout, containsInOrder(['some reason', 'All tests skipped.'])); await test.shouldExit(0); }); }); group('include_tags and exclude_tags', () { test('only runs tests with the included tags', () async { await d .file('dart_test.yaml', jsonEncode({'include_tags': 'foo && bar'})) .create(); await d.file('test.dart', ''' import 'package:test/test.dart'; void main() { test("zip", () {}, tags: "foo"); test("zap", () {}, tags: "bar"); test("zop", () {}, tags: ["foo", "bar"]); } ''').create(); var test = await runTest(['test.dart']); expect( test.stdout, containsInOrder(['+0: zop', '+1: All tests passed!'])); await test.shouldExit(0); }); test("doesn't run tests with the excluded tags", () async { await d .file('dart_test.yaml', jsonEncode({'exclude_tags': 'foo && bar'})) .create(); await d.file('test.dart', ''' import 'package:test/test.dart'; void main() { test("zip", () {}, tags: "foo"); test("zap", () {}, tags: "bar"); test("zop", () {}, tags: ["foo", "bar"]); } ''').create(); var test = await runTest(['test.dart']); expect(test.stdout, containsInOrder(['+0: zip', '+1: zap', '+2: All tests passed!'])); await test.shouldExit(0); }); }); group('errors', () { group('tags', () { test('rejects an invalid tag type', () async { await d.file('dart_test.yaml', '{"tags": {12: null}}').create(); var test = await runTest([]); expect( test.stderr, containsInOrder(['tags key must be a string', '^^'])); await test.shouldExit(exit_codes.data); }); test('rejects an invalid tag selector', () async { await d .file( 'dart_test.yaml', jsonEncode({ 'tags': {'foo bar': null} })) .create(); var test = await runTest([]); expect( test.stderr, containsInOrder( ['Invalid tags key: Expected end of input.', '^^^^^^^^^'])); await test.shouldExit(exit_codes.data); }); test('rejects an invalid tag map', () async { await d.file('dart_test.yaml', jsonEncode({'tags': 12})).create(); var test = await runTest([]); expect(test.stderr, containsInOrder(['tags must be a map', '^^'])); await test.shouldExit(exit_codes.data); }); test('rejects an invalid tag configuration', () async { await d .file( 'dart_test.yaml', jsonEncode({ 'tags': { 'foo': {'timeout': '12p'} } })) .create(); var test = await runTest([]); expect(test.stderr, containsInOrder(['Invalid timeout: expected unit', '^^^^'])); await test.shouldExit(exit_codes.data); }); test('rejects runner configuration', () async { await d .file( 'dart_test.yaml', jsonEncode({ 'tags': { 'foo': {'filename': '*_blorp.dart'} } })) .create(); var test = await runTest([]); expect(test.stderr, containsInOrder(["filename isn't supported here.", '^^^^^^^^^^'])); await test.shouldExit(exit_codes.data); }); }); group('add_tags', () { test('rejects an invalid list type', () async { await d .file('dart_test.yaml', jsonEncode({'add_tags': 'foo'})) .create(); var test = await runTest(['test.dart']); expect( test.stderr, containsInOrder(['add_tags must be a list', '^^^^'])); await test.shouldExit(exit_codes.data); }); test('rejects an invalid tag type', () async { await d .file( 'dart_test.yaml', jsonEncode({ 'add_tags': [12] })) .create(); var test = await runTest(['test.dart']); expect( test.stderr, containsInOrder(['Tag name must be a string', '^^'])); await test.shouldExit(exit_codes.data); }); test('rejects an invalid tag name', () async { await d .file( 'dart_test.yaml', jsonEncode({ 'add_tags': ['foo bar'] })) .create(); var test = await runTest(['test.dart']); expect( test.stderr, containsInOrder([ 'Tag name must be an (optionally hyphenated) Dart identifier.', '^^^^^^^^^' ])); await test.shouldExit(exit_codes.data); }); }); group('include_tags', () { test('rejects an invalid type', () async { await d .file('dart_test.yaml', jsonEncode({'include_tags': 12})) .create(); var test = await runTest(['test.dart']); expect(test.stderr, containsInOrder(['include_tags must be a string', '^^'])); await test.shouldExit(exit_codes.data); }); test('rejects an invalid selector', () async { await d .file('dart_test.yaml', jsonEncode({'include_tags': 'foo bar'})) .create(); var test = await runTest([]); expect( test.stderr, containsInOrder( ['Invalid include_tags: Expected end of input.', '^^^^^^^^^'])); await test.shouldExit(exit_codes.data); }); }); group('exclude_tags', () { test('rejects an invalid type', () async { await d .file('dart_test.yaml', jsonEncode({'exclude_tags': 12})) .create(); var test = await runTest(['test.dart']); expect(test.stderr, containsInOrder(['exclude_tags must be a string', '^^'])); await test.shouldExit(exit_codes.data); }); test('rejects an invalid selector', () async { await d .file('dart_test.yaml', jsonEncode({'exclude_tags': 'foo bar'})) .create(); var test = await runTest([]); expect( test.stderr, containsInOrder( ['Invalid exclude_tags: Expected end of input.', '^^^^^^^^^'])); await test.shouldExit(exit_codes.data); }); }); }); }
test/pkgs/test/test/runner/configuration/tags_test.dart/0
{'file_path': 'test/pkgs/test/test/runner/configuration/tags_test.dart', 'repo_id': 'test', 'token_count': 5809}
// Copyright (c) 2015, 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. @TestOn('vm') import 'package:test/test.dart'; import 'package:test_api/src/backend/platform_selector.dart'; import 'package:test_api/src/backend/runtime.dart'; import 'package:test_api/src/backend/suite_platform.dart'; import 'package:test_core/src/runner/parse_metadata.dart'; final _path = 'test.dart'; void main() { test('returns empty metadata for an empty file', () { var metadata = parseMetadata(_path, '', {}); expect(metadata.testOn, equals(PlatformSelector.all)); expect(metadata.timeout.scaleFactor, equals(1)); }); test('ignores irrelevant annotations', () { var metadata = parseMetadata(_path, '@Fblthp\n@Fblthp.foo\nlibrary foo;', {}); expect(metadata.testOn, equals(PlatformSelector.all)); }); test('parses a prefixed annotation', () { var metadata = parseMetadata( _path, "@foo.TestOn('vm')\n" "import 'package:test/test.dart' as foo;", {}); expect(metadata.testOn.evaluate(SuitePlatform(Runtime.vm)), isTrue); expect(metadata.testOn.evaluate(SuitePlatform(Runtime.chrome)), isFalse); }); group('@TestOn:', () { test('parses a valid annotation', () { var metadata = parseMetadata(_path, "@TestOn('vm')\nlibrary foo;", {}); expect(metadata.testOn.evaluate(SuitePlatform(Runtime.vm)), isTrue); expect(metadata.testOn.evaluate(SuitePlatform(Runtime.chrome)), isFalse); }); test('ignores a constructor named TestOn', () { var metadata = parseMetadata(_path, "@foo.TestOn('foo')\nlibrary foo;", {}); expect(metadata.testOn, equals(PlatformSelector.all)); }); group('throws an error for', () { test('multiple @TestOns', () { expect( () => parseMetadata( _path, "@TestOn('foo')\n@TestOn('bar')\nlibrary foo;", {}), throwsFormatException); }); }); }); group('@Timeout:', () { test('parses a valid duration annotation', () { var metadata = parseMetadata(_path, ''' @Timeout(const Duration( hours: 1, minutes: 2, seconds: 3, milliseconds: 4, microseconds: 5)) library foo; ''', {}); expect( metadata.timeout.duration, equals(Duration( hours: 1, minutes: 2, seconds: 3, milliseconds: 4, microseconds: 5))); }); test('parses a valid duration omitting const', () { var metadata = parseMetadata(_path, ''' @Timeout(Duration( hours: 1, minutes: 2, seconds: 3, milliseconds: 4, microseconds: 5)) library foo; ''', {}); expect( metadata.timeout.duration, equals(Duration( hours: 1, minutes: 2, seconds: 3, milliseconds: 4, microseconds: 5))); }); test('parses a valid duration with an import prefix', () { var metadata = parseMetadata(_path, ''' @Timeout(core.Duration( hours: 1, minutes: 2, seconds: 3, milliseconds: 4, microseconds: 5)) import 'dart:core' as core; ''', {}); expect( metadata.timeout.duration, equals(Duration( hours: 1, minutes: 2, seconds: 3, milliseconds: 4, microseconds: 5))); }); test('parses a valid int factor annotation', () { var metadata = parseMetadata(_path, ''' @Timeout.factor(1) library foo; ''', {}); expect(metadata.timeout.scaleFactor, equals(1)); }); test('parses a valid int factor annotation with an import prefix', () { var metadata = parseMetadata(_path, ''' @test.Timeout.factor(1) import 'package:test/test.dart' as test; ''', {}); expect(metadata.timeout.scaleFactor, equals(1)); }); test('parses a valid double factor annotation', () { var metadata = parseMetadata(_path, ''' @Timeout.factor(0.5) library foo; ''', {}); expect(metadata.timeout.scaleFactor, equals(0.5)); }); test('parses a valid Timeout.none annotation', () { var metadata = parseMetadata(_path, ''' @Timeout.none library foo; ''', {}); expect(metadata.timeout, same(Timeout.none)); }); test('ignores a constructor named Timeout', () { var metadata = parseMetadata(_path, "@foo.Timeout('foo')\nlibrary foo;", {}); expect(metadata.timeout.scaleFactor, equals(1)); }); group('throws an error for', () { test('multiple @Timeouts', () { expect( () => parseMetadata(_path, '@Timeout.factor(1)\n@Timeout.factor(2)\nlibrary foo;', {}), throwsFormatException); }); }); }); group('@Skip:', () { test('parses a valid annotation', () { var metadata = parseMetadata(_path, '@Skip()\nlibrary foo;', {}); expect(metadata.skip, isTrue); expect(metadata.skipReason, isNull); }); test('parses a valid annotation with a reason', () { var metadata = parseMetadata(_path, "@Skip('reason')\nlibrary foo;", {}); expect(metadata.skip, isTrue); expect(metadata.skipReason, equals('reason')); }); test('ignores a constructor named Skip', () { var metadata = parseMetadata(_path, "@foo.Skip('foo')\nlibrary foo;", {}); expect(metadata.skip, isFalse); }); group('throws an error for', () { test('multiple @Skips', () { expect( () => parseMetadata( _path, "@Skip('foo')\n@Skip('bar')\nlibrary foo;", {}), throwsFormatException); }); }); }); group('@Tags:', () { test('parses a valid annotation', () { var metadata = parseMetadata(_path, "@Tags(['a'])\nlibrary foo;", {}); expect(metadata.tags, equals(['a'])); }); test('ignores a constructor named Tags', () { var metadata = parseMetadata(_path, "@foo.Tags(['a'])\nlibrary foo;", {}); expect(metadata.tags, isEmpty); }); group('throws an error for', () { test('multiple @Tags', () { expect( () => parseMetadata( _path, "@Tags(['a'])\n@Tags(['b'])\nlibrary foo;", {}), throwsFormatException); }); test('String interpolation', () { expect( () => parseMetadata( _path, "@Tags(['\$a'])\nlibrary foo;\nconst a = 'a';", {}), throwsFormatException); }); }); }); group('@OnPlatform:', () { test('parses a valid annotation', () { var metadata = parseMetadata(_path, ''' @OnPlatform({ 'chrome': Timeout.factor(2), 'vm': [Skip(), Timeout.factor(3)] }) library foo;''', {}); var key = metadata.onPlatform.keys.first; expect(key.evaluate(SuitePlatform(Runtime.chrome)), isTrue); expect(key.evaluate(SuitePlatform(Runtime.vm)), isFalse); var value = metadata.onPlatform.values.first; expect(value.timeout.scaleFactor, equals(2)); key = metadata.onPlatform.keys.last; expect(key.evaluate(SuitePlatform(Runtime.vm)), isTrue); expect(key.evaluate(SuitePlatform(Runtime.chrome)), isFalse); value = metadata.onPlatform.values.last; expect(value.skip, isTrue); expect(value.timeout.scaleFactor, equals(3)); }); test('parses a valid annotation with an import prefix', () { var metadata = parseMetadata(_path, ''' @test.OnPlatform({ 'chrome': test.Timeout.factor(2), 'vm': [test.Skip(), test.Timeout.factor(3)] }) import 'package:test/test.dart' as test; ''', {}); var key = metadata.onPlatform.keys.first; expect(key.evaluate(SuitePlatform(Runtime.chrome)), isTrue); expect(key.evaluate(SuitePlatform(Runtime.vm)), isFalse); var value = metadata.onPlatform.values.first; expect(value.timeout.scaleFactor, equals(2)); key = metadata.onPlatform.keys.last; expect(key.evaluate(SuitePlatform(Runtime.vm)), isTrue); expect(key.evaluate(SuitePlatform(Runtime.chrome)), isFalse); value = metadata.onPlatform.values.last; expect(value.skip, isTrue); expect(value.timeout.scaleFactor, equals(3)); }); test('ignores a constructor named OnPlatform', () { var metadata = parseMetadata(_path, "@foo.OnPlatform('foo')\nlibrary foo;", {}); expect(metadata.testOn, equals(PlatformSelector.all)); }); group('throws an error for', () { test('a map with a unparseable key', () { expect( () => parseMetadata( _path, "@OnPlatform({'invalid': Skip()})\nlibrary foo;", {}), throwsFormatException); }); test('a map with an invalid value', () { expect( () => parseMetadata(_path, "@OnPlatform({'vm': const TestOn('vm')})\nlibrary foo;", {}), throwsFormatException); }); test('a map with an invalid value in a list', () { expect( () => parseMetadata(_path, "@OnPlatform({'vm': [const TestOn('vm')]})\nlibrary foo;", {}), throwsFormatException); }); test('multiple @OnPlatforms', () { expect( () => parseMetadata( _path, '@OnPlatform({})\n@OnPlatform({})\nlibrary foo;', {}), throwsFormatException); }); }); }); }
test/pkgs/test/test/runner/parse_metadata_test.dart/0
{'file_path': 'test/pkgs/test/test/runner/parse_metadata_test.dart', 'repo_id': 'test', 'token_count': 3931}
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:shelf/shelf.dart' as shelf; import 'package:test/src/util/one_off_handler.dart'; import 'package:test/test.dart'; void main() { late OneOffHandler handler; setUp(() => handler = OneOffHandler()); Future<shelf.Response> handle(shelf.Request request) => Future.sync(() => handler.handler(request)); test('returns a 404 for a root URL', () async { var request = shelf.Request('GET', Uri.parse('http://localhost/')); expect((await handle(request)).statusCode, equals(404)); }); test('returns a 404 for an unhandled URL', () async { var request = shelf.Request('GET', Uri.parse('http://localhost/1')); expect((await handle(request)).statusCode, equals(404)); }); test('passes a request to a handler only once', () async { var path = handler.create(expectAsync1((request) { expect(request.method, equals('GET')); return shelf.Response.ok('good job!'); })); var request = shelf.Request('GET', Uri.parse('http://localhost/$path')); var response = await handle(request); expect(response.statusCode, equals(200)); expect(response.readAsString(), completion(equals('good job!'))); request = shelf.Request('GET', Uri.parse('http://localhost/$path')); expect((await handle(request)).statusCode, equals(404)); }); test('passes requests to the correct handlers', () async { var path1 = handler.create(expectAsync1((request) { expect(request.method, equals('GET')); return shelf.Response.ok('one'); })); var path2 = handler.create(expectAsync1((request) { expect(request.method, equals('GET')); return shelf.Response.ok('two'); })); var path3 = handler.create(expectAsync1((request) { expect(request.method, equals('GET')); return shelf.Response.ok('three'); })); var request = shelf.Request('GET', Uri.parse('http://localhost/$path2')); var response = await handle(request); expect(response.statusCode, equals(200)); expect(response.readAsString(), completion(equals('two'))); request = shelf.Request('GET', Uri.parse('http://localhost/$path1')); response = await handle(request); expect(response.statusCode, equals(200)); expect(response.readAsString(), completion(equals('one'))); request = shelf.Request('GET', Uri.parse('http://localhost/$path3')); response = await handle(request); expect(response.statusCode, equals(200)); expect(response.readAsString(), completion(equals('three'))); }); }
test/pkgs/test/test/util/one_off_handler_test.dart/0
{'file_path': 'test/pkgs/test/test/util/one_off_handler_test.dart', 'repo_id': 'test', 'token_count': 905}
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:stack_trace/stack_trace.dart'; import 'test_failure.dart'; /// An exception that was thrown remotely. /// /// This could be an exception thrown in a different isolate, a different /// process, or on an entirely different computer. class RemoteException implements Exception { /// The original exception's message, if it had one. /// /// If the original exception was a plain string, this will contain that /// string. final String? message; /// The value of the original exception's `runtimeType.toString()`. final String type; /// The value of the original exception's `toString()`. final String _toString; /// Serializes [error] and [stackTrace] into a JSON-safe object. /// /// Other than JSON- and isolate-safety, no guarantees are made about the /// serialized format. static Map<String, dynamic> serialize(error, StackTrace stackTrace) { String? message; if (error is String) { message = error; } else { try { message = error.message.toString(); } on NoSuchMethodError catch (_) { // Do nothing. } } final supertype = (error is TestFailure) ? 'TestFailure' : null; return { 'message': message, 'type': error.runtimeType.toString(), 'supertype': supertype, 'toString': error.toString(), 'stackChain': Chain.forTrace(stackTrace).toString() }; } /// Deserializes an exception serialized with [RemoteException.serialize]. /// /// The returned [AsyncError] is guaranteed to have a [RemoteException] as its /// error and a [Chain] as its stack trace. static AsyncError deserialize(serialized) { return AsyncError(_deserializeException(serialized), Chain.parse(serialized['stackChain'] as String)); } /// Deserializes the exception portion of [serialized]. static RemoteException _deserializeException(serialized) { final message = serialized['message'] as String?; final type = serialized['type'] as String; final toString = serialized['toString'] as String; switch (serialized['supertype'] as String?) { case 'TestFailure': return _RemoteTestFailure(message, type, toString); default: return RemoteException._(message, type, toString); } } RemoteException._(this.message, this.type, this._toString); @override String toString() => _toString; } /// A subclass of [RemoteException] that implements [TestFailure]. /// /// It's important to preserve [TestFailure]-ness, because tests have different /// results depending on whether an exception was a failure or an error. class _RemoteTestFailure extends RemoteException implements TestFailure { _RemoteTestFailure(String? message, String type, String toString) : super._(message, type, toString); }
test/pkgs/test_api/lib/src/backend/remote_exception.dart/0
{'file_path': 'test/pkgs/test_api/lib/src/backend/remote_exception.dart', 'repo_id': 'test', 'token_count': 926}
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:matcher/matcher.dart'; import 'package:test_api/hooks.dart' show pumpEventQueue; import 'async_matcher.dart'; import 'expect.dart'; import 'util/pretty_print.dart'; /// Matches a [Future] that completes successfully with any value. /// /// This creates an asynchronous expectation. The call to [expect] will return /// immediately and execution will continue. Later, when the future completes, /// the expectation against [matcher] will run. To wait for the future to /// complete and the expectation to run use [expectLater] and wait on the /// returned future. /// /// To test that a Future completes with an exception, you can use [throws] and /// [throwsA]. final Matcher completes = const _Completes(null); /// Matches a [Future] that completes successfully with a value that matches /// [matcher]. /// /// This creates an asynchronous expectation. The call to [expect] will return /// immediately and execution will continue. Later, when the future completes, /// the expectation against [matcher] will run. To wait for the future to /// complete and the expectation to run use [expectLater] and wait on the /// returned future. /// /// To test that a Future completes with an exception, you can use [throws] and /// [throwsA]. Matcher completion(matcher, [@Deprecated('this parameter is ignored') String? description]) => _Completes(wrapMatcher(matcher)); class _Completes extends AsyncMatcher { final Matcher? _matcher; const _Completes(this._matcher); // Avoid async/await so we synchronously start listening to [item]. @override dynamic /*FutureOr<String>*/ matchAsync(item) { if (item is! Future) return 'was not a Future'; return item.then((value) async { if (_matcher == null) return null; String? result; if (_matcher is AsyncMatcher) { result = await (_matcher as AsyncMatcher).matchAsync(value) as String?; if (result == null) return null; } else { var matchState = {}; if (_matcher!.matches(value, matchState)) return null; result = _matcher! .describeMismatch(value, StringDescription(), matchState, false) .toString(); } var buffer = StringBuffer(); buffer.writeln(indent(prettyPrint(value), first: 'emitted ')); if (result.isNotEmpty) buffer.writeln(indent(result, first: ' which ')); return buffer.toString().trimRight(); }); } @override Description describe(Description description) { if (_matcher == null) { description.add('completes successfully'); } else { description.add('completes to a value that ').addDescriptionOf(_matcher); } return description; } } /// Matches a [Future] that does not complete. /// /// Note that this creates an asynchronous expectation. The call to /// `expect()` that includes this will return immediately and execution will /// continue. final Matcher doesNotComplete = const _DoesNotComplete(); class _DoesNotComplete extends Matcher { const _DoesNotComplete(); @override Description describe(Description description) { description.add('does not complete'); return description; } @override bool matches(item, Map matchState) { if (item is! Future) return false; item.then((value) { fail('Future was not expected to complete but completed with a value of ' '$value'); }); expect(pumpEventQueue(), completes); return true; } @override Description describeMismatch( item, Description description, Map matchState, bool verbose) { if (item is! Future) return description.add('$item is not a Future'); return description; } }
test/pkgs/test_api/lib/src/expect/future_matchers.dart/0
{'file_path': 'test/pkgs/test_api/lib/src/expect/future_matchers.dart', 'repo_id': 'test', 'token_count': 1215}
// Copyright (c) 2013, 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. /// Throws an [ArgumentError] if [message] isn't recursively JSON-safe. void ensureJsonEncodable(Object? message) { if (message == null || message is String || message is num || message is bool) { // JSON-encodable, hooray! } else if (message is List) { for (var element in message) { ensureJsonEncodable(element); } } else if (message is Map) { message.forEach((key, value) { if (key is! String) { throw ArgumentError("$message can't be JSON-encoded."); } ensureJsonEncodable(value); }); } else { throw ArgumentError.value("$message can't be JSON-encoded."); } }
test/pkgs/test_api/lib/src/utils.dart/0
{'file_path': 'test/pkgs/test_api/lib/src/utils.dart', 'repo_id': 'test', 'token_count': 310}
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:async/async.dart'; import 'package:test/test.dart'; import '../utils.dart'; void main() { test('runs once before all tests', () { return expectTestsPass(() { var setUpAllRun = false; setUpAll(() { expect(setUpAllRun, isFalse); setUpAllRun = true; }); test('test 1', () { expect(setUpAllRun, isTrue); }); test('test 2', () { expect(setUpAllRun, isTrue); }); }); }); test('runs once per group, outside-in', () { return expectTestsPass(() { var setUpAll1Run = false; var setUpAll2Run = false; var setUpAll3Run = false; setUpAll(() { expect(setUpAll1Run, isFalse); expect(setUpAll2Run, isFalse); expect(setUpAll3Run, isFalse); setUpAll1Run = true; }); group('mid', () { setUpAll(() { expect(setUpAll1Run, isTrue); expect(setUpAll2Run, isFalse); expect(setUpAll3Run, isFalse); setUpAll2Run = true; }); group('inner', () { setUpAll(() { expect(setUpAll1Run, isTrue); expect(setUpAll2Run, isTrue); expect(setUpAll3Run, isFalse); setUpAll3Run = true; }); test('test', () { expect(setUpAll1Run, isTrue); expect(setUpAll2Run, isTrue); expect(setUpAll3Run, isTrue); }); }); }); }); }); test('runs before setUps', () { return expectTestsPass(() { var setUpAllRun = false; setUp(() { expect(setUpAllRun, isTrue); }); setUpAll(() { expect(setUpAllRun, isFalse); setUpAllRun = true; }); setUp(() { expect(setUpAllRun, isTrue); }); test('test', () { expect(setUpAllRun, isTrue); }); }); }); test('multiples run in order', () { return expectTestsPass(() { var setUpAll1Run = false; var setUpAll2Run = false; var setUpAll3Run = false; setUpAll(() { expect(setUpAll1Run, isFalse); expect(setUpAll2Run, isFalse); expect(setUpAll3Run, isFalse); setUpAll1Run = true; }); setUpAll(() { expect(setUpAll1Run, isTrue); expect(setUpAll2Run, isFalse); expect(setUpAll3Run, isFalse); setUpAll2Run = true; }); setUpAll(() { expect(setUpAll1Run, isTrue); expect(setUpAll2Run, isTrue); expect(setUpAll3Run, isFalse); setUpAll3Run = true; }); test('test', () { expect(setUpAll1Run, isTrue); expect(setUpAll2Run, isTrue); expect(setUpAll3Run, isTrue); }); }); }); group('asynchronously', () { test('blocks additional setUpAlls on in-band async', () { return expectTestsPass(() { var setUpAll1Run = false; var setUpAll2Run = false; var setUpAll3Run = false; setUpAll(() async { expect(setUpAll1Run, isFalse); expect(setUpAll2Run, isFalse); expect(setUpAll3Run, isFalse); await pumpEventQueue(); setUpAll1Run = true; }); setUpAll(() async { expect(setUpAll1Run, isTrue); expect(setUpAll2Run, isFalse); expect(setUpAll3Run, isFalse); await pumpEventQueue(); setUpAll2Run = true; }); setUpAll(() async { expect(setUpAll1Run, isTrue); expect(setUpAll2Run, isTrue); expect(setUpAll3Run, isFalse); await pumpEventQueue(); setUpAll3Run = true; }); test('test', () { expect(setUpAll1Run, isTrue); expect(setUpAll2Run, isTrue); expect(setUpAll3Run, isTrue); }); }); }); test("doesn't block additional setUpAlls on out-of-band async", () { return expectTestsPass(() { var setUpAll1Run = false; var setUpAll2Run = false; var setUpAll3Run = false; setUpAll(() { expect(setUpAll1Run, isFalse); expect(setUpAll2Run, isFalse); expect(setUpAll3Run, isFalse); expect( pumpEventQueue().then((_) { setUpAll1Run = true; }), completes); }); setUpAll(() { expect(setUpAll1Run, isFalse); expect(setUpAll2Run, isFalse); expect(setUpAll3Run, isFalse); expect( pumpEventQueue().then((_) { setUpAll2Run = true; }), completes); }); setUpAll(() { expect(setUpAll1Run, isFalse); expect(setUpAll2Run, isFalse); expect(setUpAll3Run, isFalse); expect( pumpEventQueue().then((_) { setUpAll3Run = true; }), completes); }); test('test', () { expect(setUpAll1Run, isTrue); expect(setUpAll2Run, isTrue); expect(setUpAll3Run, isTrue); }); }); }); }); test("isn't run for a skipped group", () async { // Declare this in the outer test so if it runs, the outer test will fail. var shouldNotRun = expectAsync0(() {}, count: 0); var engine = declareEngine(() { group('skipped', () { setUpAll(shouldNotRun); test('test', () {}); }, skip: true); }); await engine.run(); expect(engine.liveTests, hasLength(1)); expect(engine.skipped, hasLength(1)); expect(engine.liveTests, equals(engine.skipped)); }); test('is emitted through Engine.onTestStarted', () async { var engine = declareEngine(() { setUpAll(() {}); test('test', () {}); }); var queue = StreamQueue(engine.onTestStarted); var setUpAllFuture = queue.next; var liveTestFuture = queue.next; await engine.run(); var setUpAllLiveTest = await setUpAllFuture; expect(setUpAllLiveTest.test.name, equals('(setUpAll)')); expectTestPassed(setUpAllLiveTest); // The fake test for setUpAll should be removed from the engine's live // test list so that reporters don't display it as a passed test. expect(engine.liveTests, isNot(contains(setUpAllLiveTest))); expect(engine.passed, isNot(contains(setUpAllLiveTest))); expect(engine.failed, isNot(contains(setUpAllLiveTest))); expect(engine.skipped, isNot(contains(setUpAllLiveTest))); expect(engine.active, isNot(contains(setUpAllLiveTest))); var liveTest = await liveTestFuture; expectTestPassed(await liveTestFuture); expect(engine.liveTests, contains(liveTest)); expect(engine.passed, contains(liveTest)); }); group('with an error', () { test('reports the error and remains in Engine.liveTests', () async { var engine = declareEngine(() { setUpAll(() => throw TestFailure('fail')); test('test', () {}); }); var queue = StreamQueue(engine.onTestStarted); var setUpAllFuture = queue.next; expect(await engine.run(), isFalse); var setUpAllLiveTest = await setUpAllFuture; expect(setUpAllLiveTest.test.name, equals('(setUpAll)')); expectTestFailed(setUpAllLiveTest, 'fail'); // The fake test for setUpAll should be removed from the engine's live // test list so that reporters don't display it as a passed test. expect(engine.liveTests, contains(setUpAllLiveTest)); expect(engine.failed, contains(setUpAllLiveTest)); expect(engine.passed, isNot(contains(setUpAllLiveTest))); expect(engine.skipped, isNot(contains(setUpAllLiveTest))); expect(engine.active, isNot(contains(setUpAllLiveTest))); }); test("doesn't run tests in the group", () async { // Declare this in the outer test so if it runs, the outer test will fail. var shouldNotRun = expectAsync0(() {}, count: 0); var engine = declareEngine(() { setUpAll(() => throw 'error'); test('test', shouldNotRun); }); expect(await engine.run(), isFalse); }); test("doesn't run inner groups", () async { // Declare this in the outer test so if it runs, the outer test will fail. var shouldNotRun = expectAsync0(() {}, count: 0); var engine = declareEngine(() { setUpAll(() => throw 'error'); group('group', () { test('test', shouldNotRun); }); }); expect(await engine.run(), isFalse); }); test("doesn't run further setUpAlls", () async { // Declare this in the outer test so if it runs, the outer test will fail. var shouldNotRun = expectAsync0(() {}, count: 0); var engine = declareEngine(() { setUpAll(() => throw 'error'); setUpAll(shouldNotRun); test('test', shouldNotRun); }); expect(await engine.run(), isFalse); }); }); }
test/pkgs/test_api/test/frontend/set_up_all_test.dart/0
{'file_path': 'test/pkgs/test_api/test/frontend/set_up_all_test.dart', 'repo_id': 'test', 'token_count': 4140}
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// An expected exception caused by user-controllable circumstances. class ApplicationException implements Exception { final String message; ApplicationException(this.message); @override String toString() => message; }
test/pkgs/test_core/lib/src/runner/application_exception.dart/0
{'file_path': 'test/pkgs/test_core/lib/src/runner/application_exception.dart', 'repo_id': 'test', 'token_count': 108}
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:collection'; import 'package:test_api/src/backend/runtime.dart'; // ignore: implementation_imports import 'platform.dart'; /// The functions to use to load [_platformPlugins] in all loaders. /// /// **Do not access this outside the test package**. final platformCallbacks = UnmodifiableMapView<Runtime, FutureOr<PlatformPlugin> Function()>( _platformCallbacks); final _platformCallbacks = <Runtime, FutureOr<PlatformPlugin> Function()>{}; /// **Do not call this function without express permission from the test package /// authors**. /// /// Registers a [PlatformPlugin] for [runtimes]. /// /// This globally registers a plugin for all [Loader]s. When the runner first /// requests that a suite be loaded for one of the given runtimes, this will /// call [plugin] to load the platform plugin. It may return either a /// [PlatformPlugin] or a [Future<PlatformPlugin>]. That plugin is then /// preserved and used to load all suites for all matching runtimes. /// /// This overwrites the default plugins for those runtimes. void registerPlatformPlugin( Iterable<Runtime> runtimes, FutureOr<PlatformPlugin> Function() plugin) { for (var runtime in runtimes) { _platformCallbacks[runtime] = plugin; } }
test/pkgs/test_core/lib/src/runner/hack_register_platform.dart/0
{'file_path': 'test/pkgs/test_core/lib/src/runner/hack_register_platform.dart', 'repo_id': 'test', 'token_count': 405}
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'dart:isolate'; import 'package:test_api/src/backend/live_test.dart'; // ignore: implementation_imports import 'package:test_api/src/backend/message.dart'; // ignore: implementation_imports import 'package:test_api/src/backend/state.dart'; // ignore: implementation_imports import '../../util/io.dart'; import '../../util/pretty_print.dart'; import '../../util/pretty_print.dart' as utils; import '../engine.dart'; import '../load_exception.dart'; import '../load_suite.dart'; import '../reporter.dart'; /// A reporter that prints test results to the console in a single /// continuously-updating line. class CompactReporter implements Reporter { /// Whether the reporter should emit terminal color escapes. final bool _color; /// The terminal escape for green text, or the empty string if this is Windows /// or not outputting to a terminal. final String _green; /// The terminal escape for red text, or the empty string if this is Windows /// or not outputting to a terminal. final String _red; /// The terminal escape for yellow text, or the empty string if this is /// Windows or not outputting to a terminal. final String _yellow; /// The terminal escape for gray text, or the empty string if this is /// Windows or not outputting to a terminal. final String _gray; /// The terminal escape code for cyan text, or the empty string if this is /// Windows or not outputting to a terminal. final String _cyan; /// The terminal escape for bold text, or the empty string if this is /// Windows or not outputting to a terminal. final String _bold; /// The terminal escape for removing test coloring, or the empty string if /// this is Windows or not outputting to a terminal. final String _noColor; /// The engine used to run the tests. final Engine _engine; /// Whether the path to each test's suite should be printed. final bool _printPath; /// Whether the platform each test is running on should be printed. final bool _printPlatform; /// A stopwatch that tracks the duration of the full run. final _stopwatch = Stopwatch(); /// Whether we've started [_stopwatch]. /// /// We can't just use `_stopwatch.isRunning` because the stopwatch is stopped /// when the reporter is paused. var _stopwatchStarted = false; /// The size of `_engine.passed` last time a progress notification was /// printed. int _lastProgressPassed = 0; /// The size of `_engine.skipped` last time a progress notification was /// printed. int? _lastProgressSkipped; /// The size of `_engine.failed` last time a progress notification was /// printed. int? _lastProgressFailed; /// The duration of the test run in seconds last time a progress notification /// was printed. int? _lastProgressElapsed; /// The message printed for the last progress notification. String? _lastProgressMessage; /// The suffix added to the last progress notification. String? _lastProgressSuffix; /// Whether the message printed for the last progress notification was /// truncated. bool? _lastProgressTruncated; // Whether a newline has been printed since the last progress line. var _printedNewline = true; /// Whether the reporter is paused. var _paused = false; // Whether a notice should be logged about enabling stack trace chaining at // the end of all tests running. var _shouldPrintStackTraceChainingNotice = false; /// The set of all subscriptions to various streams. final _subscriptions = <StreamSubscription>{}; final StringSink _sink; /// Watches the tests run by [engine] and prints their results to the /// terminal. /// /// If [color] is `true`, this will use terminal colors; if it's `false`, it /// won't. If [printPath] is `true`, this will print the path name as part of /// the test description. Likewise, if [printPlatform] is `true`, this will /// print the platform as part of the test description. static CompactReporter watch(Engine engine, StringSink sink, {required bool color, required bool printPath, required bool printPlatform}) => CompactReporter._(engine, sink, color: color, printPath: printPath, printPlatform: printPlatform); CompactReporter._(this._engine, this._sink, {required bool color, required bool printPath, required bool printPlatform}) : _printPath = printPath, _printPlatform = printPlatform, _color = color, _green = color ? '\u001b[32m' : '', _red = color ? '\u001b[31m' : '', _yellow = color ? '\u001b[33m' : '', _gray = color ? '\u001b[90m' : '', _cyan = color ? '\u001b[36m' : '', _bold = color ? '\u001b[1m' : '', _noColor = color ? '\u001b[0m' : '' { _subscriptions.add(_engine.onTestStarted.listen(_onTestStarted)); // Convert the future to a stream so that the subscription can be paused or // canceled. _subscriptions.add(_engine.success.asStream().listen(_onDone)); } @override void pause() { if (_paused) return; _paused = true; if (!_printedNewline) _sink.writeln(''); _printedNewline = true; _stopwatch.stop(); // Force the next message to be printed, even if it's identical to the // previous one. If the reporter was paused, text was probably printed // during the pause. _lastProgressMessage = null; for (var subscription in _subscriptions) { subscription.pause(); } } @override void resume() { if (!_paused) return; _paused = false; if (_stopwatchStarted) _stopwatch.start(); for (var subscription in _subscriptions) { subscription.resume(); } } void _cancel() { for (var subscription in _subscriptions) { subscription.cancel(); } _subscriptions.clear(); } /// A callback called when the engine begins running [liveTest]. void _onTestStarted(LiveTest liveTest) { if (!_stopwatchStarted) { _stopwatchStarted = true; _stopwatch.start(); // Keep updating the time even when nothing else is happening. _subscriptions.add(Stream.periodic(Duration(seconds: 1)) .listen((_) => _progressLine(_lastProgressMessage ?? ''))); } // If this is the first test or suite load to start, print a progress line // so the user knows what's running. if ((_engine.active.length == 1 && _engine.active.first == liveTest) || (_engine.active.isEmpty && _engine.activeSuiteLoads.length == 1 && _engine.activeSuiteLoads.first == liveTest)) { _progressLine(_description(liveTest)); } _subscriptions.add(liveTest.onStateChange .listen((state) => _onStateChange(liveTest, state))); _subscriptions.add(liveTest.onError .listen((error) => _onError(liveTest, error.error, error.stackTrace))); _subscriptions.add(liveTest.onMessage.listen((message) { _progressLine(_description(liveTest), truncate: false); if (!_printedNewline) _sink.writeln(''); _printedNewline = true; var text = message.text; if (message.type == MessageType.skip) text = ' $_yellow$text$_noColor'; _sink.writeln(text); })); liveTest.onComplete.then((_) { var result = liveTest.state.result; if (result != Result.error && result != Result.failure) return; _sink.writeln(''); _sink.writeln('$_bold${_cyan}To run this test again:$_noColor ' '${Platform.executable} test ${liveTest.suite.path} ' '-p ${liveTest.suite.platform.runtime.identifier} ' "--plain-name '${liveTest.test.name.replaceAll("'", r"'\''")}'"); }); } /// A callback called when [liveTest]'s state becomes [state]. void _onStateChange(LiveTest liveTest, State state) { if (state.status != Status.complete) return; // Errors are printed in [onError]; no need to print them here as well. if (state.result == Result.failure) return; if (state.result == Result.error) return; // Always display the name of the oldest active test, unless testing // is finished in which case display the last test to complete. if (_engine.active.isEmpty) { _progressLine(_description(liveTest)); } else { _progressLine(_description(_engine.active.first)); } } /// A callback called when [liveTest] throws [error]. void _onError(LiveTest liveTest, error, StackTrace stackTrace) { if (!liveTest.test.metadata.chainStackTraces && !liveTest.suite.isLoadSuite) { _shouldPrintStackTraceChainingNotice = true; } if (liveTest.state.status != Status.complete) return; _progressLine(_description(liveTest), truncate: false, suffix: ' $_bold$_red[E]$_noColor'); if (!_printedNewline) _sink.writeln(''); _printedNewline = true; if (error is! LoadException) { _sink.writeln(indent(error.toString())); _sink.writeln(indent('$stackTrace')); return; } // TODO - what type is this? _sink.writeln(indent(error.toString(color: _color))); // Only print stack traces for load errors that come from the user's code. if (error.innerError is! IOException && error.innerError is! IsolateSpawnException && error.innerError is! FormatException && error.innerError is! String) { _sink.writeln(indent('$stackTrace')); } } /// A callback called when the engine is finished running tests. /// /// [success] will be `true` if all tests passed, `false` if some tests /// failed, and `null` if the engine was closed prematurely. void _onDone(bool? success) { _cancel(); _stopwatch.stop(); // A null success value indicates that the engine was closed before the // tests finished running, probably because of a signal from the user. We // shouldn't print summary information, we should just make sure the // terminal cursor is on its own line. if (success == null) { if (!_printedNewline) _sink.writeln(''); _printedNewline = true; return; } if (_engine.liveTests.isEmpty) { if (!_printedNewline) _sink.write('\r'); var message = 'No tests ran.'; _sink.write(message); // Add extra padding to overwrite any load messages. if (!_printedNewline) _sink.write(' ' * (lineLength - message.length)); _sink.writeln(''); } else if (!success) { for (var liveTest in _engine.active) { _progressLine(_description(liveTest), truncate: false, suffix: ' - did not complete $_bold$_red[E]$_noColor'); _sink.writeln(''); } _progressLine('Some tests failed.', color: _red); _sink.writeln(''); } else if (_engine.passed.isEmpty) { _progressLine('All tests skipped.'); _sink.writeln(''); } else { _progressLine('All tests passed!'); _sink.writeln(''); } if (_shouldPrintStackTraceChainingNotice) { _sink ..writeln('') ..writeln('Consider enabling the flag chain-stack-traces to ' 'receive more detailed exceptions.\n' "For example, 'dart test --chain-stack-traces'."); } } /// Prints a line representing the current state of the tests. /// /// [message] goes after the progress report, and may be truncated to fit the /// entire line within [lineLength]. If [color] is passed, it's used as the /// color for [message]. If [suffix] is passed, it's added to the end of /// [message]. bool _progressLine(String message, {String? color, bool truncate = true, String? suffix}) { var elapsed = _stopwatch.elapsed.inSeconds; // Print nothing if nothing has changed since the last progress line. if (_engine.passed.length == _lastProgressPassed && _engine.skipped.length == _lastProgressSkipped && _engine.failed.length == _lastProgressFailed && message == _lastProgressMessage && // Don't re-print just because a suffix was removed. (suffix == null || suffix == _lastProgressSuffix) && // Don't re-print just because the message became re-truncated, because // that doesn't add information. (truncate || !_lastProgressTruncated!) && // If we printed a newline, that means the last line *wasn't* a progress // line. In that case, we don't want to print a new progress line just // because the elapsed time changed. (_printedNewline || elapsed == _lastProgressElapsed)) { return false; } _lastProgressPassed = _engine.passed.length; _lastProgressSkipped = _engine.skipped.length; _lastProgressFailed = _engine.failed.length; _lastProgressElapsed = elapsed; _lastProgressMessage = message; _lastProgressSuffix = suffix; _lastProgressTruncated = truncate; if (suffix != null) message += suffix; color ??= ''; var duration = _stopwatch.elapsed; var buffer = StringBuffer(); // \r moves back to the beginning of the current line. buffer.write('\r${_timeString(duration)} '); buffer.write(_green); buffer.write('+'); buffer.write(_engine.passed.length); buffer.write(_noColor); if (_engine.skipped.isNotEmpty) { buffer.write(_yellow); buffer.write(' ~'); buffer.write(_engine.skipped.length); buffer.write(_noColor); } if (_engine.failed.isNotEmpty) { buffer.write(_red); buffer.write(' -'); buffer.write(_engine.failed.length); buffer.write(_noColor); } buffer.write(': '); buffer.write(color); // Ensure the line fits within [lineLength]. [buffer] includes the color // escape sequences too. Because these sequences are not visible characters, // we make sure they are not counted towards the limit. var length = withoutColors(buffer.toString()).length; if (truncate) message = utils.truncate(message, lineLength - length); buffer.write(message); buffer.write(_noColor); // Pad the rest of the line so that it looks erased. buffer.write(' ' * (lineLength - withoutColors(buffer.toString()).length)); _sink.write(buffer.toString()); _printedNewline = false; return true; } /// Returns a representation of [duration] as `MM:SS`. String _timeString(Duration duration) { return "${duration.inMinutes.toString().padLeft(2, '0')}:" "${(duration.inSeconds % 60).toString().padLeft(2, '0')}"; } /// Returns a description of [liveTest]. /// /// This differs from the test's own description in that it may also include /// the suite's name. String _description(LiveTest liveTest) { var name = liveTest.test.name; if (_printPath && liveTest.suite is! LoadSuite && liveTest.suite.path != null) { name = '${liveTest.suite.path}: $name'; } if (_printPlatform) { name = '[${liveTest.suite.platform.runtime.name}] $name'; } if (liveTest.suite is LoadSuite) name = '$_bold$_gray$name$_noColor'; return name; } }
test/pkgs/test_core/lib/src/runner/reporter/compact.dart/0
{'file_path': 'test/pkgs/test_core/lib/src/runner/reporter/compact.dart', 'repo_id': 'test', 'token_count': 5296}