code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
// ignore: import_of_legacy_library_into_null_safe import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../marvel.dart'; import '../widgets/loading_image.dart'; /// The selected Character's ID /// /// It is an error to use [CharacterView] without overriding this /// provider to a non-null value. /// /// See also: /// /// - [MaterialApp.onGenerateRoute], in `main.dart`, which overrides /// [selectedCharacterId] to set the ID based by parsing the route path. /// /// - [CharacterView], which consumes this provider and [character] to /// show the information of one specific [Character]. final selectedCharacterId = Provider<String>((ref) { throw UnimplementedError(); }); /// A provider that individually fetches a [Character] based on its ID. /// /// This rarely perform an HTTP request as most of the time the [Character] /// is already pre-fetched by the home page. /// /// The catch is: When using deep-links, a user may want to see a [Character] /// without clicking on its item in the home page – in which case the [Character] /// wasn't obtained yet. /// In that situation, the provider will trigger an HTTP request to read that /// [Character] specifically. /// /// If the user leaves the detail page before the HTTP request completes, /// the request is cancelled. final character = FutureProvider.autoDispose.family<Character, String>((ref, id) async { // The user used a deep-link to land in the Character page, so we fetch // the Character individually. // Cancel the HTTP request if the user leaves the detail page before // the request completes. final cancelToken = CancelToken(); ref.onDispose(cancelToken.cancel); final repository = ref.watch(repositoryProvider); final character = await repository.fetchCharacter( id, cancelToken: cancelToken, ); /// Cache the Character once it was successfully obtained. ref.keepAlive(); return character; }); class CharacterView extends HookConsumerWidget { const CharacterView({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { final id = ref.watch(selectedCharacterId); return ref.watch(character(id)).when( loading: () { return const Scaffold( body: Center(child: CircularProgressIndicator()), ); }, error: (err, stack) { return Scaffold( appBar: AppBar( title: const Text('Error'), ), ); }, data: (character) { return Scaffold( appBar: AppBar( title: Text(character.name), ), body: LoadingImage(url: character.thumbnail.url), ); }, ); } }
riverpod/examples/marvel/lib/src/screens/character_detail.dart/0
{'file_path': 'riverpod/examples/marvel/lib/src/screens/character_detail.dart', 'repo_id': 'riverpod', 'token_count': 903}
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; class PubAppbar extends StatelessWidget implements PreferredSizeWidget { const PubAppbar({super.key}); static const _webProxy = 'https://api.codetabs.com/v1/proxy'; static const _dartLogoURL = 'https://pub.dev/static/hash-6pt3begn/img/pub-dev-logo.svg'; @override Widget build(BuildContext context) { return AppBar( backgroundColor: const Color(0xFF1c2834), title: SvgPicture.network( kIsWeb ? '$_webProxy/?quest=$_dartLogoURL' : _dartLogoURL, width: 150, ), ); } @override Size get preferredSize => AppBar().preferredSize; }
riverpod/examples/pub/lib/pub_ui/appbar.dart/0
{'file_path': 'riverpod/examples/pub/lib/pub_ui/appbar.dart', 'repo_id': 'riverpod', 'token_count': 283}
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; // A Counter example implemented with riverpod void main() { runApp( // Adding ProviderScope enables Riverpod for the entire project const ProviderScope(child: MyApp()), ); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(home: Home()); } } /// Providers are declared globally and specify how to create a state final counterProvider = StateProvider((ref) => 0); class Home extends ConsumerWidget { const Home({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { return Scaffold( appBar: AppBar(title: const Text('Counter example')), body: Center( // Consumer is a builder widget that allows you to read providers. child: Consumer( builder: (context, ref, _) { final count = ref.watch(counterProvider); return Text('$count'); }, ), ), floatingActionButton: FloatingActionButton( // The read method is a utility to read a provider without listening to it onPressed: () => ref.read(counterProvider.notifier).state++, child: const Icon(Icons.add), ), ); } }
riverpod/packages/flutter_riverpod/example/lib/main.dart/0
{'file_path': 'riverpod/packages/flutter_riverpod/example/lib/main.dart', 'repo_id': 'riverpod', 'token_count': 467}
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/src/internals.dart'; import 'package:flutter_test/flutter_test.dart'; import 'utils.dart'; void main() { testWidgets('Riverpod test', (tester) async { // Regression test for https://github.com/rrousselGit/riverpod/pull/3156 final streamProvider = StreamProvider.autoDispose((ref) async* {}); final provider1 = Provider.autoDispose((ref) { ref.keepAlive(); ref.watch(streamProvider); }); await tester.pumpWidget( ProviderScope( child: Consumer( builder: (context, ref, child) { ref.watch(provider1); return const SizedBox(); }, ), ), ); }); testWidgets('Passes key', (tester) async { await tester.pumpWidget( ProviderScope( child: Consumer( key: const Key('42'), builder: (context, ref, _) { return Container(); }, ), ), ); expect(find.byKey(const Key('42')), findsOneWidget); }); testWidgets('Ref is unusable after dispose', (tester) async { late WidgetRef ref; await tester.pumpWidget( ProviderScope( child: Consumer( builder: (context, r, child) { ref = r; return Container(); }, ), ), ); await tester.pumpWidget(ProviderScope(child: Container())); final throwsDisposeError = throwsA( isA<StateError>().having( (e) => e.message, 'message', 'Cannot use "ref" after the widget was disposed.', ), ); expect(() => ref.read(_provider), throwsDisposeError); expect(() => ref.watch(_provider), throwsDisposeError); expect(() => ref.refresh(_provider), throwsDisposeError); expect(() => ref.invalidate(_provider), throwsDisposeError); expect(() => ref.listen(_provider, (_, __) {}), throwsDisposeError); expect(() => ref.listenManual(_provider, (_, __) {}), throwsDisposeError); }); group('WidgetRef.exists', () { testWidgets('simple use-case', (tester) async { late WidgetRef ref; await tester.pumpWidget( ProviderScope( child: Consumer( builder: (context, r, child) { ref = r; return Container(); }, ), ), ); final provider = Provider((ref) => 0); expect(ref.exists(provider), false); expect(ref.exists(provider), false); ref.read(provider); expect(ref.exists(provider), true); }); }); testWidgets('WidgetRef.context exposes the BuildContext', (tester) async { late WidgetRef ref; await tester.pumpWidget( CallbackConsumerWidget( key: const Key('initState'), initState: (ctx, r) { ref = r; }, ), ); final consumerElement = tester.element(find.byType(CallbackConsumerWidget)); expect(ref.context, same(consumerElement)); }); testWidgets('throws if listen is used outside of `build`', (tester) async { final provider = Provider((ref) => 0); await tester.pumpWidget( CallbackConsumerWidget( key: const Key('initState'), initState: (ctx, ref) { ref.listen(provider, (prev, value) {}); }, ), ); expect(tester.takeException(), isAssertionError); }); testWidgets('works with providers that returns null', (tester) async { final nullProvider = Provider((ref) => null); Consumer( builder: (context, ref, _) { // should compile ref.watch(nullProvider); return Container(); }, ); }); testWidgets('can use "watch" inside ListView.builder', (tester) async { final provider = Provider((ref) => 'hello world'); await tester.pumpWidget( ProviderScope( child: Directionality( textDirection: TextDirection.ltr, child: Consumer( builder: (context, ref, _) { return ListView.builder( itemCount: 1, itemBuilder: (context, index) { return Text(ref.watch(provider)); }, ); }, ), ), ), ); expect(find.text('hello world'), findsOneWidget); }); testWidgets('can extend ConsumerWidget', (tester) async { await tester.pumpWidget(const ProviderScope(child: MyWidget())); expect(find.text('hello world'), findsOneWidget); }); testWidgets('hot-reload forces the widget to refresh', (tester) async { var buildCount = 0; await tester.pumpWidget( ProviderScope( child: Consumer( builder: (context, ref, _) { buildCount++; return Container(); }, ), ), ); expect(find.byType(Container), findsOneWidget); expect(buildCount, 1); // ignore: unawaited_futures tester.binding.reassembleApplication(); await tester.pump(); expect(find.byType(Container), findsOneWidget); expect(buildCount, 2); }); testWidgets( 'Consumer removing one of multiple listeners on a provider still listen to the provider', (tester) async { final stateProvider = StateProvider((ref) => 0, name: 'state'); final notifier0 = TestNotifier(); final notifier1 = TestNotifier(42); final provider0 = StateNotifierProvider<TestNotifier, int>( name: '0', (_) => notifier0, ); final provider1 = StateNotifierProvider<TestNotifier, int>( name: '1', (_) => notifier1, ); var buildCount = 0; await tester.pumpWidget( ProviderScope( child: Consumer( builder: (c, ref, _) { buildCount++; final state = ref.watch(stateProvider); final value = state == 0 ? ref.watch(provider0) : ref.watch(provider1); return Text( '${ref.watch(provider0)} $value', textDirection: TextDirection.ltr, ); }, ), ), ); final container = tester // .state<ProviderScopeState>(find.byType(ProviderScope)) .container; container.read(provider0); container.read(provider1); final familyState0 = container.getAllProviderElements().firstWhere((p) { return p.provider == provider0; }); final familyState1 = container.getAllProviderElements().firstWhere((p) { return p.provider == provider1; }); expect(buildCount, 1); expect(familyState0.hasListeners, true); expect(familyState1.hasListeners, false); expect(find.text('0 0'), findsOneWidget); notifier0.increment(); await tester.pump(); expect(buildCount, 2); expect(find.text('1 1'), findsOneWidget); notifier1.increment(); await tester.pump(); expect(buildCount, 2); // changing the provider that computed is subscribed to container.read(stateProvider.notifier).state = 1; await tester.pump(); expect(buildCount, 3); expect(find.text('1 43'), findsOneWidget); expect(familyState1.hasListeners, true); expect(familyState0.hasListeners, true); notifier1.increment(); await tester.pump(); expect(buildCount, 4); expect(find.text('1 44'), findsOneWidget); notifier0.increment(); await tester.pump(); expect(buildCount, 5); expect(find.text('2 44'), findsOneWidget); }); testWidgets( 'Stops listening to a provider when recomputed but no longer using it', (tester) async { final stateProvider = StateProvider((ref) => 0, name: 'state'); final notifier0 = TestNotifier(); final notifier1 = TestNotifier(42); final provider0 = StateNotifierProvider<TestNotifier, int>( name: '0', (_) => notifier0, ); final provider1 = StateNotifierProvider<TestNotifier, int>( name: '1', (_) => notifier1, ); var buildCount = 0; await tester.pumpWidget( ProviderScope( child: Consumer( builder: (c, ref, _) { buildCount++; final state = ref.watch(stateProvider); final result = state == 0 // ? ref.watch(provider0) : ref.watch(provider1); return Text('$result', textDirection: TextDirection.ltr); }, ), ), ); final container = tester // .state<ProviderScopeState>(find.byType(ProviderScope)) .container; container.read(provider0); container.read(provider1); final familyState0 = container.getAllProviderElements().firstWhere((p) { return p.provider == provider0; }); final familyState1 = container.getAllProviderElements().firstWhere((p) { return p.provider == provider1; }); expect(buildCount, 1); expect(familyState0.hasListeners, true); expect(familyState1.hasListeners, false); expect(find.text('0'), findsOneWidget); notifier0.increment(); await tester.pump(); expect(buildCount, 2); expect(find.text('1'), findsOneWidget); notifier1.increment(); await tester.pump(); expect(buildCount, 2); // changing the provider that computed is subscribed to container.read(stateProvider.notifier).state = 1; await tester.pump(); expect(buildCount, 3); expect(find.text('43'), findsOneWidget); expect(familyState1.hasListeners, true); expect(familyState0.hasListeners, false); notifier1.increment(); await tester.pump(); expect(buildCount, 4); expect(find.text('44'), findsOneWidget); notifier0.increment(); await tester.pump(); expect(buildCount, 4); }); testWidgets('Consumer supports changing the provider', (tester) async { final notifier1 = TestNotifier(); final provider1 = StateNotifierProvider<TestNotifier, int>((_) { return notifier1; }); final notifier2 = TestNotifier(42); final provider2 = StateNotifierProvider<TestNotifier, int>((_) { return notifier2; }); var buildCount = 0; Widget build(StateNotifierProvider<TestNotifier, int> provider) { return ProviderScope( child: Consumer( builder: (c, ref, _) { buildCount++; final value = ref.watch(provider); return Text('$value', textDirection: TextDirection.ltr); }, ), ); } await tester.pumpWidget(build(provider1)); expect(find.text('0'), findsOneWidget); expect(buildCount, 1); await tester.pumpWidget(build(provider2)); expect(find.text('42'), findsOneWidget); expect(buildCount, 2); notifier1.increment(); await tester.pump(); expect(find.text('42'), findsOneWidget); expect(buildCount, 2); notifier2.increment(); await tester.pump(); expect(find.text('43'), findsOneWidget); expect(buildCount, 3); }); testWidgets( 'multiple watch, when one of them forces rebuild, all dependencies are still flushed', (tester) async { final notifier = TestNotifier(); final provider = StateNotifierProvider<TestNotifier, int>((_) { return notifier; }); var callCount = 0; final computed = Provider<int>((ref) { callCount++; return ref.watch(provider); }); await tester.pumpWidget( ProviderScope( child: Consumer( builder: (context, ref, _) { final first = ref.watch(provider); final second = ref.watch(computed); return Text( '$first $second', textDirection: TextDirection.ltr, ); }, ), ), ); expect(find.text('0 0'), findsOneWidget); expect(callCount, 1); notifier.increment(); await tester.pump(); expect(find.text('1 1'), findsOneWidget); expect(callCount, 2); }); testWidgets("don't rebuild if Provider ref't actually change", (tester) async { final notifier = TestNotifier(); final provider = StateNotifierProvider<TestNotifier, int>((_) => notifier); final computed = Provider((ref) => !ref.watch(provider).isNegative); var buildCount = 0; final container = createContainer(); await tester.pumpWidget( UncontrolledProviderScope( container: container, child: Consumer( builder: (c, ref, _) { buildCount++; return Text( 'isPositive ${ref.watch(computed)}', textDirection: TextDirection.ltr, ); }, ), ), ); expect(find.text('isPositive true'), findsOneWidget); expect(buildCount, 1); notifier.increment(); await tester.pump(); expect(find.text('isPositive true'), findsOneWidget); expect(buildCount, 1); notifier.value = -10; await tester.pump(); expect(find.text('isPositive false'), findsOneWidget); expect(buildCount, 2); notifier.value = -5; await tester.pump(); expect(find.text('isPositive false'), findsOneWidget); expect(buildCount, 2); }); // testWidgets('remove listener when changing container', (tester) async { // final notifier = TestNotifier(); // final provider = StateNotifierProvider<TestNotifier, int>((_) { // return notifier; // }, name: 'provider'); // final notifier2 = TestNotifier(42); // const firstOwnerKey = Key('first'); // const secondOwnerKey = Key('second'); // final key = GlobalKey(); // final consumer = Consumer( // builder: (context, ref, _) { // final value = ref.watch(provider); // return Text('$value', textDirection: TextDirection.ltr); // }, // key: key); // await tester.pumpWidget( // Column( // children: [ // ProviderScope( // key: firstOwnerKey, // child: consumer, // ), // ProviderScope( // key: secondOwnerKey, // overrides: [ // provider.overrideWithValue(notifier2), // ], // child: Container(), // ), // ], // ), // ); // final owner1 = tester // // .firstState<ProviderScopeState>(find.byKey(firstOwnerKey)) // .container; // final state1 = owner1 // .getAllProviderElements() // .firstWhere((s) => s.provider == provider); // expect(state1.hasListeners, true); // expect(find.text('0'), findsOneWidget); // await tester.pumpWidget( // Column( // children: [ // ProviderScope( // key: firstOwnerKey, // child: Container(), // ), // ProviderScope( // key: secondOwnerKey, // overrides: [ // provider.overrideWithValue(notifier2), // ], // child: consumer, // ), // ], // ), // ); // final container2 = tester // // .firstState<ProviderScopeState>(find.byKey(secondOwnerKey)) // .container; // final state2 = container2 // .getAllProviderElements() // .firstWhere((s) => s.provider is StateNotifierProvider); // expect(find.text('0'), findsNothing); // expect(find.text('42'), findsOneWidget); // expect(state1.hasListeners, false); // expect(state2.hasListeners, true); // notifier2.increment(); // await tester.pump(); // expect(find.text('0'), findsNothing); // expect(find.text('43'), findsOneWidget); // expect(state1.hasListeners, false); // expect(state2.hasListeners, true); // }); testWidgets('remove listener when destroying the consumer', (tester) async { final notifier = TestNotifier(); final provider = StateNotifierProvider<TestNotifier, int>((_) => notifier); await tester.pumpWidget( ProviderScope( child: Consumer( builder: (context, ref, _) { final value = ref.watch(provider); return Text('$value', textDirection: TextDirection.ltr); }, ), ), ); final container = tester // .firstState<ProviderScopeState>(find.byType(ProviderScope)) .container; final state = container .getAllProviderElements() .firstWhere((s) => s.provider == provider); expect(state.hasListeners, true); expect(find.text('0'), findsOneWidget); await tester.pumpWidget( ProviderScope( child: Container(), ), ); expect(state.hasListeners, false); }); testWidgets('Multiple providers', (tester) async { final notifier = TestNotifier(); final firstProvider = StateNotifierProvider<TestNotifier, int>((_) { return notifier; }); final notifier2 = TestNotifier(); final secondProvider = StateNotifierProvider<TestNotifier, int>((_) { return notifier2; }); await tester.pumpWidget( ProviderScope( child: Consumer( builder: (context, ref, _) { final first = ref.watch(firstProvider); final second = ref.watch(secondProvider); return Text( 'first $first second $second', textDirection: TextDirection.ltr, ); }, ), ), ); expect(find.text('first 0 second 0'), findsOneWidget); notifier.increment(); await tester.pump(); expect(find.text('first 1 second 0'), findsOneWidget); notifier2.increment(); notifier2.increment(); await tester.pump(); expect(find.text('first 1 second 2'), findsOneWidget); }); testWidgets('Consumer', (tester) async { final notifier = TestNotifier(); final provider = StateNotifierProvider<TestNotifier, int>((_) => notifier); await tester.pumpWidget( ProviderScope( child: Consumer( builder: (context, ref, _) { final count = ref.watch(provider); return Text('$count', textDirection: TextDirection.ltr); }, ), ), ); expect(find.text('0'), findsOneWidget); notifier.increment(); await tester.pump(); expect(find.text('1'), findsOneWidget); await tester.pumpWidget(ProviderScope(child: Container())); notifier.increment(); await tester.pump(); }); testWidgets('changing provider', (tester) async { final provider = Provider((_) => 0); await tester.pumpWidget( ProviderScope( child: Consumer( builder: (context, ref, _) { final value = ref.watch(provider); return Text( '$value', textDirection: TextDirection.ltr, ); }, ), ), ); expect(find.text('0'), findsOneWidget); final provider2 = Provider((_) => 42); await tester.pumpWidget( ProviderScope( child: Consumer( builder: (context, ref, _) { final value = ref.watch(provider2); return Text( '$value', textDirection: TextDirection.ltr, ); }, ), ), ); expect(find.text('0'), findsNothing); expect(find.text('42'), findsOneWidget); }); testWidgets('can read scoped providers', (tester) async { final provider = Provider((_) => 0); final child = Consumer( builder: (context, ref, _) { final value = ref.watch(provider); return Text( '$value', textDirection: TextDirection.ltr, ); }, ); await tester.pumpWidget( ProviderScope( overrides: [ provider.overrideWithValue(42), ], child: child, ), ); expect(find.text('42'), findsOneWidget); await tester.pumpWidget( ProviderScope( overrides: [ provider.overrideWithValue(21), ], child: child, ), ); expect(find.text('21'), findsOneWidget); }); } class TestNotifier extends StateNotifier<int> { TestNotifier([super.initialValue = 0]); void increment() => state++; // ignore: avoid_setters_without_getters set value(int value) => state = value; } final _provider = Provider((ref) => 'hello world'); class MyWidget extends ConsumerWidget { const MyWidget({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { return Text(ref.watch(_provider), textDirection: TextDirection.rtl); } } class CallbackConsumerWidget extends ConsumerStatefulWidget { const CallbackConsumerWidget({ super.key, this.initState, this.didChangeDependencies, this.dispose, this.didUpdateWidget, this.reassemble, }); final void Function(BuildContext context, WidgetRef ref)? initState; final void Function(BuildContext context, WidgetRef ref)? didChangeDependencies; final void Function(BuildContext context, WidgetRef ref)? dispose; final void Function( BuildContext context, WidgetRef ref, CallbackConsumerWidget oldWidget, )? didUpdateWidget; final void Function(BuildContext context, WidgetRef ref)? reassemble; @override // ignore: library_private_types_in_public_api _CallbackConsumerWidgetState createState() => _CallbackConsumerWidgetState(); } class _CallbackConsumerWidgetState extends ConsumerState<CallbackConsumerWidget> { @override void initState() { super.initState(); widget.initState?.call(context, ref); } @override void didChangeDependencies() { super.didChangeDependencies(); widget.didChangeDependencies?.call(context, ref); } @override void dispose() { super.dispose(); widget.dispose?.call(context, ref); } @override void reassemble() { super.reassemble(); widget.reassemble?.call(context, ref); } @override void didUpdateWidget(covariant CallbackConsumerWidget oldWidget) { super.didUpdateWidget(oldWidget); widget.didUpdateWidget?.call(context, ref, oldWidget); } @override Widget build(BuildContext context) { return Container(); } }
riverpod/packages/flutter_riverpod/test/consumer_test.dart/0
{'file_path': 'riverpod/packages/flutter_riverpod/test/consumer_test.dart', 'repo_id': 'riverpod', 'token_count': 9149}
include: ../../../analysis_options.yaml linter: rules: # Useful for packages but not for apps type_annotate_public_apis: false # generates false positives close_sinks: false # Our example actually wants to print to the console avoid_print: false public_member_api_docs: false
riverpod/packages/hooks_riverpod/example/analysis_options.yaml/0
{'file_path': 'riverpod/packages/hooks_riverpod/example/analysis_options.yaml', 'repo_id': 'riverpod', 'token_count': 102}
part of '../framework.dart'; /// A provider that is driven by a value instead of a function. /// /// This is an implementation detail of `overrideWithValue`. @sealed @internal class ValueProvider<State> extends ProviderBase<State> with AlwaysAliveProviderBase<State> { /// Creates a [ValueProvider]. ValueProvider(this._value) : super( name: null, from: null, argument: null, debugGetCreateSourceHash: null, allTransitiveDependencies: null, dependencies: null, ); final State _value; @override Iterable<ProviderOrFamily>? get dependencies => null; @override Set<ProviderOrFamily>? get allTransitiveDependencies => null; @override ValueProviderElement<State> createElement() { return ValueProviderElement(this); } } /// The [ProviderElementBase] of a [ValueProvider] @sealed @internal class ValueProviderElement<State> extends ProviderElementBase<State> { /// The [ProviderElementBase] of a [ValueProvider] ValueProviderElement(ValueProvider<State> super._provider); /// A custom listener called when `overrideWithValue` changes /// with a different value. void Function(State value)? onChange; @override void update(ProviderBase<State> newProvider) { super.update(newProvider); final newValue = (provider as ValueProvider<State>)._value; // `getState` will never be in error/loading state since there is no "create" final previousState = getState()! as ResultData<State>; if (newValue != previousState.state) { assert( () { // Asserts would otherwise prevent a provider rebuild from updating // other providers _debugSkipNotifyListenersAsserts = true; return true; }(), '', ); setState(newValue); assert( () { // Asserts would otherwise prevent a provider rebuild from updating // other providers _debugSkipNotifyListenersAsserts = false; return true; }(), '', ); onChange?.call(newValue); } } @override void create({required bool didChangeDependency}) { final provider = this.provider as ValueProvider<State>; setState(provider._value); } @override bool updateShouldNotify(State previous, State next) { return true; } }
riverpod/packages/riverpod/lib/src/framework/value_provider.dart/0
{'file_path': 'riverpod/packages/riverpod/lib/src/framework/value_provider.dart', 'repo_id': 'riverpod', 'token_count': 853}
import 'dart:async'; import 'package:meta/meta.dart'; /// Run a function while catching errors and reporting possible errors to the zone. @internal void runGuarded(void Function() cb) { try { cb(); } catch (err, stack) { Zone.current.handleUncaughtError(err, stack); } } /// Run a function while catching errors and reporting possible errors to the zone. @internal void runUnaryGuarded<T, Res>(Res Function(T) cb, T value) { try { cb(value); } catch (err, stack) { Zone.current.handleUncaughtError(err, stack); } } /// Run a function while catching errors and reporting possible errors to the zone. @internal void runBinaryGuarded<A, B>(void Function(A, B) cb, A value, B value2) { try { cb(value, value2); } catch (err, stack) { Zone.current.handleUncaughtError(err, stack); } } /// Run a function while catching errors and reporting possible errors to the zone. @internal void runTernaryGuarded<A, B, C>( void Function(A, B, C) cb, A value, B value2, C value3, ) { try { cb(value, value2, value3); } catch (err, stack) { Zone.current.handleUncaughtError(err, stack); } } /// Run a function while catching errors and reporting possible errors to the zone. @internal void runQuaternaryGuarded<A, B, C, D>( void Function(A, B, C, D) cb, A value, B value2, C value3, D value4, ) { try { cb(value, value2, value3, value4); } catch (err, stack) { Zone.current.handleUncaughtError(err, stack); } }
riverpod/packages/riverpod/lib/src/run_guarded.dart/0
{'file_path': 'riverpod/packages/riverpod/lib/src/run_guarded.dart', 'repo_id': 'riverpod', 'token_count': 543}
import 'dart:async'; import 'package:mockito/mockito.dart'; import 'package:riverpod/riverpod.dart'; import 'package:test/test.dart'; import '../utils.dart'; void main() { test('implements ProviderSubscription.read on AsyncData', () async { final container = createContainer(); final dep = StateProvider((ref) => 0); final provider = FutureProvider((ref) async => ref.watch(dep)); final sub = container.listen( provider.selectAsync((data) => data.isEven), (prev, next) {}, ); expect(await sub.read(), true); container.read(dep.notifier).state += 2; await container.read(provider.future); expect(await sub.read(), true); container.read(dep.notifier).state++; await container.read(provider.future); expect(await sub.read(), false); }); test('implements ProviderSubscription.read on AsyncError', () async { final container = createContainer(); final dep = StateProvider((ref) => 0); final provider = FutureProvider<int>( (ref) => Future.error(ref.watch(dep)), ); final sub = container.listen<Future<bool>>( provider.selectAsync((data) => data.isEven), (prev, next) { // workaround to the fact that throwA(2) later in the test // will be called _after_ the failing future is reported to the zone, // marking the test as failing when the future is in fact caught next.ignore(); }, ); await expectLater(sub.read(), throwsA(0)); container.read(dep.notifier).state += 2; // ignore: avoid_types_on_closure_parameters, conflict with implicit_dynamic await container.read(provider.future).catchError((Object? _) => 0); await expectLater(sub.read(), throwsA(2)); }); test('when selector throws, returns a failing future', () async { final container = createContainer(); final dep = StateProvider((ref) => 0); final provider = FutureProvider((ref) async => ref.watch(dep)); final sub = container.listen<Future<Object?>>( // ignore: only_throw_errors provider.selectAsync((data) => throw data), (prev, next) { // workaround to the fact that throwA(2) later in the test // will be called _after_ the failing future is reported to the zone, // marking the test as failing when the future is in fact caught next.ignore(); }, ); await expectLater(sub.read(), throwsA(0)); container.read(dep.notifier).state += 2; await container.read(provider.future); await expectLater(sub.read(), throwsA(2)); }); test('handles fireImmediately: true on AsyncLoading', () async { final container = createContainer(); final provider = FutureProvider((ref) async => 0); final listener = Listener<Future<bool>>(); container.listen( provider.selectAsync((data) => data.isEven), listener.call, fireImmediately: true, ); final result = verify(listener(argThat(isNull), captureAny)).captured.single as Future<bool>; verifyNoMoreInteractions(listener); expect(await result, true); }); test('handles fireImmediately: true on AsyncData', () async { final container = createContainer(); final provider = FutureProvider((ref) => 0); final listener = Listener<Future<bool>>(); container.listen( provider.selectAsync((data) => data.isEven), listener.call, fireImmediately: true, ); final result = verify(listener(argThat(isNull), captureAny)).captured.single as Future<bool>; verifyNoMoreInteractions(listener); expect(await result, true); }); test('handles fireImmediately: true on AsyncError', () async { final container = createContainer(); final provider = FutureProvider<int>((ref) => throw StateError('0')); final listener = Listener<Future<bool>>(); container.listen( provider.selectAsync((data) => data.isEven), listener.call, fireImmediately: true, ); final result = verify(listener(argThat(isNull), captureAny)).captured.single as Future<bool>; verifyNoMoreInteractions(listener); await expectLater(result, throwsStateError); }); test('handles fireImmediately: false', () async { final container = createContainer(); final provider = FutureProvider((ref) async => 0); final listener = Listener<Future<bool>>(); container.listen( provider.selectAsync((data) => data.isEven), listener.call, fireImmediately: false, ); verifyZeroInteractions(listener); }); test( 'catching errors in the future is not necessary if the error is coming from AsyncError', () async { final container = createContainer(); final provider = FutureProvider<int>((ref) => throw StateError('err')); container.listen( provider.selectAsync((data) => data.isEven), (prev, next) {}, fireImmediately: true, ); // If somehow the future failed, it would be sent to the zone, // making the test fail }); test('handles multiple AsyncLoading at once then data', () async { final container = createContainer(); late FutureProviderRef<int> ref; final provider = FutureProvider<int>((r) { ref = r; final completer = Completer<int>(); ref.onDispose(() => completer.complete(84)); return completer.future; }); final sub = container.listen( provider.selectAsync((data) => data + 40), (prev, next) {}, ); expect(sub.read(), completion(42)); ref.state = const AsyncLoading<int>() .copyWithPrevious(const AsyncValue<int>.data(0)); ref.state = const AsyncLoading<int>() .copyWithPrevious(const AsyncError<int>('err', StackTrace.empty)); ref.state = const AsyncLoading<int>(); ref.state = const AsyncData(2); // the previous unawaited `completion` should resolve with 2+40 }); test('can watch async selectors', () async { final container = createContainer(); var buildCount = 0; final dep = StateProvider((ref) => 0); final a = FutureProvider((ref) async => ref.watch(dep)); final b = FutureProvider((ref) { buildCount++; return ref.watch(a.selectAsync((value) => value % 10)); }); expect(buildCount, 0); expect(container.read(a), const AsyncLoading<int>()); expect(container.read(b), const AsyncLoading<int>()); expect(await container.read(b.future), 0); expect(buildCount, 1); container.read(dep.notifier).state = 1; expect( container.read(a), const AsyncLoading<int>() .copyWithPrevious(const AsyncData(0), isRefresh: false), ); expect(container.read(b), const AsyncData(0)); expect(buildCount, 1); await container.read(a.future); expect(await container.read(b.future), 1); expect(buildCount, 2); container.read(dep.notifier).state = 11; expect( container.read(a), const AsyncLoading<int>() .copyWithPrevious(const AsyncData(1), isRefresh: false), ); expect(container.read(b), const AsyncData(1)); expect(buildCount, 2); await container.read(a.future); expect(await container.read(b.future), 1); expect(buildCount, 2); container.read(dep.notifier).state = 12; expect( container.read(a), const AsyncLoading<int>() .copyWithPrevious(const AsyncData(11), isRefresh: false), ); expect(container.read(b), const AsyncData(1)); expect(buildCount, 2); await container.read(a.future); expect(await container.read(b.future), 2); expect(buildCount, 3); }); test('can watch async selectors (autoDispose)', () async { final container = createContainer(); var buildCount = 0; final dep = StateProvider((ref) => 0); final a = FutureProvider.autoDispose((ref) async => ref.watch(dep)); final b = FutureProvider.autoDispose((ref) { buildCount++; return ref.watch(a.selectAsync((value) => value % 10)); }); expect(buildCount, 0); expect(container.read(b), const AsyncLoading<int>()); expect(container.read(b), const AsyncLoading<int>()); expect(await container.read(b.future), 0); expect(buildCount, 1); container.read(dep.notifier).state = 1; expect( container.read(a), const AsyncLoading<int>() .copyWithPrevious(const AsyncData(0), isRefresh: false), ); expect(container.read(b), const AsyncData(0)); expect(buildCount, 1); await container.read(a.future); expect(await container.read(b.future), 1); expect(buildCount, 2); container.read(dep.notifier).state = 11; expect( container.read(a), const AsyncLoading<int>() .copyWithPrevious(const AsyncData(1), isRefresh: false), ); expect(container.read(b), const AsyncData(1)); expect(buildCount, 2); await container.read(a.future); expect(await container.read(b.future), 1); expect(buildCount, 2); container.read(dep.notifier).state = 12; expect( container.read(a), const AsyncLoading<int>() .copyWithPrevious(const AsyncData(11), isRefresh: false), ); expect(container.read(b), const AsyncData(1)); expect(buildCount, 2); await container.read(a.future); expect(await container.read(b.future), 2); expect(buildCount, 3); }); group('Supports ProviderContainer.read', () { test('and resolves with data', () async { final container = createContainer(); final provider = FutureProvider((ref) async => 0); expect( container.read(provider.selectAsync((data) => data.toString())), completion('0'), ); }); test('resolves with error', () async { final container = createContainer(); final provider = FutureProvider<int>((ref) async => throw StateError('err')); expect( container.read(provider.selectAsync((data) => data)), throwsStateError, ); }); test('emits exceptions inside selectors as Future.error', () async { final container = createContainer(); final provider = FutureProvider<int>((ref) async => 42); expect( container.read(provider.selectAsync((data) => throw StateError('err'))), throwsStateError, ); }); }); }
riverpod/packages/riverpod/test/framework/select_async_test.dart/0
{'file_path': 'riverpod/packages/riverpod/test/framework/select_async_test.dart', 'repo_id': 'riverpod', 'token_count': 3746}
import 'package:riverpod/riverpod.dart'; import 'package:test/test.dart'; import '../../utils.dart'; void main() { group('Provider.family', () { test('specifies `from` & `argument` for related providers', () { final provider = Provider.family<int, int>((ref, _) => 0); expect(provider(0).from, provider); expect(provider(0).argument, 0); }); group('scoping an override overrides all the associated subproviders', () { test('when passing the provider itself', () { final provider = Provider.family<int, int>((ref, _) => 0); final root = createContainer(); final container = createContainer(parent: root, overrides: [provider]); expect(container.read(provider(0)), 0); expect(container.getAllProviderElements(), [ isA<ProviderElementBase<Object?>>() .having((e) => e.origin, 'origin', provider(0)), ]); expect(root.getAllProviderElements(), isEmpty); }); test('when using provider.overrideWithProvider', () { final provider = Provider.family<int, int>((ref, _) => 0); final root = createContainer(); final container = createContainer( parent: root, overrides: [ provider.overrideWithProvider((value) => Provider((ref) => 42)), ], ); expect(root.getAllProviderElements(), isEmpty); expect(container.read(provider(0)), 42); expect(container.getAllProviderElements(), [ isA<ProviderElementBase<Object?>>() .having((e) => e.origin, 'origin', provider(0)), ]); }); }); test('can be auto-scoped', () async { final dep = Provider((ref) => 0); final provider = Provider.family<int, int>( (ref, i) => ref.watch(dep) + i, dependencies: [dep], ); final root = createContainer(); final container = createContainer( parent: root, overrides: [dep.overrideWithValue(42)], ); expect(container.read(provider(10)), 52); expect(root.getAllProviderElements(), isEmpty); }); }); }
riverpod/packages/riverpod/test/providers/provider/provider_family_test.dart/0
{'file_path': 'riverpod/packages/riverpod/test/providers/provider/provider_family_test.dart', 'repo_id': 'riverpod', 'token_count': 862}
import 'package:riverpod/riverpod.dart'; import 'package:test/test.dart'; import '../../utils.dart'; void main() { group('StreamProvider.family', () { test('specifies `from` & `argument` for related providers', () { final provider = StreamProvider.family<int, int>((ref, _) => Stream.value(0)); expect(provider(0).from, provider); expect(provider(0).argument, 0); }); group('scoping an override overrides all the associated subproviders', () { test('when passing the provider itself', () async { final provider = StreamProvider.family<int, int>((ref, _) => Stream.value(0)); final root = createContainer(); final container = createContainer(parent: root, overrides: [provider]); // ignore: deprecated_member_use_from_same_package expect(await container.read(provider(0).stream).first, 0); expect(await container.read(provider(0).future), 0); expect(container.read(provider(0)), const AsyncData(0)); expect(root.getAllProviderElements(), isEmpty); expect( container.getAllProviderElements(), unorderedEquals(<Object?>[ isA<ProviderElementBase<Object?>>() .having((e) => e.origin, 'origin', provider(0)), ]), ); }); test('when using provider.overrideWithProvider', () async { final provider = StreamProvider.family<int, int>((ref, _) => Stream.value(0)); final root = createContainer(); final container = createContainer( parent: root, overrides: [ provider.overrideWithProvider( (value) => StreamProvider((ref) => Stream.value(42)), ), ], ); // ignore: deprecated_member_use_from_same_package expect(await container.read(provider(0).stream).first, 42); expect(await container.read(provider(0).future), 42); expect(container.read(provider(0)), const AsyncData(42)); expect(root.getAllProviderElements(), isEmpty); expect( container.getAllProviderElements(), unorderedEquals(<Object?>[ isA<ProviderElementBase<Object?>>() .having((e) => e.origin, 'origin', provider(0)), ]), ); }); }); test('can be auto-scoped', () async { final dep = Provider((ref) => 0); final provider = StreamProvider.family<int, int>( (ref, i) => Stream.value(ref.watch(dep) + i), dependencies: [dep], ); final root = createContainer(); final container = createContainer( parent: root, overrides: [dep.overrideWithValue(42)], ); // ignore: deprecated_member_use_from_same_package await expectLater(container.read(provider(10).stream), emits(52)); await expectLater(container.read(provider(10).future), completion(52)); expect(container.read(provider(10)), const AsyncData(52)); expect(root.getAllProviderElements(), isEmpty); }); test('StreamProvider.family override', () async { final provider = StreamProvider.family<String, int>((ref, a) { return Stream.value('$a'); }); final container = ProviderContainer( overrides: [ provider.overrideWithProvider( (a) => StreamProvider((ref) => Stream.value('override $a')), ), ], ); expect(container.read(provider(0)), const AsyncValue<String>.loading()); await container.pump(); expect( container.read(provider(0)), const AsyncValue<String>.data('override 0'), ); }); }); }
riverpod/packages/riverpod/test/providers/stream_provider/stream_provider_family_test.dart/0
{'file_path': 'riverpod/packages/riverpod/test/providers/stream_provider/stream_provider_family_test.dart', 'repo_id': 'riverpod', 'token_count': 1529}
part of '../riverpod_ast.dart'; abstract class ProviderDeclaration extends RiverpodAst { Token get name; AnnotatedNode get node; ProviderDeclarationElement get providerElement; }
riverpod/packages/riverpod_analyzer_utils/lib/src/riverpod_ast/provider_declaration.dart/0
{'file_path': 'riverpod/packages/riverpod_analyzer_utils/lib/src/riverpod_ast/provider_declaration.dart', 'repo_id': 'riverpod', 'token_count': 53}
import 'dart:async'; import 'package:analyzer/dart/analysis/results.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/diagnostic/diagnostic.dart'; import 'package:build/build.dart'; import 'package:build_test/build_test.dart'; import 'package:meta/meta.dart'; import 'package:riverpod_analyzer_utils/riverpod_analyzer_utils.dart'; import 'package:riverpod_generator/src/riverpod_generator.dart'; import 'package:test/test.dart'; int _testNumber = 0; /// Due to [resolveSource] throwing if trying to interact with the resolver /// after the future completed, we change the syntax to make sure our test /// executes within the resolver scope. @isTest void testSource( String description, Future<void> Function(Resolver resolver) run, { required String source, Map<String, String> files = const {}, bool runGenerator = false, Timeout? timeout, }) { final testId = _testNumber++; test( description, timeout: timeout, () async { // Giving a unique name to the package to avoid the analyzer cache // messing up tests. final packageName = 'test_lib$testId'; final sourceWithLibrary = 'library foo;$source'; final enclosingZone = Zone.current; final otherSources = { for (final entry in files.entries) '$packageName|lib/${entry.key}': 'library "${entry.key}"; ${entry.value}', }; String? generated; if (runGenerator) { final analysisResult = await resolveSources( { '$packageName|lib/foo.dart': sourceWithLibrary, ...otherSources, }, (resolver) { return resolver.resolveRiverpodLibraryResult( ignoreErrors: true, ); }, ); generated = RiverpodGenerator(const {}).runGenerator(analysisResult); } await resolveSources({ '$packageName|lib/foo.dart': sourceWithLibrary, if (generated != null) '$packageName|lib/foo.g.dart': 'part of "foo.dart";$generated', ...otherSources, }, (resolver) async { try { final originalZone = Zone.current; return runZoned( () => run(resolver), zoneSpecification: ZoneSpecification( // Somehow prints are captured inside the callback. Let's restore them print: (self, parent, zone, line) => enclosingZone.print(line), handleUncaughtError: (self, parent, zone, error, stackTrace) { originalZone.handleUncaughtError(error, stackTrace); enclosingZone.handleUncaughtError(error, stackTrace); }, ), ); } catch (err, stack) { enclosingZone.handleUncaughtError(err, stack); } }); }, ); } extension MapTake<Key, Value> on Map<Key, Value> { Map<Key, Value> take(List<Key> keys) { return <Key, Value>{ for (final key in keys) if (!containsKey(key)) key: throw StateError('No key $key found') else key: this[key] as Value, }; } } extension ResolverX on Resolver { Future<RiverpodAnalysisResult> resolveRiverpodAnalysisResult({ String libraryName = 'foo', bool ignoreErrors = false, }) async { final riverpodAst = await resolveRiverpodLibraryResult( libraryName: libraryName, ignoreErrors: ignoreErrors, ); final result = RiverpodAnalysisResult(); riverpodAst.accept(result); if (!ignoreErrors) { final errors = result.resolvedRiverpodLibraryResults .expand((e) => e.errors) .toList(); if (errors.isNotEmpty) { throw StateError(errors.map((e) => '- $e\n').join()); } } return result; } Future<ResolvedRiverpodLibraryResult> resolveRiverpodLibraryResult({ String libraryName = 'foo', bool ignoreErrors = false, }) async { final library = await _requireFindLibraryByName( libraryName, ignoreErrors: ignoreErrors, ); final libraryAst = await library.session.getResolvedLibraryByElement(library); libraryAst as ResolvedLibraryResult; final result = ResolvedRiverpodLibraryResult.from( libraryAst.units.map((e) => e.unit).toList(), ); expectValidParentChildrenRelationship(result); return result; } Future<LibraryElement> _requireFindLibraryByName( String libraryName, { required bool ignoreErrors, }) async { final library = await findLibraryByName(libraryName); if (library == null) { throw StateError('No library found for name "$libraryName"'); } if (!ignoreErrors) { final errorResult = await library.session.getErrors('/test_lib/lib/foo.dart'); errorResult as ErrorsResult; final errors = errorResult.errors // Infos are only recommendations. There's no reason to fail just for this .where((e) => e.severity != Severity.info) .toList(); if (errors.isNotEmpty) { throw StateError(''' The parsed library has errors: ${errors.map((e) => '- $e\n').join()} '''); } } return library; } } /// Visit all the nodes of the AST and ensure that that all children /// have the correct parent. void expectValidParentChildrenRelationship( ResolvedRiverpodLibraryResult result, ) { result.accept(_ParentRiverpodVisitor(null)); } class _ParentRiverpodVisitor extends RecursiveRiverpodAstVisitor { _ParentRiverpodVisitor(this.expectedParent); final RiverpodAst? expectedParent; @override void visitProviderScopeInstanceCreationExpression( ProviderScopeInstanceCreationExpression declaration, ) { expect( declaration.parent, expectedParent, reason: 'Node ${declaration.runtimeType} should have $expectedParent as parent', ); declaration.visitChildren(_ParentRiverpodVisitor(declaration)); } @override void visitProviderContainerInstanceCreationExpression( ProviderContainerInstanceCreationExpression declaration, ) { expect( declaration.parent, expectedParent, reason: 'Node ${declaration.runtimeType} should have $expectedParent as parent', ); declaration.visitChildren(_ParentRiverpodVisitor(declaration)); } @override void visitConsumerStateDeclaration(ConsumerStateDeclaration declaration) { expect( declaration.parent, expectedParent, reason: 'Node ${declaration.runtimeType} should have $expectedParent as parent', ); declaration.visitChildren(_ParentRiverpodVisitor(declaration)); } @override void visitConsumerWidgetDeclaration(ConsumerWidgetDeclaration declaration) { expect( declaration.parent, expectedParent, reason: 'Node ${declaration.runtimeType} should have $expectedParent as parent', ); declaration.visitChildren(_ParentRiverpodVisitor(declaration)); } @override void visitLegacyProviderDeclaration(LegacyProviderDeclaration declaration) { expect( declaration.parent, expectedParent, reason: 'Node ${declaration.runtimeType} should have $expectedParent as parent', ); declaration.visitChildren(_ParentRiverpodVisitor(declaration)); } @override void visitLegacyProviderDependencies( LegacyProviderDependencies dependencies, ) { expect( dependencies.parent, expectedParent, reason: 'Node ${dependencies.runtimeType} should have $expectedParent as parent', ); dependencies.visitChildren(_ParentRiverpodVisitor(dependencies)); } @override void visitLegacyProviderDependency(LegacyProviderDependency dependency) { expect( dependency.parent, expectedParent, reason: 'Node ${dependency.runtimeType} should have $expectedParent as parent', ); dependency.visitChildren(_ParentRiverpodVisitor(dependency)); } @override void visitProviderListenableExpression( ProviderListenableExpression expression, ) { expect( expression.parent, expectedParent, reason: 'Node ${expression.runtimeType} should have $expectedParent as parent', ); expression.visitChildren(_ParentRiverpodVisitor(expression)); } @override void visitRefListenInvocation(RefListenInvocation invocation) { expect( invocation.parent, expectedParent, reason: 'Node ${invocation.runtimeType} should have $expectedParent as parent', ); invocation.visitChildren(_ParentRiverpodVisitor(invocation)); } @override void visitRefReadInvocation(RefReadInvocation invocation) { expect( invocation.parent, expectedParent, reason: 'Node ${invocation.runtimeType} should have $expectedParent as parent', ); invocation.visitChildren(_ParentRiverpodVisitor(invocation)); } @override void visitRefWatchInvocation(RefWatchInvocation invocation) { expect( invocation.parent, expectedParent, reason: 'Node ${invocation.runtimeType} should have $expectedParent as parent', ); invocation.visitChildren(_ParentRiverpodVisitor(invocation)); } @override void visitResolvedRiverpodUnit(ResolvedRiverpodLibraryResult result) { expect( result.parent, expectedParent, reason: 'Node ${result.runtimeType} should have $expectedParent as parent', ); result.visitChildren(_ParentRiverpodVisitor(result)); } @override void visitRiverpodAnnotation(RiverpodAnnotation annotation) { expect( annotation.parent, expectedParent, reason: 'Node ${annotation.runtimeType} should have $expectedParent as parent', ); annotation.visitChildren(_ParentRiverpodVisitor(annotation)); } @override void visitRiverpodAnnotationDependency( RiverpodAnnotationDependency dependency, ) { expect( dependency.parent, expectedParent, reason: 'Node ${dependency.runtimeType} should have $expectedParent as parent', ); dependency.visitChildren(_ParentRiverpodVisitor(dependency)); } @override void visitRiverpodAnnotationDependencies( RiverpodAnnotationDependencies dependencies, ) { expect( dependencies.parent, expectedParent, reason: 'Node ${dependencies.runtimeType} should have $expectedParent as parent', ); dependencies.visitChildren(_ParentRiverpodVisitor(dependencies)); } @override void visitConsumerStatefulWidgetDeclaration( ConsumerStatefulWidgetDeclaration declaration, ) { expect( declaration.parent, expectedParent, reason: 'Node ${declaration.runtimeType} should have $expectedParent as parent', ); declaration.visitChildren(_ParentRiverpodVisitor(declaration)); } @override void visitClassBasedProviderDeclaration( ClassBasedProviderDeclaration declaration, ) { expect( declaration.parent, expectedParent, reason: 'Node ${declaration.runtimeType} should have $expectedParent as parent', ); declaration.visitChildren(_ParentRiverpodVisitor(declaration)); } @override void visitFunctionalProviderDeclaration( FunctionalProviderDeclaration declaration, ) { expect( declaration.parent, expectedParent, reason: 'Node ${declaration.runtimeType} should have $expectedParent as parent', ); declaration.visitChildren(_ParentRiverpodVisitor(declaration)); } @override void visitWidgetRefListenInvocation(WidgetRefListenInvocation invocation) { expect( invocation.parent, expectedParent, reason: 'Node ${invocation.runtimeType} should have $expectedParent as parent', ); invocation.visitChildren(_ParentRiverpodVisitor(invocation)); } @override void visitWidgetRefListenManualInvocation( WidgetRefListenManualInvocation invocation, ) { expect( invocation.parent, expectedParent, reason: 'Node ${invocation.runtimeType} should have $expectedParent as parent', ); invocation.visitChildren(_ParentRiverpodVisitor(invocation)); } @override void visitWidgetRefReadInvocation(WidgetRefReadInvocation invocation) { expect( invocation.parent, expectedParent, reason: 'Node ${invocation.runtimeType} should have $expectedParent as parent', ); invocation.visitChildren(_ParentRiverpodVisitor(invocation)); } @override void visitWidgetRefWatchInvocation(WidgetRefWatchInvocation invocation) { expect( invocation.parent, expectedParent, reason: 'Node ${invocation.runtimeType} should have $expectedParent as parent', ); invocation.visitChildren(_ParentRiverpodVisitor(invocation)); } @override void visitHookConsumerWidgetDeclaration( HookConsumerWidgetDeclaration declaration, ) { expect( declaration.parent, expectedParent, reason: 'Node ${declaration.runtimeType} should have $expectedParent as parent', ); declaration.visitChildren(_ParentRiverpodVisitor(declaration)); } @override void visitStatefulHookConsumerWidgetDeclaration( StatefulHookConsumerWidgetDeclaration declaration, ) { expect( declaration.parent, expectedParent, reason: 'Node ${declaration.runtimeType} should have $expectedParent as parent', ); declaration.visitChildren(_ParentRiverpodVisitor(declaration)); } } class RiverpodAnalysisResult extends RecursiveRiverpodAstVisitor { final providerContainerInstanceCreationExpressions = <ProviderContainerInstanceCreationExpression>[]; @override void visitProviderContainerInstanceCreationExpression( ProviderContainerInstanceCreationExpression expression, ) { super.visitProviderContainerInstanceCreationExpression(expression); providerContainerInstanceCreationExpressions.add(expression); } final providerScopeInstanceCreationExpressions = <ProviderScopeInstanceCreationExpression>[]; @override void visitProviderScopeInstanceCreationExpression( ProviderScopeInstanceCreationExpression expression, ) { super.visitProviderScopeInstanceCreationExpression(expression); providerScopeInstanceCreationExpressions.add(expression); } final consumerStateDeclarations = <ConsumerStateDeclaration>[]; @override void visitConsumerStateDeclaration(ConsumerStateDeclaration declaration) { super.visitConsumerStateDeclaration(declaration); consumerStateDeclarations.add(declaration); } final consumerWidgetDeclarations = <ConsumerWidgetDeclaration>[]; @override void visitConsumerWidgetDeclaration(ConsumerWidgetDeclaration declaration) { super.visitConsumerWidgetDeclaration(declaration); consumerWidgetDeclarations.add(declaration); } final hookConsumerWidgetDeclaration = <HookConsumerWidgetDeclaration>[]; @override void visitHookConsumerWidgetDeclaration( HookConsumerWidgetDeclaration declaration, ) { super.visitHookConsumerWidgetDeclaration(declaration); hookConsumerWidgetDeclaration.add(declaration); } final statefulHookConsumerWidgetDeclaration = <StatefulHookConsumerWidgetDeclaration>[]; @override void visitStatefulHookConsumerWidgetDeclaration( StatefulHookConsumerWidgetDeclaration declaration, ) { super.visitStatefulHookConsumerWidgetDeclaration(declaration); statefulHookConsumerWidgetDeclaration.add(declaration); } final legacyProviderDeclarations = <LegacyProviderDeclaration>[]; @override void visitLegacyProviderDeclaration(LegacyProviderDeclaration declaration) { super.visitLegacyProviderDeclaration(declaration); legacyProviderDeclarations.add(declaration); } final legacyProviderDependencies = <LegacyProviderDependencies>[]; @override void visitLegacyProviderDependencies( LegacyProviderDependencies dependencies, ) { super.visitLegacyProviderDependencies(dependencies); legacyProviderDependencies.add(dependencies); } final legacyProviderDependencyList = <LegacyProviderDependency>[]; @override void visitLegacyProviderDependency(LegacyProviderDependency dependency) { super.visitLegacyProviderDependency(dependency); legacyProviderDependencyList.add(dependency); } final providerListenableExpressions = <ProviderListenableExpression>[]; @override void visitProviderListenableExpression( ProviderListenableExpression expression, ) { super.visitProviderListenableExpression(expression); providerListenableExpressions.add(expression); } final refInvocations = <RefInvocation>[]; final refListenInvocations = <RefListenInvocation>[]; @override void visitRefListenInvocation(RefListenInvocation invocation) { super.visitRefListenInvocation(invocation); refInvocations.add(invocation); refListenInvocations.add(invocation); } final refReadInvocations = <RefReadInvocation>[]; @override void visitRefReadInvocation(RefReadInvocation invocation) { super.visitRefReadInvocation(invocation); refInvocations.add(invocation); refReadInvocations.add(invocation); } final refWatchInvocations = <RefWatchInvocation>[]; @override void visitRefWatchInvocation(RefWatchInvocation invocation) { super.visitRefWatchInvocation(invocation); refInvocations.add(invocation); refWatchInvocations.add(invocation); } final resolvedRiverpodLibraryResults = <ResolvedRiverpodLibraryResult>[]; @override void visitResolvedRiverpodUnit(ResolvedRiverpodLibraryResult result) { super.visitResolvedRiverpodUnit(result); resolvedRiverpodLibraryResults.add(result); } final riverpodAnnotations = <RiverpodAnnotation>[]; @override void visitRiverpodAnnotation(RiverpodAnnotation annotation) { super.visitRiverpodAnnotation(annotation); riverpodAnnotations.add(annotation); } final riverpodAnnotationDependencyList = <RiverpodAnnotationDependency>[]; @override void visitRiverpodAnnotationDependency( RiverpodAnnotationDependency dependency, ) { super.visitRiverpodAnnotationDependency(dependency); riverpodAnnotationDependencyList.add(dependency); } final riverpodAnnotationDependencies = <RiverpodAnnotationDependencies>[]; @override void visitRiverpodAnnotationDependencies( RiverpodAnnotationDependencies dependencies, ) { super.visitRiverpodAnnotationDependencies(dependencies); riverpodAnnotationDependencies.add(dependencies); } final consumerStatefulWidgetDeclarations = <ConsumerStatefulWidgetDeclaration>[]; @override void visitConsumerStatefulWidgetDeclaration( ConsumerStatefulWidgetDeclaration declaration, ) { super.visitConsumerStatefulWidgetDeclaration(declaration); consumerStatefulWidgetDeclarations.add(declaration); } final generatorProviderDeclarations = <GeneratorProviderDeclaration>[]; final classBasedProviderDeclarations = <ClassBasedProviderDeclaration>[]; @override void visitClassBasedProviderDeclaration( ClassBasedProviderDeclaration declaration, ) { super.visitClassBasedProviderDeclaration(declaration); generatorProviderDeclarations.add(declaration); classBasedProviderDeclarations.add(declaration); } final functionalProviderDeclarations = <FunctionalProviderDeclaration>[]; @override void visitFunctionalProviderDeclaration( FunctionalProviderDeclaration declaration, ) { super.visitFunctionalProviderDeclaration(declaration); generatorProviderDeclarations.add(declaration); functionalProviderDeclarations.add(declaration); } final widgetRefInvocations = <WidgetRefInvocation>[]; final widgetRefListenInvocations = <WidgetRefListenInvocation>[]; @override void visitWidgetRefListenInvocation(WidgetRefListenInvocation invocation) { super.visitWidgetRefListenInvocation(invocation); widgetRefInvocations.add(invocation); widgetRefListenInvocations.add(invocation); } final widgetRefListenManualInvocations = <WidgetRefListenManualInvocation>[]; @override void visitWidgetRefListenManualInvocation( WidgetRefListenManualInvocation invocation, ) { super.visitWidgetRefListenManualInvocation(invocation); widgetRefInvocations.add(invocation); widgetRefListenManualInvocations.add(invocation); } final widgetRefReadInvocations = <WidgetRefReadInvocation>[]; @override void visitWidgetRefReadInvocation(WidgetRefReadInvocation invocation) { super.visitWidgetRefReadInvocation(invocation); widgetRefInvocations.add(invocation); widgetRefReadInvocations.add(invocation); } final widgetRefWatchInvocations = <WidgetRefWatchInvocation>[]; @override void visitWidgetRefWatchInvocation(WidgetRefWatchInvocation invocation) { super.visitWidgetRefWatchInvocation(invocation); widgetRefInvocations.add(invocation); widgetRefWatchInvocations.add(invocation); } } extension TakeList<T extends ProviderDeclaration> on List<T> { Map<String, T> takeAll(List<String> names) { final result = Map.fromEntries(map((e) => MapEntry(e.name.lexeme, e))); return result.take(names); } T findByName(String name) { return singleWhere((element) => element.name.lexeme == name); } } extension LibraryElementX on LibraryElement { Element findElementWithName(String name) { return topLevelElements.singleWhere( (element) => !element.isSynthetic && element.name == name, orElse: () => throw StateError('No element found with name "$name"'), ); } }
riverpod/packages/riverpod_analyzer_utils_tests/test/analyzer_test_utils.dart/0
{'file_path': 'riverpod/packages/riverpod_analyzer_utils_tests/test/analyzer_test_utils.dart', 'repo_id': 'riverpod', 'token_count': 7294}
name: codemod_riverpod_test_unified_syntax_golden description: Test riverpod codemods publish_to: none environment: sdk: ">=2.12.0-0 <3.0.0" dependencies: flutter: sdk: flutter flutter_hooks: flutter_riverpod: hooks_riverpod: riverpod:
riverpod/packages/riverpod_cli/fixtures/unified_syntax/golden/pubspec.yaml/0
{'file_path': 'riverpod/packages/riverpod_cli/fixtures/unified_syntax/golden/pubspec.yaml', 'repo_id': 'riverpod', 'token_count': 108}
import 'package:codemod/test.dart'; import 'package:riverpod_cli/src/migrate/imports.dart'; import 'package:test/test.dart'; void main() { group('ImportAllRenamer', () { test('renames imports', () async { final sourceFile = await fileContextForTest( 'test.dart', ''' // Don't touch path import 'package:path/path.dart'; // Changes required import 'package:riverpod/all.dart'; import 'package:hooks_riverpod/all.dart'; import 'package:flutter_riverpod/all.dart'; // With double quotes import "package:flutter_riverpod/all.dart"; ''', ); const expectedOutput = ''' // Don't touch path import 'package:path/path.dart'; // Changes required import 'package:riverpod/riverpod.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; // With double quotes import "package:flutter_riverpod/flutter_riverpod.dart"; '''; expectSuggestorGeneratesPatches( RiverpodImportAllMigrationSuggestor().call, sourceFile, expectedOutput, ); }); }); }
riverpod/packages/riverpod_cli/test/imports_test.dart/0
{'file_path': 'riverpod/packages/riverpod_cli/test/imports_test.dart', 'repo_id': 'riverpod', 'token_count': 405}
import 'package:build_verify/build_verify.dart'; import 'package:build_yaml/main.dart'; import 'package:test/test.dart'; void main() { test( 'ensure_build', () => expectBuildClean( packageRelativeDirectory: 'packages/riverpod_generator/integration/build_yaml', ), timeout: const Timeout(Duration(minutes: 1)), ); test('provider names', () { expect(countPod.name, 'countPod'); expect(countFuturePod.name, 'countFuturePod'); expect(countStreamPod.name, 'countStreamPod'); expect(countNotifierPod.name, 'countNotifierPod'); expect(countAsyncNotifierPod.name, 'countAsyncNotifierPod'); expect(countStreamNotifierPod.name, 'countStreamNotifierPod'); }); test('provider family names', () { expect(count2ProviderFamily.name, 'count2ProviderFamily'); expect(countFuture2ProviderFamily.name, 'countFuture2ProviderFamily'); expect(countStream2ProviderFamily.name, 'countStream2ProviderFamily'); expect(countNotifier2ProviderFamily.name, 'countNotifier2ProviderFamily'); expect( countAsyncNotifier2ProviderFamily.name, 'countAsyncNotifier2ProviderFamily', ); expect( countStreamNotifier2ProviderFamily.name, 'countStreamNotifier2ProviderFamily', ); }); }
riverpod/packages/riverpod_generator/integration/build_yaml/test/build_yaml_test.dart/0
{'file_path': 'riverpod/packages/riverpod_generator/integration/build_yaml/test/build_yaml_test.dart', 'repo_id': 'riverpod', 'token_count': 445}
import 'package:riverpod_generator/src/models.dart'; import 'package:test/test.dart'; void main() { test('custom suffix', () async { const map = {'provider_name_suffix': 'Pod'}; final options = BuildYamlOptions.fromMap(map); expect(options.providerNameSuffix, 'Pod'); }); test('custom family suffix', () async { const map = {'provider_family_name_suffix': 'ProviderFamily'}; final options = BuildYamlOptions.fromMap(map); expect(options.providerFamilyNameSuffix, 'ProviderFamily'); }); }
riverpod/packages/riverpod_generator/test/build_yaml_config_test.dart/0
{'file_path': 'riverpod/packages/riverpod_generator/test/build_yaml_config_test.dart', 'repo_id': 'riverpod', 'token_count': 182}
// Regresion test for https://github.com/rrousselGit/riverpod/issues/2175 import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'split2.dart'; part 'split.g.dart'; @riverpod int counter2(Counter2Ref ref) => 0;
riverpod/packages/riverpod_generator/test/integration/split.dart/0
{'file_path': 'riverpod/packages/riverpod_generator/test/integration/split.dart', 'repo_id': 'riverpod', 'token_count': 84}
export 'package:riverpod_graph/src/analyze.dart' show analyze;
riverpod/packages/riverpod_graph/lib/riverpod_graph.dart/0
{'file_path': 'riverpod/packages/riverpod_graph/lib/riverpod_graph.dart', 'repo_id': 'riverpod', 'token_count': 21}
import 'package:analyzer/error/listener.dart'; import 'package:custom_lint_builder/custom_lint_builder.dart'; class AvoidExposingProviderRef extends DartLintRule { const AvoidExposingProviderRef() : super(code: _code); static const _code = LintCode( name: 'avoid_exposing_provider_ref', problemMessage: 'The "ref" of a provider should not be accessible from outside of the ' 'provider and its internals.', ); @override void run( CustomLintResolver resolver, ErrorReporter reporter, CustomLintContext context, ) { // TODO: implement run } }
riverpod/packages/riverpod_lint/lib/src/legacy_backup/avoid_exposing_provider_ref.dart/0
{'file_path': 'riverpod/packages/riverpod_lint/lib/src/legacy_backup/avoid_exposing_provider_ref.dart', 'repo_id': 'riverpod', 'token_count': 209}
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:custom_lint_builder/custom_lint_builder.dart'; import 'package:riverpod_analyzer_utils/riverpod_analyzer_utils.dart'; import '../riverpod_custom_lint.dart'; const _buildMethodName = 'build'; class NotifierBuild extends RiverpodLintRule { const NotifierBuild() : super(code: _code); static const _code = LintCode( name: 'notifier_build', problemMessage: 'Classes annotated by `@riverpod` must have the `build` method', ); @override void run( CustomLintResolver resolver, ErrorReporter reporter, CustomLintContext context, ) { context.registry.addClassDeclaration((node) { final hasRiverpodAnnotation = node.metadata.where( (element) { final annotationElement = element.element; if (annotationElement == null || annotationElement is! ExecutableElement) return false; return riverpodType.isExactlyType(annotationElement.returnType); }, ).isNotEmpty; if (!hasRiverpodAnnotation) return; final hasBuildMethod = node.members .where((e) => e.declaredElement?.displayName == _buildMethodName) .isNotEmpty; if (hasBuildMethod) return; reporter.reportErrorForToken(_code, node.name); }); } @override List<RiverpodFix> getFixes() => [ AddBuildMethodFix(), ]; } class AddBuildMethodFix extends RiverpodFix { @override void run( CustomLintResolver resolver, ChangeReporter reporter, CustomLintContext context, AnalysisError analysisError, List<AnalysisError> others, ) { context.registry.addClassDeclaration((node) { if (!node.sourceRange.intersects(analysisError.sourceRange)) return; final changeBuilder = reporter.createChangeBuilder( message: 'Add build method', priority: 80, ); changeBuilder.addDartFileEdit((builder) { final offset = node.leftBracket.offset + 1; builder.addSimpleInsertion( offset, ''' @override dynamic build() { // TODO: implement build throw UnimplementedError(); } ''', ); }); }); } }
riverpod/packages/riverpod_lint/lib/src/lints/notifier_build.dart/0
{'file_path': 'riverpod/packages/riverpod_lint/lib/src/lints/notifier_build.dart', 'repo_id': 'riverpod', 'token_count': 879}
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'avoid_public_notifier_properties.g.dart'; class MyNotifier extends Notifier<int> { static int get staticPublicGetter => 0; static int staticPublicProperty = 0; int _privateProperty = 0; int get _privateGetter => _privateProperty; // expect_lint: avoid_public_notifier_properties int get publicGetter => _privateGetter; // Public setters are OK set publicSetter(int value) { _privateProperty = value; } // expect_lint: avoid_public_notifier_properties int publicProperty = 0; @protected int get protectedMember => 0; @visibleForTesting int get visibleForTestingMember => 0; @visibleForOverriding int get visibleForOverridingMember => 0; @override int build() => 0; void _privateMethod() {} // Public methods are OK void publicMethod() { _privateMethod(); } } class MyAutoDisposeNotifier extends AutoDisposeNotifier<int> { int get _privateGetter => 0; // expect_lint: avoid_public_notifier_properties int get publicGetter => _privateGetter; @override int build() => 0; } class MyAutoDisposeFamilyNotifier extends AutoDisposeFamilyNotifier<int, int> { int get _privateGetter => 0; // expect_lint: avoid_public_notifier_properties int get publicGetter => _privateGetter; @override int build(int param) => 0; } class MyAsyncNotifier extends AsyncNotifier<int> { int get _privateGetter => 0; // expect_lint: avoid_public_notifier_properties int get publicGetter => _privateGetter; @override Future<int> build() async => 0; } class MyAutoDisposeAsyncNotifier extends AutoDisposeAsyncNotifier<int> { int get _privateGetter => 0; // expect_lint: avoid_public_notifier_properties int get publicGetter => _privateGetter; @override Future<int> build() async => 0; } class MyAutoDisposeFamilyAsyncNotifier extends AutoDisposeFamilyAsyncNotifier<int, int> { int get _privateGetter => 0; // expect_lint: avoid_public_notifier_properties int get publicGetter => _privateGetter; @override Future<int> build(int param) async => 0; } // Regression test for https://github.com/rrousselGit/riverpod/discussions/2642 @riverpod class GeneratedNotifier extends _$GeneratedNotifier { @override int build(int param) { return 0; } }
riverpod/packages/riverpod_lint_flutter_test/test/lints/avoid_public_notifier_properties.dart/0
{'file_path': 'riverpod/packages/riverpod_lint_flutter_test/test/lints/avoid_public_notifier_properties.dart', 'repo_id': 'riverpod', 'token_count': 791}
import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'protected_notifier_properties.g.dart'; @riverpod class A extends _$A { @override int build() => 0; } @Riverpod(keepAlive: true) class A2 extends _$A2 { @override int build() => 0; } @riverpod class A3 extends _$A3 { @override int build(int param) => 0; } @Riverpod(keepAlive: true) class A4 extends _$A4 { @override int build(int param) => 0; } @riverpod class A5 extends _$A5 { @override Future<int> build(int param) async => 0; } @Riverpod(keepAlive: true) class A6 extends _$A6 { @override Future<int> build(int param) async => 0; } @riverpod class A7 extends _$A7 { @override Stream<int> build(int param) => Stream.empty(); } @Riverpod(keepAlive: true) class A8 extends _$A8 { @override Stream<int> build(int param) => Stream.empty(); } @Riverpod(keepAlive: true) class B extends _$B { @override int build() => 0; void increment() { final obj = Obj(); obj.state++; this.state = 42; // expect_lint: protected_notifier_properties ref.read(aProvider.notifier).state = 42; // expect_lint: protected_notifier_properties ref.read(aProvider.notifier).state++; // expect_lint: protected_notifier_properties ref.read(a2Provider.notifier).state++; // expect_lint: protected_notifier_properties ref.read(a3Provider(42).notifier).state++; // expect_lint: protected_notifier_properties ref.read(a4Provider(42).notifier).state++; // expect_lint: protected_notifier_properties ref.read(a5Provider(42).notifier).state = AsyncData(42); // expect_lint: protected_notifier_properties ref.read(a6Provider(42).notifier).state = AsyncData(42); // expect_lint: protected_notifier_properties ref.read(a7Provider(42).notifier).state = AsyncData(42); // expect_lint: protected_notifier_properties ref.read(a8Provider(42).notifier).state = AsyncData(42); // expect_lint: protected_notifier_properties ref.read(a8Provider(42).notifier).state; // expect_lint: protected_notifier_properties ref.read(a8Provider(42).notifier).future; // expect_lint: protected_notifier_properties ref.read(a8Provider(42).notifier).ref; } } @riverpod class B2 extends _$B2 { @override int build() => 0; void increment() { final obj = Obj(); obj.state++; this.state = 42; // expect_lint: protected_notifier_properties ref.read(aProvider.notifier).state++; // expect_lint: protected_notifier_properties ref.read(a2Provider.notifier).state++; // expect_lint: protected_notifier_properties ref.read(a3Provider(42).notifier).state++; // expect_lint: protected_notifier_properties ref.read(a4Provider(42).notifier).state++; // expect_lint: protected_notifier_properties ref.read(a5Provider(42).notifier).state = AsyncData(42); // expect_lint: protected_notifier_properties ref.read(a6Provider(42).notifier).state = AsyncData(42); // expect_lint: protected_notifier_properties ref.read(a7Provider(42).notifier).state = AsyncData(42); // expect_lint: protected_notifier_properties ref.read(a8Provider(42).notifier).state = AsyncData(42); } } class Obj { int state = 0; }
riverpod/packages/riverpod_lint_flutter_test/test/lints/protected_notifier_properties.dart/0
{'file_path': 'riverpod/packages/riverpod_lint_flutter_test/test/lints/protected_notifier_properties.dart', 'repo_id': 'riverpod', 'token_count': 1226}
// ignore_for_file: unused_local_variable import 'package:http/http.dart' as http; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../cache_for_extension.dart'; /* SNIPPET START */ final provider = FutureProvider.autoDispose<Object>((ref) async { /// Keeps the state alive for 5 minutes ref.cacheFor(const Duration(minutes: 5)); return http.get(Uri.https('example.com')); }); /* SNIPPET END */
riverpod/website/docs/essentials/auto_dispose/cache_for_usage/raw.dart/0
{'file_path': 'riverpod/website/docs/essentials/auto_dispose/cache_for_usage/raw.dart', 'repo_id': 'riverpod', 'token_count': 142}
import 'package:riverpod_annotation/riverpod_annotation.dart'; /* SNIPPET START */ // We can specify autoDispose to enable automatic state destruction. final provider = Provider.autoDispose<int>((ref) { return 0; });
riverpod/website/docs/essentials/auto_dispose/raw_auto_dispose.dart/0
{'file_path': 'riverpod/website/docs/essentials/auto_dispose/raw_auto_dispose.dart', 'repo_id': 'riverpod', 'token_count': 65}
// ignore_for_file: omit_local_variable_types, unused_local_variable, prefer_final_locals import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'tuple_family.dart'; class Example extends ConsumerWidget { const Example({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { /* SNIPPET START */ ref.watch( // Using a Record, we can pass our parameters. // It is fine to create the record directly // in the watch call as records override ==. activityProvider((type: 'recreational', maxPrice: 40)), ); /* SNIPPET END */ return Container(); } }
riverpod/website/docs/essentials/passing_args/raw/consumer_tuple_family.dart/0
{'file_path': 'riverpod/website/docs/essentials/passing_args/raw/consumer_tuple_family.dart', 'repo_id': 'riverpod', 'token_count': 220}
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../raw/todo_list_notifier.dart' show Todo; import '../raw/todo_list_notifier_add_todo.dart'; /* SNIPPET START */ class Example extends ConsumerWidget { const Example({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { return ElevatedButton( onPressed: () { // Using "ref.read" combined with "myProvider.notifier", we can // obtain the class instance of our notifier. This enables us // to call the "addTodo" method. ref .read(todoListProvider.notifier) .addTodo(Todo(description: 'This is a new todo')); }, child: const Text('Add todo'), ); } }
riverpod/website/docs/essentials/side_effects/raw/consumer_add_todo_call.dart/0
{'file_path': 'riverpod/website/docs/essentials/side_effects/raw/consumer_add_todo_call.dart', 'repo_id': 'riverpod', 'token_count': 304}
// ignore_for_file: unused_local_variable import 'package:flutter_test/flutter_test.dart'; import 'package:riverpod/riverpod.dart'; import 'create_container.dart'; final provider = FutureProvider((_) async => 42); void main() { test('Some description', () async { // Create a ProviderContainer for this test. // DO NOT share ProviderContainers between tests. final container = createContainer(); /* SNIPPET START */ // TODO: use the container to test your application. // Our expectation is asynchronous, so we should use "expectLater" await expectLater( // We read "provider.future" instead of "provider". // This is possible on asynchronous providers, and returns a future // which will resolve with the value of the provider. container.read(provider.future), // We can verify that the future resolves with the expected value. // Alternatively we can use "throwsA" for errors. completion('some value'), ); /* SNIPPET END */ }); }
riverpod/website/docs/essentials/testing/await_future.dart/0
{'file_path': 'riverpod/website/docs/essentials/testing/await_future.dart', 'repo_id': 'riverpod', 'token_count': 317}
import 'dart:math'; import 'package:riverpod_annotation/riverpod_annotation.dart'; /* SNIPPET START */ final diceRollProvider = Provider.autoDispose((ref) { // Since this provider is .autoDispose, un-listening to it will dispose // its current exposed state. // Then, whenever this provider is listened to again, // a new dice will be rolled and exposed again. final dice = Random().nextInt(10); return dice.isEven; }); final cachedDiceRollProvider = Provider.autoDispose((ref) { final coin = Random().nextInt(10); if (coin > 5) throw Exception('Way too large.'); // The above condition might fail; // If it doesn't, the following instruction tells the Provider // to keep its cached state, *even when no one listens to it anymore*. ref.keepAlive(); return coin.isEven; });
riverpod/website/docs/from_provider/motivation/auto_dispose/raw.dart/0
{'file_path': 'riverpod/website/docs/from_provider/motivation/auto_dispose/raw.dart', 'repo_id': 'riverpod', 'token_count': 235}
// ignore_for_file: omit_local_variable_types import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; /* SNIPPET START */ final counterProvider = StateProvider((ref) => 0); Widget build(BuildContext context, WidgetRef ref) { // "read" ব্যবহার করুন একটি প্রভাইডার এর আপডেট এড়িয়ে যাওয়ার জন্যে final counter = ref.read(counterProvider.notifier); return ElevatedButton( onPressed: () => counter.state++, child: const Text('button'), ); }
riverpod/website/i18n/bn/docusaurus-plugin-content-docs/current/concepts/reading_read_build.dart/0
{'file_path': 'riverpod/website/i18n/bn/docusaurus-plugin-content-docs/current/concepts/reading_read_build.dart', 'repo_id': 'riverpod', 'token_count': 258}
// ignore_for_file: avoid_print /* SNIPPET START */ import 'package:riverpod/riverpod.dart'; // আমরা একটি "প্রভাইডার" তৈরি করি, যা একটি মান সংরক্ষণ করবে (এখানে "Hello World")। // একটি প্রভাইডার ব্যবহার করে, এটি আমাদের উন্মুক্ত মানকে মক/ওভাররাইড করতে দেয়। final helloWorldProvider = Provider((_) => 'Hello world'); void main() { // এখানে আমাদের প্রভাইডারদের স্টেট সংরক্ষণ করা হবে। final container = ProviderContainer(); // ধন্যবাদ "container" কে, যেটি আমাদের প্রভাইডারসগুলা পড়তে দেই. final value = container.read(helloWorldProvider); print(value); // Hello world }
riverpod/website/i18n/bn/docusaurus-plugin-content-docs/current/getting_started_hello_world_dart.dart/0
{'file_path': 'riverpod/website/i18n/bn/docusaurus-plugin-content-docs/current/getting_started_hello_world_dart.dart', 'repo_id': 'riverpod', 'token_count': 571}
// ignore_for_file: omit_local_variable_types, prefer_final_locals import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'todos.dart'; /* SNIPPET START */ class TodoListView extends ConsumerWidget { const TodoListView({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { // উইজেট রিবিল্ট হবে যখন টুডু লিস্ট চ্যাঞ্জ হবে List<Todo> todos = ref.watch(todosProvider); // আসুন একটি স্ক্রোলযোগ্য ListView-তে todos রেন্ডার করি return ListView( children: [ for (final todo in todos) CheckboxListTile( value: todo.completed, // টোডোতে ট্যাপ করার সময়, এর স্টেট পরিবর্তন করুন কমপ্লিট স্ট্যাটাস এ onChanged: (value) => ref.read(todosProvider.notifier).toggle(todo.id), title: Text(todo.description), ), ], ); } }
riverpod/website/i18n/bn/docusaurus-plugin-content-docs/current/providers/state_notifier_provider/todos_consumer.dart/0
{'file_path': 'riverpod/website/i18n/bn/docusaurus-plugin-content-docs/current/providers/state_notifier_provider/todos_consumer.dart', 'repo_id': 'riverpod', 'token_count': 642}
// A provider that controls the current page import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; /* SNIPPET START */ final pageIndexProvider = StateProvider<int>((ref) => 0); // Un provider que calcula si el usuario puede ir a la página anterior /* highlight-start */ final canGoToPreviousPageProvider = Provider<bool>((ref) { /* highlight-end */ return ref.watch(pageIndexProvider) > 0; }); class PreviousButton extends ConsumerWidget { const PreviousButton({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { // Ahora estamos viendo nuestro nuevo Provider // Nuestro widget ya no calcula si podemos ir a la página anterior. /* highlight-start */ final canGoToPreviousPage = ref.watch(canGoToPreviousPageProvider); /* highlight-end */ void goToPreviousPage() { ref.read(pageIndexProvider.notifier).update((state) => state - 1); } return ElevatedButton( onPressed: canGoToPreviousPage ? goToPreviousPage : null, child: const Text('previous'), ); } }
riverpod/website/i18n/es/docusaurus-plugin-content-docs/current/providers/provider/optimized_previous_button.dart/0
{'file_path': 'riverpod/website/i18n/es/docusaurus-plugin-content-docs/current/providers/provider/optimized_previous_button.dart', 'repo_id': 'riverpod', 'token_count': 352}
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; /* SNIPPET START */ final counterProvider = StateProvider<int>((ref) => 0); class HomeView extends ConsumerWidget { const HomeView({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { return Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { // Estamos actualizando el estado del valor anterior, terminamos leyendo // el provider ¡dos veces! ref.read(counterProvider.notifier).state = ref.read(counterProvider.notifier).state + 1; }, ), ); } }
riverpod/website/i18n/es/docusaurus-plugin-content-docs/current/providers/state_provider/update_read_twice.dart/0
{'file_path': 'riverpod/website/i18n/es/docusaurus-plugin-content-docs/current/providers/state_provider/update_read_twice.dart', 'repo_id': 'riverpod', 'token_count': 248}
// ignore_for_file: unused_local_variable import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'reading_counter.dart'; /* SNIPPET START */ class HomeView extends StatefulHookConsumerWidget { const HomeView({super.key}); @override HomeViewState createState() => HomeViewState(); } class HomeViewState extends ConsumerState<HomeView> { @override void initState() { super.initState(); // "ref" peut être utilisé dans tous les cycles de vie d'un StatefulWidget. ref.read(counterProvider); } @override Widget build(BuildContext context) { // Comme HookConsumerWidget, nous pouvons utiliser des hooks à l'intérieur du constructeur. final state = useState(0); // Nous pouvons également utiliser "ref" pour écouter un provider dans la méthode build. final counter = ref.watch(counterProvider); return Text('$counter'); } }
riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/concepts/reading_stateful_hook_consumer_widget.dart/0
{'file_path': 'riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/concepts/reading_stateful_hook_consumer_widget.dart', 'repo_id': 'riverpod', 'token_count': 331}
name: my_app_name environment: sdk: ">=2.17.0 <3.0.0" flutter: ">=3.0.0" dependencies: flutter: sdk: flutter flutter_hooks: ^0.18.0 hooks_riverpod: ^2.1.1 riverpod_annotation: ^1.0.6 dev_dependencies: build_runner: riverpod_generator: ^1.0.6
riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/getting_started/pubspec/hooks_codegen.yaml/0
{'file_path': 'riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/getting_started/pubspec/hooks_codegen.yaml', 'repo_id': 'riverpod', 'token_count': 131}
// ignore_for_file: unused_local_variable import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'completed_todos.dart'; Widget build() { /* SNIPPET START */ return Consumer(builder: (context, ref, child) { final completedTodos = ref.watch(completedTodosProvider); // TODO afficher les todos en utilisant un ListView/GridView/... /* SKIP */ return Container(); /* SKIP END */ }); /* SNIPPET END */ }
riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/providers/provider/todos_consumer.dart/0
{'file_path': 'riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/providers/provider/todos_consumer.dart', 'repo_id': 'riverpod', 'token_count': 169}
// ignore_for_file: unused_local_variable import 'package:http/http.dart' as http; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../cache_for_extension.dart'; part 'codegen.g.dart'; /* SNIPPET START */ @riverpod Future<Object> example(ExampleRef ref) async { // Mantiene lo stato attivo per 5 minuti ref.cacheFor(const Duration(minutes: 5)); return http.get(Uri.https('example.com')); }
riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/auto_dispose/cache_for_usage/codegen.dart/0
{'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/auto_dispose/cache_for_usage/codegen.dart', 'repo_id': 'riverpod', 'token_count': 150}
// ignore_for_file: unused_local_variable, use_key_in_widget_constructors import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; final myProvider = Provider<int>((ref) => 0); /* SNIPPET START */ void main() { runApp(ProviderScope(child: MyApp())); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return const _EagerInitialization( // TODO: Renderizza la tua app qui child: MaterialApp(), ); } } class _EagerInitialization extends ConsumerWidget { const _EagerInitialization({required this.child}); final Widget child; @override Widget build(BuildContext context, WidgetRef ref) { // Inizializza anticipatamente i provider osservandoli. // Usando "watch", il provider resterà in vita e non sarà distrutto. ref.watch(myProvider); return child; } } /* SNIPPET END */
riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/eager_initialization/consumer_example.dart/0
{'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/eager_initialization/consumer_example.dart', 'repo_id': 'riverpod', 'token_count': 311}
// ignore_for_file: omit_local_variable_types, unused_local_variable, prefer_final_locals import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../first_request/raw/activity.dart'; import 'family.dart'; class Example extends ConsumerWidget { const Example({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { /* SNIPPET START */ AsyncValue<Activity> activity = ref.watch( // Il provider è ora una funzione che si aspetta il tipo dell'attività // Passiamo una costante stringa per ora, per semplicità. activityProvider('recreational'), ); /* SNIPPET END */ return Container(); } }
riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/passing_args/raw/consumer_family.dart/0
{'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/passing_args/raw/consumer_family.dart', 'repo_id': 'riverpod', 'token_count': 244}
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'todo_list_provider.freezed.dart'; part 'todo_list_provider.g.dart'; @freezed class Todo with _$Todo { factory Todo({ required String description, @Default(false) bool completed, }) = _Todo; } /* SNIPPET START */ @riverpod Future<List<Todo>> todoList(TodoListRef ref) async { // Simula una richiesta di rete. Normalmente il risultato dovrebbe venire da una API reale return [ Todo(description: 'Learn Flutter', completed: true), Todo(description: 'Learn Riverpod'), ]; }
riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/side_effects/codegen/todo_list_provider.dart/0
{'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/side_effects/codegen/todo_list_provider.dart', 'repo_id': 'riverpod', 'token_count': 230}
// ignore_for_file: unused_local_variable import 'package:flutter_test/flutter_test.dart'; import 'package:riverpod/riverpod.dart'; import 'create_container.dart'; final provider = Provider((_) => 42); /* SNIPPET START */ void main() { test('Some description', () { // Crea un ProviderContainer per questo test. // NON condividere dei ProviderContainer tra i test. final container = createContainer(); // TODO: usare il container per testare la tua applicazione. expect( container.read(provider), equals('some value'), ); }); }
riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/testing/unit_test.dart/0
{'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/testing/unit_test.dart', 'repo_id': 'riverpod', 'token_count': 196}
// ignore_for_file: unused_local_variable import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'reading_counter.dart'; class HomeView extends HookConsumerWidget { const HomeView({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { return /* SNIPPET START */ Scaffold( body: HookConsumer( builder: (context, ref, child) { // HookConsumerWidget と同様にフックが使えます。 final state = useState(0); // `ref` オブジェクトを使ってプロバイダを監視することもできます。 final counter = ref.watch(counterProvider); return Text('$counter'); }, ), ); /* SNIPPET END */ } }
riverpod/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/reading_consumer_hook.dart/0
{'file_path': 'riverpod/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/reading_consumer_hook.dart', 'repo_id': 'riverpod', 'token_count': 285}
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; class MyApp extends StatelessWidget { // ignore: prefer_const_constructors_in_immutables MyApp({super.key}); @override Widget build(BuildContext context) { return Container(); } } final repositoryProvider = Provider((ref) => FakeRepository()); class FakeRepository {} void main() { /* SNIPPET START */ testWidgets('override repositoryProvider', (tester) async { await tester.pumpWidget( ProviderScope( overrides: [ // repositoryProvider の挙動をオーバーライドして // Repository の代わりに FakeRepository を戻り値とする /* highlight-start */ repositoryProvider.overrideWithValue(FakeRepository()) /* highlight-end */ // `todoListProvider` はオーバーライドされた repositoryProvider を // 自動的に利用することになるため、オーバーライド不要 ], child: MyApp(), ), ); }); /* SNIPPET END */ }
riverpod/website/i18n/ja/docusaurus-plugin-content-docs/current/cookbooks/testing_flutter.dart/0
{'file_path': 'riverpod/website/i18n/ja/docusaurus-plugin-content-docs/current/cookbooks/testing_flutter.dart', 'repo_id': 'riverpod', 'token_count': 410}
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'dropdown.dart'; /* SNIPPET START */ final productSortTypeProvider = StateProvider<ProductSortType>( // ソートの種類 name を返します。これがデフォルトのステートとなります。 (ref) => ProductSortType.name, );
riverpod/website/i18n/ja/docusaurus-plugin-content-docs/current/providers/state_provider/sort_provider.dart/0
{'file_path': 'riverpod/website/i18n/ja/docusaurus-plugin-content-docs/current/providers/state_provider/sort_provider.dart', 'repo_id': 'riverpod', 'token_count': 107}
// ignore_for_file: avoid_print, use_key_in_widget_constructors import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'fetch_activity/codegen.dart'; /* SNIPPET START */ class ActivityView extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final activity = ref.watch(activityProvider); return Scaffold( appBar: AppBar(title: const Text('Pull to refresh')), body: RefreshIndicator( // "activityProvider.future"를 새로 고침으로, 해당 결과를 반환하면, // 새 액티비티를 가져올 때까지 // 새로 고침 표시기(refresh indicator)가 계속 표시됩니다. /* highlight-start */ onRefresh: () => ref.refresh(activityProvider.future), /* highlight-end */ child: ListView( children: [ Text(activity.valueOrNull?.activity ?? ''), ], ), ), ); } }
riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/case_studies/pull_to_refresh/display_activity3.dart/0
{'file_path': 'riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/case_studies/pull_to_refresh/display_activity3.dart', 'repo_id': 'riverpod', 'token_count': 476}
import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'async_class_stream.g.dart'; /* SNIPPET START */ @riverpod class Example extends _$Example { @override Stream<String> build() async* { yield 'foo'; } // 상태(State) 변경(Mutation)을 위한 메서드 추가 }
riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/concepts/about_codegen/provider_type/async_class_stream.dart/0
{'file_path': 'riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/concepts/about_codegen/provider_type/async_class_stream.dart', 'repo_id': 'riverpod', 'token_count': 129}
// ignore_for_file: unused_local_variable import 'package:http/http.dart' as http; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'codegen.g.dart'; /* SNIPPET START */ @riverpod Future<String> example(ExampleRef ref) async { final response = await http.get(Uri.parse('https://example.com')); // 요청이 성공적으로 완료된 후에만 프로바이더를 살아있게 유지합니다. // 요청이 실패한 경우(그리고 throw된 경우), 공급자에 청취를 중단하면 상태가 소멸됩니다. ref.keepAlive(); // `link`를 사용하여 자동 폐기 동작을 복원할 수 있습니다: // link.close(); return response.body; }
riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/auto_dispose/keep_alive/codegen.dart/0
{'file_path': 'riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/auto_dispose/keep_alive/codegen.dart', 'repo_id': 'riverpod', 'token_count': 385}
/* SNIPPET START */ import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'activity.dart'; // 코드 생성이 작동하는 데 필요합니다. part 'provider.g.dart'; /// 그러면 `activityProvider`라는 이름의 provider가 생성됩니다. /// 이 함수의 결과를 캐시하는 공급자를 생성합니다. @riverpod Future<Activity> activity(ActivityRef ref) async { // package:http를 사용하여 Bored API에서 임의의 Activity를 가져옵니다. final response = await http.get(Uri.https('boredapi.com', '/api/activity')); // 그런 다음 dart:convert를 사용하여 JSON 페이로드를 맵 데이터 구조로 디코딩합니다. final json = jsonDecode(response.body) as Map<String, dynamic>; // 마지막으로 맵을 Activity 인스턴스로 변환합니다. return Activity.fromJson(json); }
riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/first_request/codegen/provider.dart/0
{'file_path': 'riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/first_request/codegen/provider.dart', 'repo_id': 'riverpod', 'token_count': 493}
import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../../first_request/codegen/activity.dart'; part 'family.g.dart'; /* SNIPPET START */ @riverpod Future<Activity> activity( ActivityRef ref, // provider에 인수를 추가할 수 있습니다. // 매개변수 타입은 원하는 대로 지정할 수 있습니다. String activityType, ) async { // "activityType" 인수를 사용하여 URL을 작성할 수 있습니다. // "https://boredapi.com/api/activity?type=<activityType>"을 가리키게 됩니다. final response = await http.get( Uri( scheme: 'https', host: 'boredapi.com', path: '/api/activity', // 쿼리 매개변수를 수동으로 인코딩할 필요 없이 "Uri" 클래스가 자동으로 인코딩합니다. queryParameters: {'type': activityType}, ), ); final json = jsonDecode(response.body) as Map<String, dynamic>; return Activity.fromJson(json); }
riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/passing_args/codegen/family.dart/0
{'file_path': 'riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/passing_args/codegen/family.dart', 'repo_id': 'riverpod', 'token_count': 521}
// ignore_for_file: avoid_print import 'dart:convert'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:http/http.dart' as http; import 'todo_list_notifier.dart'; final todoListProvider = AsyncNotifierProvider.autoDispose<TodoList, List<Todo>>( TodoList.new, ); /* SNIPPET START */ class TodoList extends AutoDisposeAsyncNotifier<List<Todo>> { @override Future<List<Todo>> build() async => [/* ... */]; Future<void> addTodo(Todo todo) async { await http.post( Uri.https('your_api.com', '/todos'), // We serialize our Todo object and POST it to the server. headers: {'Content-Type': 'application/json'}, body: jsonEncode(todo.toJson()), ); } }
riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/side_effects/raw/todo_list_notifier_add_todo.dart/0
{'file_path': 'riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/side_effects/raw/todo_list_notifier_add_todo.dart', 'repo_id': 'riverpod', 'token_count': 282}
// ignore_for_file: prefer_mixin import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:mockito/mockito.dart'; /* SNIPPET START */ class MyNotifier extends Notifier<int> { @override int build() => throw UnimplementedError(); } // Your mock needs to subclass the Notifier base-class corresponding // to whatever your notifier uses class MyNotifierMock extends Notifier<int> with Mock implements MyNotifier {} /* SNIPPET END */
riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/testing/notifier_mock/raw.dart/0
{'file_path': 'riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/testing/notifier_mock/raw.dart', 'repo_id': 'riverpod', 'token_count': 139}
// ignore_for_file: omit_local_variable_types, prefer_final_locals, use_key_in_widget_constructors import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'codegen.g.dart'; /* SNIPPET START */ @riverpod Stream<int> streamExample(StreamExampleRef ref) async* { // 1초마다 0에서 41 사이의 숫자를 yield합니다. // 이 값은 Firestore나 GraphQL 등의 스트림으로 대체할 수 있습니다. for (var i = 0; i < 42; i++) { yield i; await Future<void>.delayed(const Duration(seconds: 1)); } } class Consumer extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { // 스트림을 수신하고 AsyncValue로 변환합니다. AsyncValue<int> value = ref.watch(streamExampleProvider); // 로딩/오류 상태를 처리하고 데이터를 표시하는 데 AsyncValue를 사용할 수 있습니다. return switch (value) { AsyncValue(:final error?) => Text('Error: $error'), AsyncValue(:final valueOrNull?) => Text('$valueOrNull'), _ => const CircularProgressIndicator(), }; } } /* SNIPPET END */
riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/websockets_sync/stream_provider/codegen.dart/0
{'file_path': 'riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/websockets_sync/stream_provider/codegen.dart', 'repo_id': 'riverpod', 'token_count': 551}
typedef Json = Map<String, dynamic>;
riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/from_provider/helpers/json.dart/0
{'file_path': 'riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/from_provider/helpers/json.dart', 'repo_id': 'riverpod', 'token_count': 14}
import 'dart:async'; import 'package:dio/dio.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../../utils.dart'; part 'old_lifecycles_final.g.dart'; final repositoryProvider = Provider<_MyRepo>((ref) { return _MyRepo(); }); class _MyRepo { Future<void> update(int i, {CancelToken? token}) async {} } /* SNIPPET START */ @riverpod class MyNotifier extends _$MyNotifier { @override int build() { // 한 곳에서 코드를 읽고 쓰면 됩니다. final period = ref.watch(durationProvider); final timer = Timer.periodic(period, (t) => update()); ref.onDispose(timer.cancel); return 0; } Future<void> update() async { final cancelToken = CancelToken(); ref.onDispose(cancelToken.cancel); await ref.read(repositoryProvider).update(state + 1, token: cancelToken); // `cancelToken.cancel`이 호출되면 커스텀 예외가 발생합니다. state++; } }
riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/migration/from_state_notifier/old_lifecycles_final/old_lifecycles_final.dart/0
{'file_path': 'riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/migration/from_state_notifier/old_lifecycles_final/old_lifecycles_final.dart', 'repo_id': 'riverpod', 'token_count': 405}
// ignore_for_file: prefer_const_literals_to_create_immutables import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'dropdown.dart'; import 'sort_provider.dart'; Widget build(BuildContext context, WidgetRef ref) { return AppBar(actions: [ /* SNIPPET START */ DropdownButton<ProductSortType>( // При изменении типа сортировки произойдет перестройка DropdownButton value: ref.watch(productSortTypeProvider), // Обновляем состояние провайдера при взаимодействии пользователя с DropdownButton onChanged: (value) => ref.read(productSortTypeProvider.notifier).state = value!, items: [ // ... ], ), /* SNIPPET END */ ]); }
riverpod/website/i18n/ru/docusaurus-plugin-content-docs/current/providers/state_provider/connected_dropdown.dart/0
{'file_path': 'riverpod/website/i18n/ru/docusaurus-plugin-content-docs/current/providers/state_provider/connected_dropdown.dart', 'repo_id': 'riverpod', 'token_count': 328}
// ignore_for_file: use_key_in_widget_constructors import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; // We can specify autoDispose to enable automatic state destruction. final someProvider = Provider.autoDispose<int>((ref) { return 0; }); /* SNIPPET START */ class MyWidget extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { return ElevatedButton( onPressed: () { // 点击后,处置提供者程序。 ref.invalidate(someProvider); }, child: const Text('dispose a provider'), ); } }
riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/auto_dispose/invalidate_example.dart/0
{'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/auto_dispose/invalidate_example.dart', 'repo_id': 'riverpod', 'token_count': 236}
import 'dart:async'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../first_request/raw/activity.dart'; /* SNIPPET START */ FutureOr<Activity> fetchActivity() => throw UnimplementedError(); // “函数型”提供者程序 final activityProvider = FutureProvider.autoDispose((ref) async { // TODO: 执行网络请求以获取活动 return fetchActivity(); }); // 或者替代方案,“通知者程序” final activityProvider2 = AsyncNotifierProvider<ActivityNotifier, Activity>( ActivityNotifier.new, ); class ActivityNotifier extends AsyncNotifier<Activity> { @override Future<Activity> build() async { // TODO: 执行网络请求以获取活动 return fetchActivity(); } }
riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/passing_args/raw/provider.dart/0
{'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/passing_args/raw/provider.dart', 'repo_id': 'riverpod', 'token_count': 295}
// ignore_for_file: avoid_print, prefer_final_locals, omit_local_variable_types import 'dart:convert'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:http/http.dart' as http; import 'todo_list_notifier.dart'; final todoListProvider = AsyncNotifierProvider.autoDispose<TodoList, List<Todo>>( TodoList.new, ); class TodoList extends AutoDisposeAsyncNotifier<List<Todo>> { @override Future<List<Todo>> build() async => [/* ... */]; Future<void> addTodo(Todo todo) async { // We don't care about the API response await http.post( Uri.https('your_api.com', '/todos'), headers: {'Content-Type': 'application/json'}, body: jsonEncode(todo.toJson()), ); /* SNIPPET START */ final previousState = await future; // 改变之前的待办事项列表。 previousState.add(todo); // 手动通知监听者。 ref.notifyListeners(); /* SNIPPET END */ } }
riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/side_effects/raw/mutable_manual_add_todo.dart/0
{'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/side_effects/raw/mutable_manual_add_todo.dart', 'repo_id': 'riverpod', 'token_count': 382}
// ignore_for_file: use_key_in_widget_constructors, omit_local_variable_types import 'package:dio/dio.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'codegen.g.dart'; class Package { static Package fromJson(dynamic json) { throw UnimplementedError(); } } /* SNIPPET START */ // 从 pub.dev 获取包列表 @riverpod Future<List<Package>> fetchPackages( FetchPackagesRef ref, { required int page, String search = '', }) async { final dio = Dio(); // 获取 API。 这里我们使用 package:dio,但我们可以使用其他任何东西。 final response = await dio.get<List<Object?>>( 'https://pub.dartlang.org/api/search?page=$page&q=${Uri.encodeQueryComponent(search)}', ); // 将 JSON 响应解码为 Dart 类。 return response.data?.map(Package.fromJson).toList() ?? const []; }/* SNIPPET END */
riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/introduction/why_riverpod/codegen.dart/0
{'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/introduction/why_riverpod/codegen.dart', 'repo_id': 'riverpod', 'token_count': 352}
import 'package:flame/components/animation_component.dart'; import 'package:flame/animation.dart'; import 'package:flame/components/mixins/has_game_ref.dart'; import '../game.dart'; import './explosion_component.dart'; class EnemyComponent extends AnimationComponent with HasGameRef<SpaceShooterGame>{ static const enemy_speed = 150; bool destroyed = false; EnemyComponent(double x, double y): super(25, 25,Animation.sequenced("enemy.png", 4, textureWidth: 16, textureHeight: 16)) { this.x = x; this.y = y; } @override void update(double dt) { super.update(dt); y += enemy_speed * dt; if (gameRef.player != null && gameRef.player.toRect().overlaps(toRect())) { takeHit(); gameRef.playerTakeHit(); } } void takeHit() { destroyed = true; gameRef.add(ExplosionComponent(x - 25, y - 25)); gameRef.increaseScore(); } @override bool destroy() => destroyed || y >= gameRef.size.height; }
rogue_shooter/game/lib/components/enemy_component.dart/0
{'file_path': 'rogue_shooter/game/lib/components/enemy_component.dart', 'repo_id': 'rogue_shooter', 'token_count': 356}
import 'package:flutter/material.dart'; class SearchErrorWidget extends StatelessWidget { const SearchErrorWidget({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Container( alignment: FractionalOffset.center, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Icon(Icons.error_outline, color: Colors.red[300], size: 80.0), Container( padding: EdgeInsets.only(top: 16.0), child: Text( "Rate limit exceeded", style: TextStyle( color: Colors.red[300], ), ), ) ], ), ); } }
rxdart/example/flutter/github_search/lib/search_error_widget.dart/0
{'file_path': 'rxdart/example/flutter/github_search/lib/search_error_widget.dart', 'repo_id': 'rxdart', 'token_count': 361}
import 'dart:async'; import 'package:rxdart/src/streams/zip.dart'; import 'package:rxdart/src/transformers/materialize.dart'; import 'package:rxdart/src/utils/notification.dart'; /// Determine whether two Streams emit the same sequence of items. /// You can provide an optional equals handler to determine equality. /// /// [Interactive marble diagram](https://rxmarbles.com/#sequenceEqual) /// /// ### Example /// /// SequenceEqualsStream([ /// Stream.fromIterable([1, 2, 3, 4, 5]), /// Stream.fromIterable([1, 2, 3, 4, 5]) /// ]) /// .listen(print); // prints true class SequenceEqualStream<S, T> extends Stream<bool> { final StreamController<bool> _controller; /// Creates a [Stream] that emits true or false, depending on the /// equality between the provided [Stream]s. /// This single value is emitted when both provided [Stream]s are complete. /// After this event, the [Stream] closes. SequenceEqualStream(Stream<S> stream, Stream<T> other, {bool Function(S s, T t) equals}) : _controller = _buildController(stream, other, equals); @override StreamSubscription<bool> listen(void Function(bool event) onData, {Function onError, void Function() onDone, bool cancelOnError}) => _controller.stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); static StreamController<bool> _buildController<S, T>( Stream<S> stream, Stream<T> other, bool Function(S s, T t) equals) { if (stream == null) { throw ArgumentError.notNull('stream'); } if (other == null) { throw ArgumentError.notNull('other'); } final doCompare = equals ?? (S s, T t) => s == t; StreamController<bool> controller; StreamSubscription<bool> subscription; controller = StreamController<bool>( sync: true, onListen: () { final emitAndClose = ([bool value = true]) => controller ..add(value) ..close(); subscription = ZipStream.zip2( stream.transform(MaterializeStreamTransformer()), other.transform(MaterializeStreamTransformer()), (Notification<S> s, Notification<T> t) => s.kind == t.kind && s.errorAndStackTrace?.error?.toString() == t.errorAndStackTrace?.error?.toString() && doCompare(s.value, t.value)) .where((isEqual) => !isEqual) .listen(emitAndClose, onError: controller.addError, onDone: emitAndClose); }, onPause: () => subscription.pause(), onResume: () => subscription.resume(), onCancel: () => subscription.cancel()); return controller; } }
rxdart/lib/src/streams/sequence_equal.dart/0
{'file_path': 'rxdart/lib/src/streams/sequence_equal.dart', 'repo_id': 'rxdart', 'token_count': 1107}
import 'package:rxdart/src/utils/min_max.dart'; /// Extends the Stream class with the ability to transform into a Future /// that completes with the largest item emitted by the Stream. extension MaxExtension<T> on Stream<T> { /// Converts a Stream into a Future that completes with the largest item /// emitted by the Stream. /// /// This is similar to finding the max value in a list, but the values are /// asynchronous. /// /// ### Example /// /// final max = await Stream.fromIterable([1, 2, 3]).max(); /// /// print(max); // prints 3 /// /// ### Example with custom [Comparator] /// /// final stream = Stream.fromIterable(['short', 'looooooong']); /// final max = await stream.max((a, b) => a.length - b.length); /// /// print(max); // prints 'looooooong' Future<T> max([Comparator<T> comparator]) => minMax(this, false, comparator); }
rxdart/lib/src/transformers/max.dart/0
{'file_path': 'rxdart/lib/src/transformers/max.dart', 'repo_id': 'rxdart', 'token_count': 290}
import 'dart:async'; import 'package:rxdart/rxdart.dart'; import 'package:test/test.dart'; Stream<int> get streamA => Stream<int>.periodic(const Duration(milliseconds: 1), (int count) => count) .take(3); Stream<int> get streamB => Stream<int>.fromIterable(const <int>[1, 2, 3, 4]); Stream<bool> get streamC { final controller = StreamController<bool>() ..add(true) ..close(); return controller.stream; } void main() { test('Rx.forkJoinList', () async { final combined = Rx.forkJoinList<int>([ Stream.fromIterable([1, 2, 3]), Stream.value(2), Stream.value(3), ]); await expectLater( combined, emitsInOrder(<dynamic>[ [3, 2, 3], emitsDone ]), ); }); test('Rx.forkJoin.empty', () { expect(Rx.forkJoinList<int>([]), emitsDone); }); test('Rx.forkJoinList.singleStream', () async { final combined = Rx.forkJoinList<int>([ Stream.fromIterable([1, 2, 3]) ]); await expectLater( combined, emitsInOrder(<dynamic>[ [3], emitsDone ]), ); }); test('Rx.forkJoin', () async { final combined = Rx.forkJoin<int, int>( [ Stream.fromIterable([1, 2, 3]), Stream.value(2), Stream.value(3), ], (values) => values.fold(0, (acc, val) => acc + val), ); await expectLater( combined, emitsInOrder(<dynamic>[8, emitsDone]), ); }); test('Rx.forkJoin3', () async { final stream = Rx.forkJoin3( streamA, streamB, streamC, (int a_value, int b_value, bool c_value) => '$a_value $b_value $c_value'); await expectLater(stream, emitsInOrder(<dynamic>['2 4 true', emitsDone])); }); test('Rx.forkJoin3.single.subscription', () async { final stream = Rx.forkJoin3( streamA, streamB, streamC, (int a_value, int b_value, bool c_value) => '$a_value $b_value $c_value'); await expectLater( stream, emitsInOrder(<dynamic>['2 4 true', emitsDone]), ); await expectLater(() => stream.listen(null), throwsA(isStateError)); }); test('Rx.forkJoin2', () async { var a = Stream.fromIterable(const [1, 2]), b = Stream.value(2); final stream = Rx.forkJoin2(a, b, (int first, int second) => [first, second]); await expectLater( stream, emitsInOrder(<dynamic>[ [2, 2], emitsDone ])); }); test('Rx.forkJoin2.throws', () async { var a = Stream.value(1), b = Stream.value(2); final stream = Rx.forkJoin2(a, b, (int first, int second) { throw Exception(); }); stream.listen(null, onError: expectAsync2((Exception e, StackTrace s) { expect(e, isException); })); }); test('Rx.forkJoin3', () async { var a = Stream<int>.value(1), b = Stream<String>.value('2'), c = Stream<double>.value(3.0); final stream = Rx.forkJoin3(a, b, c, (int first, String second, double third) => [first, second, third]); await expectLater( stream, emitsInOrder(<dynamic>[ const [1, '2', 3.0], emitsDone ])); }); test('Rx.forkJoin4', () async { var a = Stream.value(1), b = Stream<int>.value(2), c = Stream<int>.value(3), d = Stream<int>.value(4); final stream = Rx.forkJoin4( a, b, c, d, (int first, int second, int third, int fourth) => [first, second, third, fourth]); await expectLater( stream, emitsInOrder(<dynamic>[ const [1, 2, 3, 4], emitsDone ])); }); test('Rx.forkJoin5', () async { var a = Stream<int>.value(1), b = Stream<int>.value(2), c = Stream<int>.value(3), d = Stream<int>.value(4), e = Stream<int>.value(5); final stream = Rx.forkJoin5( a, b, c, d, e, (int first, int second, int third, int fourth, int fifth) => <int>[first, second, third, fourth, fifth]); await expectLater( stream, emitsInOrder(<dynamic>[ const [1, 2, 3, 4, 5], emitsDone ])); }); test('Rx.forkJoin6', () async { var a = Stream<int>.value(1), b = Stream<int>.value(2), c = Stream<int>.value(3), d = Stream<int>.value(4), e = Stream<int>.value(5), f = Stream<int>.value(6); final stream = Rx.combineLatest6( a, b, c, d, e, f, (int first, int second, int third, int fourth, int fifth, int sixth) => [first, second, third, fourth, fifth, sixth]); await expectLater( stream, emitsInOrder(<dynamic>[ const [1, 2, 3, 4, 5, 6], emitsDone ])); }); test('Rx.forkJoin7', () async { var a = Stream<int>.value(1), b = Stream<int>.value(2), c = Stream<int>.value(3), d = Stream<int>.value(4), e = Stream<int>.value(5), f = Stream<int>.value(6), g = Stream<int>.value(7); final stream = Rx.forkJoin7( a, b, c, d, e, f, g, (int first, int second, int third, int fourth, int fifth, int sixth, int seventh) => [first, second, third, fourth, fifth, sixth, seventh]); await expectLater( stream, emitsInOrder(<dynamic>[ const [1, 2, 3, 4, 5, 6, 7], emitsDone ])); }); test('Rx.forkJoin8', () async { var a = Stream<int>.value(1), b = Stream<int>.value(2), c = Stream<int>.value(3), d = Stream<int>.value(4), e = Stream<int>.value(5), f = Stream<int>.value(6), g = Stream<int>.value(7), h = Stream<int>.value(8); final stream = Rx.forkJoin8( a, b, c, d, e, f, g, h, (int first, int second, int third, int fourth, int fifth, int sixth, int seventh, int eighth) => [first, second, third, fourth, fifth, sixth, seventh, eighth]); await expectLater( stream, emitsInOrder(<dynamic>[ const [1, 2, 3, 4, 5, 6, 7, 8], emitsDone ])); }); test('Rx.forkJoin9', () async { var a = Stream<int>.value(1), b = Stream<int>.value(2), c = Stream<int>.value(3), d = Stream<int>.value(4), e = Stream<int>.value(5), f = Stream<int>.value(6), g = Stream<int>.value(7), h = Stream<int>.value(8), i = Stream<int>.value(9); final stream = Rx.forkJoin9( a, b, c, d, e, f, g, h, i, (int first, int second, int third, int fourth, int fifth, int sixth, int seventh, int eighth, int ninth) => [ first, second, third, fourth, fifth, sixth, seventh, eighth, ninth ]); await expectLater( stream, emitsInOrder(<dynamic>[ const [1, 2, 3, 4, 5, 6, 7, 8, 9], emitsDone ])); }); test('Rx.forkJoin.asBroadcastStream', () async { final stream = Rx.forkJoin3( streamA, streamB, streamC, (int a_value, int b_value, bool c_value) => '$a_value $b_value $c_value').asBroadcastStream(); // listen twice on same stream stream.listen(null); stream.listen(null); // code should reach here await expectLater(stream.isBroadcast, isTrue); }); test('Rx.forkJoin.error.shouldThrowA', () async { final streamWithError = Rx.forkJoin4( Stream.value(1), Stream.value(1), Stream.value(1), Stream<int>.error(Exception()), (int a_value, int b_value, int c_value, dynamic _) => '$a_value $b_value $c_value $_'); streamWithError.listen(null, onError: expectAsync2((Exception e, StackTrace s) { expect(e, isException); }), cancelOnError: true); }); test('Rx.forkJoin.error.shouldThrowB', () async { final streamWithError = Rx.forkJoin3(Stream.value(1), Stream.value(1), Stream.value(1), (int a_value, int b_value, int c_value) { throw Exception('oh noes!'); }); streamWithError.listen(null, onError: expectAsync2((Exception e, StackTrace s) { expect(e, isException); })); }); test('Rx.forkJoin.pause.resume', () async { final first = Stream.periodic(const Duration(milliseconds: 10), (index) => const [1, 2, 3, 4][index]).take(4), second = Stream.periodic(const Duration(milliseconds: 10), (index) => const [5, 6, 7, 8][index]).take(4), last = Stream.periodic(const Duration(milliseconds: 10), (index) => const [9, 10, 11, 12][index]).take(4); StreamSubscription<Iterable<num>> subscription; subscription = Rx.forkJoin3(first, second, last, (int a, int b, int c) => [a, b, c]) .listen(expectAsync1((value) { expect(value.elementAt(0), 4); expect(value.elementAt(1), 8); expect(value.elementAt(2), 12); subscription.cancel(); }, count: 1)); subscription.pause(Future<void>.delayed(const Duration(milliseconds: 80))); }); test('Rx.forkJoin.completed', () async { final stream = Rx.forkJoin2( Stream<int>.empty(), Stream.value(1), (int a, int b) => a + b, ); await expectLater( stream, emitsInOrder(<dynamic>[emitsError(isStateError), emitsDone]), ); }); test('Rx.forkJoin.error.shouldThrowC', () async { final stream = Rx.forkJoin2( Stream.value(1), Stream<int>.error(Exception()).concatWith([ Rx.timer( 2, const Duration(milliseconds: 100), ) ]), (int a, int b) => a + b, ); await expectLater( stream, emitsInOrder(<dynamic>[emitsError(isException), 3, emitsDone]), ); }); test('Rx.forkJoin.error.shouldThrowD', () async { final stream = Rx.forkJoin2( Stream.value(1), Stream<int>.error(Exception()).concatWith([ Rx.timer( 2, const Duration(milliseconds: 100), ) ]), (int a, int b) => a + b, ); stream.listen( expectAsync1((value) {}, count: 0), onError: expectAsync2( (Object e, StackTrace s) => expect(e, isException), count: 1, ), cancelOnError: true, ); }); }
rxdart/test/streams/fork_join_test.dart/0
{'file_path': 'rxdart/test/streams/fork_join_test.dart', 'repo_id': 'rxdart', 'token_count': 5198}
import 'dart:async'; import 'package:rxdart/rxdart.dart'; import 'package:test/test.dart'; void main() { test('Rx.zip', () async { expect( Rx.zip<String, String>([ Stream.fromIterable(['A1', 'B1']), Stream.fromIterable(['A2', 'B2', 'C2']), ], (values) => values.first + values.last), emitsInOrder(<dynamic>['A1A2', 'B1B2', emitsDone]), ); }); test('Rx.zip.empty', () { expect(Rx.zipList<int>([]), emitsDone); }); test('Rx.zipList', () async { expect( Rx.zipList([ Stream.fromIterable(['A1', 'B1']), Stream.fromIterable(['A2', 'B2', 'C2']), Stream.fromIterable(['A3', 'B3', 'C3']), ]), emitsInOrder(<dynamic>[ ['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], emitsDone ]), ); }); test('Rx.zipBasics', () async { const expectedOutput = [ [0, 1, true], [1, 2, false], [2, 3, true], [3, 4, false] ]; var count = 0; final testStream = StreamController<bool>() ..add(true) ..add(false) ..add(true) ..add(false) ..add(true) ..close(); // ignore: unawaited_futures final stream = Rx.zip3( Stream.periodic(const Duration(milliseconds: 1), (count) => count) .take(4), Stream.fromIterable(const [1, 2, 3, 4, 5, 6, 7, 8, 9]), testStream.stream, (int a, int b, bool c) => [a, b, c]); stream.listen(expectAsync1((result) { // test to see if the combined output matches for (var i = 0, len = result.length; i < len; i++) { expect(result[i], expectedOutput[count][i]); } count++; }, count: expectedOutput.length)); }); test('Rx.zipTwo', () async { const expected = [1, 2]; // A purposely emits 2 items, b only 1 final a = Stream.fromIterable(const [1, 2]), b = Stream.value(2); final stream = Rx.zip2(a, b, (int first, int second) => [first, second]); // Explicitly adding count: 1. It's important here, and tests the difference // between zip and combineLatest. If this was combineLatest, the count would // be two, and a second List<int> would be emitted. stream.listen(expectAsync1((result) { expect(result, expected); }, count: 1)); }); test('Rx.zip3', () async { // Verify the ability to pass through various types with safety const expected = [1, '2', 3.0]; final a = Stream.value(1), b = Stream.value('2'), c = Stream.value(3.0); final stream = Rx.zip3(a, b, c, (int first, String second, double third) => [first, second, third]); stream.listen(expectAsync1((result) { expect(result, expected); })); }); test('Rx.zip4', () async { const expected = [1, 2, 3, 4]; final a = Stream.value(1), b = Stream.value(2), c = Stream.value(3), d = Stream.value(4); final stream = Rx.zip4( a, b, c, d, (int first, int second, int third, int fourth) => [first, second, third, fourth]); stream.listen(expectAsync1((result) { expect(result, expected); })); }); test('Rx.zip5', () async { const expected = [1, 2, 3, 4, 5]; final a = Stream.value(1), b = Stream.value(2), c = Stream.value(3), d = Stream.value(4), e = Stream.value(5); final stream = Rx.zip5( a, b, c, d, e, (int first, int second, int third, int fourth, int fifth) => [first, second, third, fourth, fifth]); stream.listen(expectAsync1((result) { expect(result, expected); })); }); test('Rx.zip6', () async { const expected = [1, 2, 3, 4, 5, 6]; final a = Stream.value(1), b = Stream.value(2), c = Stream.value(3), d = Stream.value(4), e = Stream.value(5), f = Stream.value(6); final stream = Rx.zip6( a, b, c, d, e, f, (int first, int second, int third, int fourth, int fifth, int sixth) => [first, second, third, fourth, fifth, sixth]); stream.listen(expectAsync1((result) { expect(result, expected); })); }); test('Rx.zip7', () async { const expected = [1, 2, 3, 4, 5, 6, 7]; final a = Stream.value(1), b = Stream.value(2), c = Stream.value(3), d = Stream.value(4), e = Stream.value(5), f = Stream.value(6), g = Stream.value(7); final stream = Rx.zip7( a, b, c, d, e, f, g, (int first, int second, int third, int fourth, int fifth, int sixth, int seventh) => [first, second, third, fourth, fifth, sixth, seventh]); stream.listen(expectAsync1((result) { expect(result, expected); })); }); test('Rx.zip8', () async { const expected = [1, 2, 3, 4, 5, 6, 7, 8]; final a = Stream.value(1), b = Stream.value(2), c = Stream.value(3), d = Stream.value(4), e = Stream.value(5), f = Stream.value(6), g = Stream.value(7), h = Stream.value(8); final stream = Rx.zip8( a, b, c, d, e, f, g, h, (int first, int second, int third, int fourth, int fifth, int sixth, int seventh, int eighth) => [first, second, third, fourth, fifth, sixth, seventh, eighth]); stream.listen(expectAsync1((result) { expect(result, expected); })); }); test('Rx.zip9', () async { const expected = [1, 2, 3, 4, 5, 6, 7, 8, 9]; final a = Stream.value(1), b = Stream.value(2), c = Stream.value(3), d = Stream.value(4), e = Stream.value(5), f = Stream.value(6), g = Stream.value(7), h = Stream.value(8), i = Stream.value(9); final stream = Rx.zip9( a, b, c, d, e, f, g, h, i, (int first, int second, int third, int fourth, int fifth, int sixth, int seventh, int eighth, int ninth) => [ first, second, third, fourth, fifth, sixth, seventh, eighth, ninth ]); stream.listen(expectAsync1((result) { expect(result, expected); })); }); test('Rx.zip.single.subscription', () async { final stream = Rx.zip2(Stream.value(1), Stream.value(1), (int a, int b) => a + b); stream.listen(null); await expectLater(() => stream.listen(null), throwsA(isStateError)); }); test('Rx.zip.asBroadcastStream', () async { final testStream = StreamController<bool>() ..add(true) ..add(false) ..add(true) ..add(false) ..add(true) ..close(); // ignore: unawaited_futures final stream = Rx.zip3( Stream.periodic(const Duration(milliseconds: 1), (count) => count) .take(4), Stream.fromIterable(const [1, 2, 3, 4, 5, 6, 7, 8, 9]), testStream.stream, (int a, int b, bool c) => [a, b, c]).asBroadcastStream(); // listen twice on same stream stream.listen(null); stream.listen(null); // code should reach here await expectLater(stream.isBroadcast, isTrue); }); test('Rx.zip.error.shouldThrowA', () async { final streamWithError = Rx.zip2( Stream.value(1), Stream.value(2), (int a, int b) => throw Exception(), ); streamWithError.listen(null, onError: expectAsync2((Exception e, StackTrace s) { expect(e, isException); })); }); /*test('Rx.zip.error.shouldThrowB', () { expect( () => Rx.zip2( Stream.value(1), null, (int a, _) => null), throwsArgumentError); }); test('Rx.zip.error.shouldThrowC', () { expect(() => ZipStream<num>(null, () {}), throwsArgumentError); }); test('Rx.zip.error.shouldThrowD', () { expect(() => ZipStream<num>(<Stream<dynamic>>[], () {}), throwsArgumentError); });*/ test('Rx.zip.pause.resume.A', () async { StreamSubscription<int> subscription; final stream = Rx.zip2(Stream.value(1), Stream.value(2), (int a, int b) => a + b); subscription = stream.listen(expectAsync1((value) { expect(value, 3); subscription.cancel(); })); subscription.pause(); subscription.resume(); }); test('Rx.zip.pause.resume.B', () async { final first = Stream.periodic(const Duration(milliseconds: 10), (index) => const [1, 2, 3, 4][index]), second = Stream.periodic(const Duration(milliseconds: 10), (index) => const [5, 6, 7, 8][index]), last = Stream.periodic(const Duration(milliseconds: 10), (index) => const [9, 10, 11, 12][index]); StreamSubscription<Iterable<num>> subscription; subscription = Rx.zip3(first, second, last, (num a, num b, num c) => [a, b, c]) .listen(expectAsync1((value) { expect(value.elementAt(0), 1); expect(value.elementAt(1), 5); expect(value.elementAt(2), 9); subscription.cancel(); }, count: 1)); subscription.pause(Future<void>.delayed(const Duration(milliseconds: 80))); }); }
rxdart/test/streams/zip_test.dart/0
{'file_path': 'rxdart/test/streams/zip_test.dart', 'repo_id': 'rxdart', 'token_count': 4424}
import 'dart:async'; import 'package:rxdart/rxdart.dart'; import 'package:test/test.dart'; Stream<int> getStream(int n) async* { var k = 0; while (k < n) { await Future<Null>.delayed(const Duration(milliseconds: 100)); yield k++; } } void main() { test('Rx.window', () async { await expectLater( getStream(4) .window(Stream<Null>.periodic(const Duration(milliseconds: 160)) .take(3)) .asyncMap((stream) => stream.toList()), emitsInOrder(<dynamic>[ const [0, 1], const [2, 3], emitsDone ])); }); test('Rx.window.sampleBeforeEvent.shouldEmit', () async { await expectLater( Stream.fromFuture( Future<Null>.delayed(const Duration(milliseconds: 200)) .then((_) => 'end')) .startWith('start') .window(Stream<Null>.periodic(const Duration(milliseconds: 40)) .take(10)) .asyncMap((stream) => stream.toList()), emitsInOrder(<dynamic>[ const ['start'], // after 40ms const <String>[], // 80ms const <String>[], // 120ms const <String>[], // 160ms const ['end'], // done emitsDone ])); }); test('Rx.window.shouldClose', () async { final controller = StreamController<int>()..add(0)..add(1)..add(2)..add(3); scheduleMicrotask(controller.close); await expectLater( controller.stream .window(Stream<Null>.periodic(const Duration(seconds: 3))) .asyncMap((stream) => stream.toList()) .take(1), emitsInOrder(<dynamic>[ const [0, 1, 2, 3], // done emitsDone ])); }); test('Rx.window.reusable', () async { final transformer = WindowStreamTransformer<int>((_) => Stream<Null>.periodic(const Duration(milliseconds: 160)) .take(3) .asBroadcastStream()); await expectLater( getStream(4) .transform(transformer) .asyncMap((stream) => stream.toList()), emitsInOrder(<dynamic>[ const [0, 1], const [2, 3], emitsDone ])); await expectLater( getStream(4) .transform(transformer) .asyncMap((stream) => stream.toList()), emitsInOrder(<dynamic>[ const [0, 1], const [2, 3], emitsDone ])); }); test('Rx.window.asBroadcastStream', () async { final future = getStream(4) .asBroadcastStream() .window(Stream<Null>.periodic(const Duration(milliseconds: 160)) .take(10) .asBroadcastStream()) .drain<void>(); // listen twice on same stream await expectLater(future, completes); await expectLater(future, completes); }); test('Rx.window.error.shouldThrowA', () async { await expectLater( Stream<Null>.error(Exception()) .window(Stream<Null>.periodic(const Duration(milliseconds: 160))), emitsError(isException)); }); test('Rx.window.error.shouldThrowB', () async { await expectLater(Stream.fromIterable(const [1, 2, 3, 4]).window(null), emitsError(isArgumentError)); }); }
rxdart/test/transformers/backpressure/window_test.dart/0
{'file_path': 'rxdart/test/transformers/backpressure/window_test.dart', 'repo_id': 'rxdart', 'token_count': 1515}
import 'dart:async'; import 'package:rxdart/rxdart.dart'; import 'package:test/test.dart'; Stream<int> _getStream() { final controller = StreamController<int>(); Timer(const Duration(milliseconds: 100), () => controller.add(1)); Timer(const Duration(milliseconds: 200), () => controller.add(2)); Timer(const Duration(milliseconds: 300), () => controller.add(3)); Timer(const Duration(milliseconds: 400), () { controller.add(4); controller.close(); }); return controller.stream; } void main() { test('Rx.ignoreElements', () async { var hasReceivedEvent = false; // ignore: deprecated_member_use_from_same_package _getStream().ignoreElements().listen((_) { hasReceivedEvent = true; }, onDone: expectAsync0(() { expect(hasReceivedEvent, isFalse); }, count: 1)); }); test('Rx.ignoreElements.reusable', () async { // ignore: deprecated_member_use_from_same_package final transformer = IgnoreElementsStreamTransformer<int>(); var hasReceivedEvent = false; _getStream().transform(transformer).listen((_) { hasReceivedEvent = true; }, onDone: expectAsync0(() { expect(hasReceivedEvent, isFalse); }, count: 1)); _getStream().transform(transformer).listen((_) { hasReceivedEvent = true; }, onDone: expectAsync0(() { expect(hasReceivedEvent, isFalse); }, count: 1)); }); test('Rx.ignoreElements.asBroadcastStream', () async { // ignore: deprecated_member_use_from_same_package final stream = _getStream().asBroadcastStream().ignoreElements(); // listen twice on same stream stream.listen(null); stream.listen(null); // code should reach here await expectLater(true, true); }); test('Rx.ignoreElements.pause.resume', () async { var hasReceivedEvent = false; // ignore: deprecated_member_use_from_same_package _getStream().ignoreElements().listen((_) { hasReceivedEvent = true; }, onDone: expectAsync0(() { expect(hasReceivedEvent, isFalse); }, count: 1)) ..pause() ..resume(); }); test('Rx.ignoreElements.error.shouldThrow', () async { // ignore: deprecated_member_use_from_same_package final streamWithError = Stream<void>.error(Exception()).ignoreElements(); streamWithError.listen(null, onError: expectAsync2((Exception e, StackTrace s) { expect(e, isException); }, count: 1)); }); test('Rx.flatMap accidental broadcast', () async { final controller = StreamController<int>(); // ignore: deprecated_member_use_from_same_package final stream = controller.stream.ignoreElements(); stream.listen(null); expect(() => stream.listen(null), throwsStateError); controller.add(1); }); }
rxdart/test/transformers/ignore_elements_test.dart/0
{'file_path': 'rxdart/test/transformers/ignore_elements_test.dart', 'repo_id': 'rxdart', 'token_count': 1057}
import 'dart:async'; import 'package:rxdart/rxdart.dart'; import 'package:test/test.dart'; void main() { test('Rx.switchIfEmpty.whenEmpty', () async { expect( Stream<int>.empty().switchIfEmpty(Stream.value(1)), emitsInOrder(<dynamic>[1, emitsDone]), ); }); test('Rx.initial.completes', () async { expect( Stream.value(99).switchIfEmpty(Stream.value(1)), emitsInOrder(<dynamic>[99, emitsDone]), ); }); test('Rx.switchIfEmpty.reusable', () async { final transformer = SwitchIfEmptyStreamTransformer<bool>( Stream.value(true).asBroadcastStream()); Stream<bool>.empty().transform(transformer).listen(expectAsync1((result) { expect(result, true); }, count: 1)); Stream<bool>.empty().transform(transformer).listen(expectAsync1((result) { expect(result, true); }, count: 1)); }); test('Rx.switchIfEmpty.whenNotEmpty', () async { Stream.value(false) .switchIfEmpty(Stream.value(true)) .listen(expectAsync1((result) { expect(result, false); }, count: 1)); }); test('Rx.switchIfEmpty.asBroadcastStream', () async { final stream = Stream<int>.empty().switchIfEmpty(Stream.value(1)).asBroadcastStream(); // listen twice on same stream stream.listen(null); stream.listen(null); // code should reach here await expectLater(stream.isBroadcast, isTrue); }); test('Rx.switchIfEmpty.error.shouldThrowA', () async { final streamWithError = Stream<int>.error(Exception()).switchIfEmpty(Stream.value(1)); streamWithError.listen(null, onError: expectAsync2((Exception e, StackTrace s) { expect(e, isException); })); }); test('Rx.switchIfEmpty.error.shouldThrowB', () { expect(() => Stream<void>.empty().switchIfEmpty(null), throwsArgumentError); }); test('Rx.switchIfEmpty.pause.resume', () async { StreamSubscription<int> subscription; final stream = Stream<int>.empty().switchIfEmpty(Stream.value(1)); subscription = stream.listen(expectAsync1((value) { expect(value, 1); subscription.cancel(); }, count: 1)); subscription.pause(); subscription.resume(); }); test('Rx.switchIfEmpty accidental broadcast', () async { final controller = StreamController<int>(); final stream = controller.stream.switchIfEmpty(Stream<int>.empty()); stream.listen(null); expect(() => stream.listen(null), throwsStateError); controller.add(1); }); }
rxdart/test/transformers/switch_if_empty_test.dart/0
{'file_path': 'rxdart/test/transformers/switch_if_empty_test.dart', 'repo_id': 'rxdart', 'token_count': 949}
// 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:math'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:sensors/sensors.dart'; // This is on alternate entrypoint for this module to display Flutter UI in // a (multi-)view integration scenario. void main() { runApp(const Cell()); } class Cell extends StatefulWidget { const Cell({super.key}); @override State<StatefulWidget> createState() => _CellState(); } class _CellState extends State<Cell> with WidgetsBindingObserver { static const double gravity = 9.81; static final AccelerometerEvent defaultPosition = AccelerometerEvent(0, 0, 0); int cellNumber = 0; Random? _random; AppLifecycleState? appLifecycleState; @override void initState() { const channel = MethodChannel('dev.flutter.example/cell'); channel.setMethodCallHandler((call) async { if (call.method == 'setCellNumber') { setState(() { cellNumber = call.arguments as int; _random = Random(cellNumber); }); } }); // Keep track of what the current platform lifecycle state is. WidgetsBinding.instance.addObserver(this); super.initState(); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { setState(() { appLifecycleState = state; }); } // Show a random bright color. Color randomLightColor() { _random ??= Random(cellNumber); return Color.fromARGB(255, _random!.nextInt(50) + 205, _random!.nextInt(50) + 205, _random!.nextInt(50) + 205); } @override Widget build(BuildContext context) { return MaterialApp( // The Flutter cells will be noticeably different (due to background color // and the Flutter logo). The banner breaks immersion. debugShowCheckedModeBanner: false, home: Container( color: Colors.white, child: Builder( builder: (context) { return Card( // Mimic the platform Material look. margin: const EdgeInsets.symmetric(horizontal: 36, vertical: 24), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), elevation: 16, color: randomLightColor(), child: Stack( children: [ Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( // Show a number provided by the platform based on // the cell's index. cellNumber.toString(), style: Theme.of(context).textTheme.displaySmall, ), ], ), ), Positioned( left: 42, top: 0, bottom: 0, child: Opacity( opacity: 0.2, child: StreamBuilder<AccelerometerEvent>( // Don't continuously rebuild for nothing when the // cell isn't visible. stream: appLifecycleState == AppLifecycleState.resumed ? accelerometerEvents : Stream.value(defaultPosition), initialData: defaultPosition, builder: (context, snapshot) { return Transform( // Figure out the phone's orientation relative // to gravity's direction. Ignore the z vector. transform: Matrix4.rotationX( snapshot.data!.y / gravity * pi / 2) ..multiply(Matrix4.rotationY( snapshot.data!.x / gravity * pi / 2)), alignment: Alignment.center, child: const FlutterLogo(size: 72)); }, ), ), ), ], ), ); }, ), ), ); } }
samples/add_to_app/android_view/flutter_module_using_plugin/lib/cell.dart/0
{'file_path': 'samples/add_to_app/android_view/flutter_module_using_plugin/lib/cell.dart', 'repo_id': 'samples', 'token_count': 2266}
name: flutter_module_books description: A Flutter module using the Pigeon package to demonstrate integrating Flutter in a realistic scenario where the existing platform app already has business logic and middleware constraints. version: 1.0.0+1 environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter dev_dependencies: analysis_defaults: path: ../../../analysis_defaults pigeon: ">=11.0.0 <17.0.0" flutter_test: sdk: flutter flutter: uses-material-design: true # This section identifies your Flutter project as a module meant for # embedding in a native host app. These identifiers should _not_ ordinarily # be changed after generation - they are used to ensure that the tooling can # maintain consistency when adding or modifying assets and plugins. # They also do not have any bearing on your native host application's # identifiers, which may be completely independent or the same as these. module: androidX: true androidPackage: dev.flutter.example.flutter_module_books iosBundleIdentifier: dev.flutter.example.flutterModuleBooks
samples/add_to_app/books/flutter_module_books/pubspec.yaml/0
{'file_path': 'samples/add_to_app/books/flutter_module_books/pubspec.yaml', 'repo_id': 'samples', 'token_count': 322}
// 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:flutter/services.dart'; import 'package:provider/provider.dart'; /// The entrypoint for the flutter module. void main() { // This call ensures the Flutter binding has been set up before creating the // MethodChannel-based model. WidgetsFlutterBinding.ensureInitialized(); final model = CounterModel(); runApp( ChangeNotifierProvider.value( value: model, child: const MyApp(), ), ); } /// A simple model that uses a [MethodChannel] as the source of truth for the /// state of a counter. /// /// Rather than storing app state data within the Flutter module itself (where /// the native portions of the app can't access it), this module passes messages /// back to the containing app whenever it needs to increment or retrieve the /// value of the counter. class CounterModel extends ChangeNotifier { CounterModel() { _channel.setMethodCallHandler(_handleMessage); _channel.invokeMethod<void>('requestCounter'); } final _channel = const MethodChannel('dev.flutter.example/counter'); int _count = 0; int get count => _count; void increment() { _channel.invokeMethod<void>('incrementCounter'); } Future<dynamic> _handleMessage(MethodCall call) async { if (call.method == 'reportCounter') { _count = call.arguments as int; notifyListeners(); } } } /// The "app" displayed by this module. /// /// It offers two routes, one suitable for displaying as a full screen and /// another designed to be part of a larger UI.class MyApp extends StatelessWidget { class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Module Title', theme: ThemeData.light(useMaterial3: true), routes: { '/': (context) => const FullScreenView(), '/mini': (context) => const Contents(), }, ); } } /// Wraps [Contents] in a Material [Scaffold] so it looks correct when displayed /// full-screen. class FullScreenView extends StatelessWidget { const FullScreenView({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Full-screen Flutter'), ), body: const Contents(showExit: true), ); } } /// The actual content displayed by the module. /// /// This widget displays info about the state of a counter and how much room (in /// logical pixels) it's been given. It also offers buttons to increment the /// counter and (optionally) close the Flutter view. class Contents extends StatelessWidget { final bool showExit; const Contents({this.showExit = false, super.key}); @override Widget build(BuildContext context) { final mediaInfo = MediaQuery.of(context); return SizedBox.expand( child: Stack( children: [ Positioned.fill( child: DecoratedBox( decoration: BoxDecoration( color: Theme.of(context).scaffoldBackgroundColor, ), ), ), const Positioned.fill( child: Opacity( opacity: .25, child: FittedBox( fit: BoxFit.cover, child: FlutterLogo(), ), ), ), Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Window is ${mediaInfo.size.width.toStringAsFixed(1)} x ' '${mediaInfo.size.height.toStringAsFixed(1)}', style: Theme.of(context).textTheme.headlineSmall, ), const SizedBox(height: 16), Consumer<CounterModel>( builder: (context, model, child) { return Text( 'Taps: ${model.count}', style: Theme.of(context).textTheme.headlineSmall, ); }, ), const SizedBox(height: 16), Consumer<CounterModel>( builder: (context, model, child) { return ElevatedButton( onPressed: () => model.increment(), child: const Text('Tap me!'), ); }, ), if (showExit) ...[ const SizedBox(height: 16), ElevatedButton( onPressed: () => SystemNavigator.pop(animated: true), child: const Text('Exit this screen'), ), ], ], ), ), ], ), ); } }
samples/add_to_app/fullscreen/flutter_module/lib/main.dart/0
{'file_path': 'samples/add_to_app/fullscreen/flutter_module/lib/main.dart', 'repo_id': 'samples', 'token_count': 2117}
include: package:analysis_defaults/flutter.yaml
samples/add_to_app/plugin/flutter_module_using_plugin/analysis_options.yaml/0
{'file_path': 'samples/add_to_app/plugin/flutter_module_using_plugin/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 'package:flutter/material.dart'; class PageRouteBuilderDemo extends StatelessWidget { const PageRouteBuilderDemo({super.key}); static const String routeName = 'basics/page_route_builder'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Page 1'), ), body: Center( child: ElevatedButton( child: const Text('Go!'), onPressed: () { Navigator.of(context).push<void>(_createRoute()); }, ), ), ); } } Route _createRoute() { return PageRouteBuilder<SlideTransition>( pageBuilder: (context, animation, secondaryAnimation) => _Page2(), transitionsBuilder: (context, animation, secondaryAnimation, child) { var tween = Tween<Offset>(begin: const Offset(0.0, 1.0), end: Offset.zero); var curveTween = CurveTween(curve: Curves.ease); return SlideTransition( position: animation.drive(curveTween).drive(tween), child: child, ); }, ); } class _Page2 extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Page 2'), ), body: Center( child: Text('Page 2!', style: Theme.of(context).textTheme.headlineMedium), ), ); } }
samples/animations/lib/src/basics/page_route_builder.dart/0
{'file_path': 'samples/animations/lib/src/basics/page_route_builder.dart', 'repo_id': 'samples', 'token_count': 614}
name: shared description: Common data models required by our client and server version: 1.0.0 environment: sdk: ^3.2.0 dependencies: freezed_annotation: ^2.1.0 json_annotation: ^4.7.0 dev_dependencies: build_runner: ^2.2.1 freezed: ^2.1.1 json_serializable: ^6.4.0 lints: ">=2.0.0 <4.0.0" test: ^1.16.0
samples/code_sharing/shared/pubspec.yaml/0
{'file_path': 'samples/code_sharing/shared/pubspec.yaml', 'repo_id': 'samples', 'token_count': 144}
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; typedef PlatformCallback = void Function(TargetPlatform platform); class PlatformSelector extends StatefulWidget { const PlatformSelector({ super.key, required this.onChangedPlatform, }); final PlatformCallback onChangedPlatform; @override State<PlatformSelector> createState() => _PlatformSelectorState(); } class _PlatformSelectorState extends State<PlatformSelector> { static const int targetPlatformStringLength = 15; // 'TargetPlatform.'.length static String _platformToString(TargetPlatform platform) { return platform.toString().substring(targetPlatformStringLength); } final TargetPlatform originaPlatform = defaultTargetPlatform; @override Widget build(BuildContext context) { return SizedBox( width: 170.0, child: DropdownButton<TargetPlatform>( value: defaultTargetPlatform, icon: const Icon(Icons.arrow_downward), elevation: 16, onChanged: (value) { if (value == null) { return; } widget.onChangedPlatform(value); setState(() {}); }, items: TargetPlatform.values.map((platform) { return DropdownMenuItem<TargetPlatform>( value: platform, child: Row( children: <Widget>[ if (platform == originaPlatform) const Icon( Icons.home, color: Color(0xff616161), ), Text(_platformToString(platform)), ], ), ); }).toList(), ), ); } }
samples/context_menus/lib/platform_selector.dart/0
{'file_path': 'samples/context_menus/lib/platform_selector.dart', 'repo_id': 'samples', 'token_count': 698}
import 'package:context_menus/custom_menu_page.dart'; import 'package:context_menus/main.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Shows default buttons in a custom context menu', (tester) async { await tester.pumpWidget(const MyApp()); // Navigate to the CustomMenuPage example. await tester.dragUntilVisible( find.text(CustomMenuPage.title), find.byType(ListView), const Offset(0.0, -200.0), ); await tester.pumpAndSettle(); await tester.tap(find.text(CustomMenuPage.title)); await tester.pumpAndSettle(); // Right click on the text field to show the context menu. final TestGesture gesture = await tester.startGesture( tester.getCenter(find.byType(EditableText)), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await gesture.removePointer(); await tester.pumpAndSettle(); // A custom context menu is shown, and the buttons are the default ones. expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); expect(find.byType(CupertinoAdaptiveTextSelectionToolbar), findsNothing); switch (defaultTargetPlatform) { case TargetPlatform.iOS: expect( find.byType(CupertinoTextSelectionToolbarButton), findsNWidgets(2)); case TargetPlatform.macOS: expect(find.byType(CupertinoDesktopTextSelectionToolbarButton), findsNWidgets(2)); case TargetPlatform.android: case TargetPlatform.fuchsia: expect(find.byType(TextSelectionToolbarTextButton), findsNWidgets(1)); case TargetPlatform.linux: case TargetPlatform.windows: expect( find.byType(DesktopTextSelectionToolbarButton), findsNWidgets(1)); } }); }
samples/context_menus/test/custom_menu_page_test.dart/0
{'file_path': 'samples/context_menus/test/custom_menu_page_test.dart', 'repo_id': 'samples', 'token_count': 743}
// Copyright 2018-present the Flutter authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. enum Category { all, accessories, clothing, home, } class ProductsRepository { static const _allProducts = <Product>[ Product( category: Category.accessories, id: 0, name: 'Vagabond sack', price: 120, ), Product( category: Category.accessories, id: 1, name: 'Stella sunglasses', price: 58, ), Product( category: Category.accessories, id: 2, name: 'Whitney belt', price: 35, ), Product( category: Category.accessories, id: 3, name: 'Garden strand', price: 98, ), Product( category: Category.accessories, id: 4, name: 'Strut earrings', price: 34, ), Product( category: Category.accessories, id: 5, name: 'Varsity socks', price: 12, ), Product( category: Category.accessories, id: 6, name: 'Weave keyring', price: 16, ), Product( category: Category.accessories, id: 7, name: 'Gatsby hat', price: 40, ), Product( category: Category.accessories, id: 8, name: 'Shrug bag', price: 198, ), Product( category: Category.home, id: 9, name: 'Gilt desk trio', price: 58, ), Product( category: Category.home, id: 10, name: 'Copper wire rack', price: 18, ), Product( category: Category.home, id: 11, name: 'Soothe ceramic set', price: 28, ), Product( category: Category.home, id: 12, name: 'Hurrahs tea set', price: 34, ), Product( category: Category.home, id: 13, name: 'Blue stone mug', price: 18, ), Product( category: Category.home, id: 14, name: 'Rainwater tray', price: 27, ), Product( category: Category.home, id: 15, name: 'Chambray napkins', price: 16, ), Product( category: Category.home, id: 16, name: 'Succulent planters', price: 16, ), Product( category: Category.home, id: 17, name: 'Quartet table', price: 175, ), Product( category: Category.home, id: 18, name: 'Kitchen quattro', price: 129, ), Product( category: Category.clothing, id: 19, name: 'Clay sweater', price: 48, ), Product( category: Category.clothing, id: 20, name: 'Sea tunic', price: 45, ), Product( category: Category.clothing, id: 21, name: 'Plaster tunic', price: 38, ), Product( category: Category.clothing, id: 22, name: 'White pinstripe shirt', price: 70, ), Product( category: Category.clothing, id: 23, name: 'Chambray shirt', price: 70, ), Product( category: Category.clothing, id: 24, name: 'Seabreeze sweater', price: 60, ), Product( category: Category.clothing, id: 25, name: 'Gentry jacket', price: 178, ), Product( category: Category.clothing, id: 26, name: 'Navy trousers', price: 74, ), Product( category: Category.clothing, id: 27, name: 'Walter henley (white)', price: 38, ), Product( category: Category.clothing, id: 28, name: 'Surf and perf shirt', price: 48, ), Product( category: Category.clothing, id: 29, name: 'Ginger scarf', price: 98, ), Product( category: Category.clothing, id: 30, name: 'Ramona crossover', price: 68, ), Product( category: Category.clothing, id: 31, name: 'Chambray shirt', price: 38, ), Product( category: Category.clothing, id: 32, name: 'Classic white collar', price: 58, ), Product( category: Category.clothing, id: 33, name: 'Cerise scallop tee', price: 42, ), Product( category: Category.clothing, id: 34, name: 'Shoulder rolls tee', price: 27, ), Product( category: Category.clothing, id: 35, name: 'Grey slouch tank', price: 24, ), Product( category: Category.clothing, id: 36, name: 'Sunshirt dress', price: 58, ), Product( category: Category.clothing, id: 37, name: 'Fine lines tee', price: 58, ), ]; static List<Product> loadProducts({Category category = Category.all}) { if (category == Category.all) { return _allProducts; } else { return _allProducts.where((p) => p.category == category).toList(); } } static Product loadProduct({required int id}) { return _allProducts.firstWhere((Product p) => p.id == id); } } String getCategoryTitle(Category category) => switch (category) { Category.all => 'All', Category.accessories => 'Accessories', Category.clothing => 'Clothing', Category.home => 'Home Decorations' }; class Product { const Product({ required this.category, required this.id, required this.name, required this.price, }); final Category category; final int id; final String name; final int price; String get assetName => '$id-0.jpg'; String get assetName2X => '2.0x/$id-0.jpg'; String get assetPackage => 'shrine_images'; @override String toString() => '$name (id=$id)'; }
samples/deeplink_store_example/lib/model/products_repository.dart/0
{'file_path': 'samples/deeplink_store_example/lib/model/products_repository.dart', 'repo_id': 'samples', 'token_count': 2739}
// 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:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; import 'package:built_value/standard_json_plugin.dart'; import 'model/search.dart'; import 'unsplash/api_error.dart'; import 'unsplash/current_user_collections.dart'; import 'unsplash/exif.dart'; import 'unsplash/links.dart'; import 'unsplash/location.dart'; import 'unsplash/photo.dart'; import 'unsplash/position.dart'; import 'unsplash/search_photos_response.dart'; import 'unsplash/tags.dart'; import 'unsplash/urls.dart'; import 'unsplash/user.dart'; part 'serializers.g.dart'; //add all of the built value types that require serialization @SerializersFor([Search, ApiError, Photo, SearchPhotosResponse]) final Serializers serializers = (_$serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build();
samples/desktop_photo_search/fluent_ui/lib/src/serializers.dart/0
{'file_path': 'samples/desktop_photo_search/fluent_ui/lib/src/serializers.dart', 'repo_id': 'samples', 'token_count': 322}
// 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:convert'; import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; import '../serializers.dart'; import 'photo.dart'; part 'search_photos_response.g.dart'; abstract class SearchPhotosResponse implements Built<SearchPhotosResponse, SearchPhotosResponseBuilder> { factory SearchPhotosResponse( [void Function(SearchPhotosResponseBuilder)? updates]) = _$SearchPhotosResponse; SearchPhotosResponse._(); @BuiltValueField(wireName: 'total') int? get total; @BuiltValueField(wireName: 'total_pages') int? get totalPages; @BuiltValueField(wireName: 'results') BuiltList<Photo> get results; String toJson() { return json.encode( serializers.serializeWith(SearchPhotosResponse.serializer, this)); } static SearchPhotosResponse? fromJson(String jsonString) { return serializers.deserializeWith( SearchPhotosResponse.serializer, json.decode(jsonString)); } static Serializer<SearchPhotosResponse> get serializer => _$searchPhotosResponseSerializer; }
samples/desktop_photo_search/fluent_ui/lib/src/unsplash/search_photos_response.dart/0
{'file_path': 'samples/desktop_photo_search/fluent_ui/lib/src/unsplash/search_photos_response.dart', 'repo_id': 'samples', 'token_count': 402}
// 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:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:logging/logging.dart'; import 'package:menubar/menubar.dart' as menubar; import 'package:provider/provider.dart'; import 'package:window_size/window_size.dart'; import 'src/model/photo_search_model.dart'; import 'src/unsplash/unsplash.dart'; import 'src/widgets/photo_search_dialog.dart'; import 'src/widgets/policy_dialog.dart'; import 'src/widgets/unsplash_notice.dart'; import 'src/widgets/unsplash_search_content.dart'; import 'unsplash_access_key.dart'; void main() { Logger.root.level = Level.ALL; Logger.root.onRecord.listen((rec) { // ignore: avoid_print print('${rec.loggerName} ${rec.level.name}: ${rec.time}: ${rec.message}'); }); if (unsplashAccessKey.isEmpty) { Logger('main').severe('Unsplash Access Key is required. ' 'Please add to `lib/unsplash_access_key.dart`.'); exit(1); } setupWindow(); runApp( ChangeNotifierProvider<PhotoSearchModel>( create: (context) => PhotoSearchModel( Unsplash(accessKey: unsplashAccessKey), ), child: const UnsplashSearchApp(), ), ); } const double windowWidth = 1024; const double windowHeight = 800; void setupWindow() { if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) { WidgetsFlutterBinding.ensureInitialized(); setWindowMinSize(const Size(windowWidth, windowHeight)); } } class UnsplashSearchApp extends StatelessWidget { const UnsplashSearchApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Photo Search', theme: ThemeData( colorSchemeSeed: Colors.orange, useMaterial3: true, ), home: const UnsplashHomePage(title: 'Photo Search'), ); } } class UnsplashHomePage extends StatelessWidget { const UnsplashHomePage({required this.title, super.key}); final String title; @override Widget build(BuildContext context) { final photoSearchModel = Provider.of<PhotoSearchModel>(context); menubar.setApplicationMenu([ menubar.NativeSubmenu(label: 'Search', children: [ menubar.NativeMenuItem( label: 'Search…', onSelected: () { showDialog<void>( context: context, builder: (context) => PhotoSearchDialog(callback: photoSearchModel.addSearch), ); }, ), if (!Platform.isMacOS) menubar.NativeMenuItem( label: 'Quit', onSelected: () { SystemNavigator.pop(); }, ), ]), menubar.NativeSubmenu(label: 'About', children: [ menubar.NativeMenuItem( label: 'About', onSelected: () { showDialog<void>( context: context, builder: (context) => const PolicyDialog(), ); }, ), ]) ]); return UnsplashNotice( child: Scaffold( appBar: AppBar( title: Text(title), ), body: photoSearchModel.entries.isNotEmpty ? const UnsplashSearchContent() : const Center( child: Text('Search for Photos using the Fab button'), ), floatingActionButton: FloatingActionButton( onPressed: () => showDialog<void>( context: context, builder: (context) => PhotoSearchDialog(callback: photoSearchModel.addSearch), ), tooltip: 'Search for a photo', child: const Icon(Icons.search), ), ), ); } }
samples/desktop_photo_search/material/lib/main.dart/0
{'file_path': 'samples/desktop_photo_search/material/lib/main.dart', 'repo_id': 'samples', 'token_count': 1651}
include: package:analysis_defaults/flutter.yaml
samples/experimental/federated_plugin/federated_plugin/example/analysis_options.yaml/0
{'file_path': 'samples/experimental/federated_plugin/federated_plugin/example/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 'dart:html' as html; import 'package:federated_plugin_platform_interface/federated_plugin_platform_interface.dart'; import 'package:flutter/services.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; /// Web Implementation of [FederatedPluginInterface] to retrieve current battery /// level of device. class FederatedPlugin extends FederatedPluginInterface { final html.Navigator _navigator; /// Constructor to override the navigator object for testing purpose. FederatedPlugin({html.Navigator? navigator}) : _navigator = navigator ?? html.window.navigator; /// Method to register the plugin which sets [FederatedPlugin] to be the default /// instance of [FederatedPluginInterface]. static void registerWith(Registrar registrar) { FederatedPluginInterface.instance = FederatedPlugin(); } /// Returns the current battery level of device. /// /// If any error, it's assume that the BatteryManager API is not supported by /// browser. @override Future<int> getBatteryLevel() async { try { final battery = await _navigator.getBattery() as html.BatteryManager; // The battery level retrieved is in range of 0.0 to 1.0. return battery.level! * 100 as int; } catch (error) { throw PlatformException( code: 'STATUS_UNAVAILABLE', message: 'The plugin is not supported by the browser.', details: null, ); } } }
samples/experimental/federated_plugin/federated_plugin_web/lib/federated_plugin_web.dart/0
{'file_path': 'samples/experimental/federated_plugin/federated_plugin_web/lib/federated_plugin_web.dart', 'repo_id': 'samples', 'token_count': 489}
// 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:context_menus/context_menus.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart' show SystemUiOverlayStyle; import 'package:linting_tool/layout/adaptive.dart'; import 'package:linting_tool/model/editing_controller.dart'; import 'package:linting_tool/model/profiles_store.dart'; import 'package:linting_tool/widgets/saved_rule_tile.dart'; import 'package:provider/provider.dart'; class RulesPage extends StatelessWidget { final int selectedProfileIndex; const RulesPage({ required this.selectedProfileIndex, super.key, }); @override Widget build(BuildContext context) { final isDesktop = isDisplayLarge(context); final isTablet = isDisplayMedium(context); final textTheme = Theme.of(context).textTheme; final startPadding = isTablet ? 60.0 : isDesktop ? 120.0 : 16.0; final endPadding = isTablet ? 60.0 : isDesktop ? 120.0 : 4.0; return Scaffold( appBar: AppBar( title: Text( context .read<ProfilesStore>() .savedProfiles[selectedProfileIndex] .name, style: textTheme.titleSmall!.copyWith( color: textTheme.bodyLarge!.color, ), ), leading: Padding( padding: const EdgeInsets.only(left: 80.0), child: TextButton.icon( onPressed: () { Navigator.pop(context); }, icon: const Icon(Icons.arrow_back_ios_new), label: const Text('Back'), ), ), leadingWidth: 160.0, toolbarHeight: 38.0, backgroundColor: Colors.white, systemOverlayStyle: SystemUiOverlayStyle.dark, ), /// ContextMenuOverlay is required to show /// right-click context menus using ContextMenuRegion. body: ContextMenuOverlay( child: Consumer<ProfilesStore>( builder: (context, profilesStore, child) { var profile = profilesStore.savedProfiles[selectedProfileIndex]; return profile.rules.isEmpty ? const Center( child: Text('There are no rules added to the profile.'), ) : Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: ListView.separated( padding: EdgeInsetsDirectional.only( start: startPadding, end: endPadding, top: isDesktop ? 28 : 16, bottom: isDesktop ? kToolbarHeight : 16, ), itemCount: profile.rules.length, cacheExtent: 5, itemBuilder: (context, index) { /// Show right-click context menu to delete rule. return ContextMenuRegion( contextMenu: GenericContextMenu( buttonConfigs: [ ContextMenuButtonConfig( 'Remove rule from profile', onPressed: () { context .read<ProfilesStore>() .removeRuleFromProfile( profile, profile.rules[index]); }, ), ], ), child: SavedRuleTile( rule: profile.rules[index], ), ); }, separatorBuilder: (context, index) => const SizedBox(height: 4), ), ), Padding( padding: const EdgeInsetsDirectional.only(top: 28), child: Row( children: [ Consumer<EditingController>( builder: (context, editingController, child) { var isEditing = editingController.isEditing; return isEditing ? Column( children: [ IconButton( icon: const Icon(Icons.done), onPressed: () { editingController.isEditing = false; }, ), if (editingController .selectedRules.isNotEmpty) IconButton( icon: const Icon(Icons.delete), onPressed: () { editingController .deleteSelected( profile, profilesStore, ); }, ), ], ) : IconButton( icon: const Icon(Icons.edit), onPressed: () { editingController.isEditing = true; }, ); }, ), SizedBox( width: isTablet ? 30 : isDesktop ? 60 : 16), ], ), ), ], ); }, ), ), ); } }
samples/experimental/linting_tool/lib/pages/rules_page.dart/0
{'file_path': 'samples/experimental/linting_tool/lib/pages/rules_page.dart', 'repo_id': 'samples', 'token_count': 4483}
name: linting_tool description: A new Flutter project. version: 1.0.0+1 publish_to: "none" environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter adaptive_breakpoints: ^0.1.1 cupertino_icons: ^1.0.2 equatable: ^2.0.3 file_selector: ^1.0.0 flutter_markdown: ^0.6.2 google_fonts: ^6.0.0 hive: ^2.0.4 hive_flutter: ^1.1.0 http: ^1.0.0 json2yaml: ^3.0.0 json_annotation: ^4.8.1 mockito: ^5.0.13 provider: ^6.0.2 yaml: ^3.1.0 context_menus: ^1.0.1 window_size: git: url: https://github.com/google/flutter-desktop-embedding.git path: plugins/window_size dev_dependencies: analysis_defaults: path: ../../analysis_defaults flutter_test: sdk: flutter build_runner: ^2.4.6 hive_generator: ^2.0.0 json_serializable: ^6.7.1 flutter: uses-material-design: true
samples/experimental/linting_tool/pubspec.yaml/0
{'file_path': 'samples/experimental/linting_tool/pubspec.yaml', 'repo_id': 'samples', 'token_count': 399}
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:fl_chart/fl_chart.dart'; import 'steps_repo.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, useMaterial3: true, ), home: const Home(), ); } } class RoundClipper extends CustomClipper<Path> { @override Path getClip(Size size) { final diameter = size.shortestSide * 1.5; final x = -(diameter - size.width) / 2; final y = size.height - diameter; final rect = Offset(x, y) & Size(diameter, diameter); return Path()..addOval(rect); } @override bool shouldReclip(CustomClipper<Path> oldClipper) { return false; } } class Home extends StatefulWidget { const Home({super.key}); @override State<Home> createState() => _HomeState(); } class _HomeState extends State<Home> { var hourlySteps = <Steps>[]; DateTime? lastUpdated; @override void initState() { runPedometer(); super.initState(); } void runPedometer() async { final now = DateTime.now(); hourlySteps = await StepsRepo.instance.getSteps(); lastUpdated = now; setState(() {}); } @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; final barGroups = hourlySteps .map( (e) => BarChartGroupData( x: int.parse(e.startHour), barRods: [ BarChartRodData( color: Colors.blue[900], toY: e.steps.toDouble() / 100, ) ], ), ) .toList(); return Scaffold( body: Stack( children: [ ClipPath( clipper: RoundClipper(), child: FractionallySizedBox( heightFactor: 0.55, widthFactor: 1, child: Container(color: Colors.blue[300]), ), ), Align( alignment: Alignment.topCenter, child: Padding( padding: const EdgeInsets.all(80.0), child: Column( children: [ lastUpdated != null ? Padding( padding: const EdgeInsets.symmetric(vertical: 50.0), child: Text( DateFormat.yMMMMd('en_US').format(lastUpdated!), style: textTheme.titleLarge! .copyWith(color: Colors.blue[900]), ), ) : const SizedBox(height: 0), Text( hourlySteps.fold(0, (t, e) => t + e.steps).toString(), style: textTheme.displayMedium!.copyWith(color: Colors.white), ), Text( 'steps', style: textTheme.titleLarge!.copyWith(color: Colors.white), ) ], ), ), ), Align( alignment: Alignment.centerRight, child: GestureDetector( onTap: runPedometer, child: Padding( padding: const EdgeInsets.all(20.0), child: Container( decoration: BoxDecoration( color: Colors.blue[900], shape: BoxShape.circle, ), child: const Padding( padding: EdgeInsets.all(8.0), child: Icon( Icons.refresh, color: Colors.white, size: 50, ), ), ), ), ), ), Align( alignment: Alignment.bottomCenter, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 30.0, vertical: 50.0), child: AspectRatio( aspectRatio: 1.2, child: BarChart( BarChartData( titlesData: const FlTitlesData( show: true, // Top titles are null topTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)), rightTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)), leftTitles: AxisTitles( sideTitles: SideTitles( showTitles: false, ), ), bottomTitles: AxisTitles( sideTitles: SideTitles( showTitles: true, reservedSize: 30, getTitlesWidget: getBottomTitles, ), ), ), borderData: FlBorderData( show: false, ), barGroups: barGroups, gridData: const FlGridData(show: false), alignment: BarChartAlignment.spaceAround, ), ), ), ), ), ], )); } } // Axis labels for bottom of chart Widget getBottomTitles(double value, TitleMeta meta) { String text; switch (value.toInt()) { case 0: text = '12AM'; break; case 6: text = '6AM'; break; case 12: text = '12PM'; break; case 18: text = '6PM'; break; default: text = ''; } return SideTitleWidget( axisSide: meta.axisSide, space: 4, child: Text(text, style: TextStyle(fontSize: 14, color: Colors.blue[900])), ); }
samples/experimental/pedometer/example/lib/main.dart/0
{'file_path': 'samples/experimental/pedometer/example/lib/main.dart', 'repo_id': 'samples', 'token_count': 3225}
// 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 'dart:math'; import 'package:flutter/material.dart'; import '../components/components.dart'; import '../page_content/wallpapers_flow.dart'; import 'pages.dart'; class PagesFlow extends StatefulWidget { const PagesFlow({super.key}); static const pageScrollDuration = 400; @override State<PagesFlow> createState() => _PagesFlowState(); } class _PagesFlowState extends State<PagesFlow> { late PageController pageController = PageController(); @override Widget build(BuildContext context) { final double screenWidth = MediaQuery.of(context).size.width; final double screenHeight = MediaQuery.of(context).size.height; bool narrowView = screenWidth * 1.8 < screenHeight ? true : false; double puzzleSize = narrowView ? screenWidth * 1 : min(screenHeight * 0.6, screenWidth); double topBottomMargin = (screenHeight - puzzleSize) * 0.5; double wonkyCharLargeSize = topBottomMargin * 1.0; double wonkyCharSmallSize = wonkyCharLargeSize * 0.5; PageConfig pageConfig = PageConfig( screenWidth: screenWidth, screenHeight: screenHeight, narrowView: narrowView, puzzleSize: puzzleSize, pageController: pageController, wonkyCharLargeSize: wonkyCharLargeSize, wonkyCharSmallSize: wonkyCharSmallSize, ); return PageView( controller: pageController, physics: const NeverScrollableScrollPhysics(), scrollDirection: Axis.vertical, children: [ PageNarrativePre( pageConfig: pageConfig, ), PageWeight( pageConfig: pageConfig, ), PageAscenderDescender( pageConfig: pageConfig, ), PageOpticalSize( pageConfig: pageConfig, ), PageWidth( pageConfig: pageConfig, ), PageNarrativePost( pageConfig: pageConfig, ), const WallpapersFlow(), ], ); } } class PageConfig { final double screenWidth; final double screenHeight; final bool narrowView; final double puzzleSize; final PageController pageController; final double wonkyCharLargeSize; final double wonkyCharSmallSize; static double baseWeight = 800; const PageConfig({ Key? key, required this.screenWidth, required this.screenHeight, required this.narrowView, required this.puzzleSize, required this.pageController, required this.wonkyCharLargeSize, required this.wonkyCharSmallSize, }); } class SinglePage extends StatefulWidget { final PageConfig pageConfig; const SinglePage({ super.key, required this.pageConfig, }); @override State<SinglePage> createState() => SinglePageState(); } class SinglePageState extends State<SinglePage> with TickerProviderStateMixin { List<Widget> buildWonkyChars() { return <Widget>[]; } Widget createPuzzle() { return Container(); } Widget createTopicIntro() { return LightboxedPanel( pageConfig: widget.pageConfig, content: const [], ); } @override Widget build(BuildContext context) { List<Widget> c = []; c.add(createPuzzle()); c += buildWonkyChars(); c.add(createTopicIntro()); return Stack( children: c, ); } void puzzleDone() {} } class NarrativePage extends StatefulWidget { final PageConfig pageConfig; const NarrativePage({ super.key, required this.pageConfig, }); @override State<NarrativePage> createState() => NarrativePageState(); } class NarrativePageState extends State<NarrativePage> with TickerProviderStateMixin { int panelIndex = 0; List<LightboxedPanel> panels = []; void handleIntroDismiss() { Future.delayed(const Duration(milliseconds: 50), () { setState(() { if (panelIndex == panels.length - 1) { widget.pageConfig.pageController.nextPage( duration: const Duration(milliseconds: PagesFlow.pageScrollDuration), curve: Curves.easeOut, ); } else { panelIndex++; } }); }); } @override Widget build(BuildContext context) { switch (panelIndex) { default: return Container(); } } void puzzleDone() {} }
samples/experimental/varfont_shader_puzzle/lib/page_content/pages_flow.dart/0
{'file_path': 'samples/experimental/varfont_shader_puzzle/lib/page_content/pages_flow.dart', 'repo_id': 'samples', 'token_count': 1624}
// 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. abstract class Auth { Future<bool> get isSignedIn; Future<User> signIn(); Future signOut(); } abstract class User { String get uid; } class SignInException implements Exception {}
samples/experimental/web_dashboard/lib/src/auth/auth.dart/0
{'file_path': 'samples/experimental/web_dashboard/lib/src/auth/auth.dart', 'repo_id': 'samples', 'token_count': 113}
// 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 'package:flutter_test/flutter_test.dart'; import 'package:web_dashboard/src/api/api.dart'; import 'package:web_dashboard/src/utils/chart_utils.dart'; void main() { group('chart utils', () { test('totals entries by day', () async { var entries = [ Entry(10, DateTime(2020, 3, 1)), Entry(10, DateTime(2020, 3, 1)), Entry(10, DateTime(2020, 3, 2)), ]; var totals = entryTotalsByDay(entries, 2, today: DateTime(2020, 3, 2)); expect(totals, hasLength(3)); expect(totals[1].value, 20); expect(totals[2].value, 10); }); test('days', () async { expect( DateTime.utc(2020, 1, 3).difference(DateTime.utc(2020, 1, 2)).inDays, 1); }); }); }
samples/experimental/web_dashboard/test/chart_utils_test.dart/0
{'file_path': 'samples/experimental/web_dashboard/test/chart_utils_test.dart', 'repo_id': 'samples', 'token_count': 395}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'sign_in_http.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** FormData _$FormDataFromJson(Map<String, dynamic> json) { return FormData( email: json['email'] as String?, password: json['password'] as String?, ); } Map<String, dynamic> _$FormDataToJson(FormData instance) => <String, dynamic>{ 'email': instance.email, 'password': instance.password, };
samples/form_app/lib/src/sign_in_http.g.dart/0
{'file_path': 'samples/form_app/lib/src/sign_in_http.g.dart', 'repo_id': 'samples', 'token_count': 166}
// 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 'package:flutter/foundation.dart'; import 'package:in_app_purchase/in_app_purchase.dart'; import 'package:logging/logging.dart'; import '../style/snack_bar.dart'; import 'ad_removal.dart'; /// Allows buying in-app. Facade of `package:in_app_purchase`. class InAppPurchaseController extends ChangeNotifier { static final Logger _log = Logger('InAppPurchases'); StreamSubscription<List<PurchaseDetails>>? _subscription; InAppPurchase inAppPurchaseInstance; AdRemovalPurchase _adRemoval = const AdRemovalPurchase.notStarted(); /// Creates a new [InAppPurchaseController] with an injected /// [InAppPurchase] instance. /// /// Example usage: /// /// var controller = InAppPurchaseController(InAppPurchase.instance); InAppPurchaseController(this.inAppPurchaseInstance); /// The current state of the ad removal purchase. AdRemovalPurchase get adRemoval => _adRemoval; /// Launches the platform UI for buying an in-app purchase. /// /// Currently, the only supported in-app purchase is ad removal. /// To support more, ad additional classes similar to [AdRemovalPurchase] /// and modify this method. Future<void> buy() async { if (!await inAppPurchaseInstance.isAvailable()) { _reportError('InAppPurchase.instance not available'); return; } _adRemoval = const AdRemovalPurchase.pending(); notifyListeners(); _log.info('Querying the store with queryProductDetails()'); final response = await inAppPurchaseInstance .queryProductDetails({AdRemovalPurchase.productId}); if (response.error != null) { _reportError('There was an error when making the purchase: ' '${response.error}'); return; } if (response.productDetails.length != 1) { _log.info( 'Products in response: ' '${response.productDetails.map((e) => '${e.id}: ${e.title}, ').join()}', ); _reportError('There was an error when making the purchase: ' 'product ${AdRemovalPurchase.productId} does not exist?'); return; } final productDetails = response.productDetails.single; _log.info('Making the purchase'); final purchaseParam = PurchaseParam(productDetails: productDetails); try { final success = await inAppPurchaseInstance.buyNonConsumable( purchaseParam: purchaseParam); _log.info('buyNonConsumable() request was sent with success: $success'); // The result of the purchase will be reported in the purchaseStream, // which is handled in [_listenToPurchaseUpdated]. } catch (e) { _log.severe( 'Problem with calling inAppPurchaseInstance.buyNonConsumable(): ' '$e'); } } @override void dispose() { _subscription?.cancel(); super.dispose(); } /// Asks the underlying platform to list purchases that have been already /// made (for example, in a previous session of the game). Future<void> restorePurchases() async { if (!await inAppPurchaseInstance.isAvailable()) { _reportError('InAppPurchase.instance not available'); return; } try { await inAppPurchaseInstance.restorePurchases(); } catch (e) { _log.severe('Could not restore in-app purchases: $e'); } _log.info('In-app purchases restored'); } /// Subscribes to the [inAppPurchaseInstance.purchaseStream]. void subscribe() { _subscription?.cancel(); _subscription = inAppPurchaseInstance.purchaseStream.listen((purchaseDetailsList) { _listenToPurchaseUpdated(purchaseDetailsList); }, onDone: () { _subscription?.cancel(); }, onError: (dynamic error) { _log.severe('Error occurred on the purchaseStream: $error'); }); } Future<void> _listenToPurchaseUpdated( List<PurchaseDetails> purchaseDetailsList) async { for (final purchaseDetails in purchaseDetailsList) { _log.info(() => 'New PurchaseDetails instance received: ' 'productID=${purchaseDetails.productID}, ' 'status=${purchaseDetails.status}, ' 'purchaseID=${purchaseDetails.purchaseID}, ' 'error=${purchaseDetails.error}, ' 'pendingCompletePurchase=${purchaseDetails.pendingCompletePurchase}'); if (purchaseDetails.productID != AdRemovalPurchase.productId) { _log.severe("The handling of the product with id " "'${purchaseDetails.productID}' is not implemented."); _adRemoval = const AdRemovalPurchase.notStarted(); notifyListeners(); continue; } switch (purchaseDetails.status) { case PurchaseStatus.pending: _adRemoval = const AdRemovalPurchase.pending(); notifyListeners(); case PurchaseStatus.purchased: case PurchaseStatus.restored: bool valid = await _verifyPurchase(purchaseDetails); if (valid) { _adRemoval = const AdRemovalPurchase.active(); if (purchaseDetails.status == PurchaseStatus.purchased) { showSnackBar('Thank you for your support!'); } notifyListeners(); } else { _log.severe('Purchase verification failed: $purchaseDetails'); _adRemoval = AdRemovalPurchase.error( StateError('Purchase could not be verified')); notifyListeners(); } case PurchaseStatus.error: _log.severe('Error with purchase: ${purchaseDetails.error}'); _adRemoval = AdRemovalPurchase.error(purchaseDetails.error!); notifyListeners(); case PurchaseStatus.canceled: _adRemoval = const AdRemovalPurchase.notStarted(); notifyListeners(); } if (purchaseDetails.pendingCompletePurchase) { // Confirm purchase back to the store. await inAppPurchaseInstance.completePurchase(purchaseDetails); } } } void _reportError(String message) { _log.severe(message); showSnackBar(message); _adRemoval = AdRemovalPurchase.error(message); notifyListeners(); } Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) async { _log.info('Verifying purchase: ${purchaseDetails.verificationData}'); // TODO: verify the purchase. // See the info in [purchaseDetails.verificationData] to learn more. // There's also a codelab that explains purchase verification // on the backend: // https://codelabs.developers.google.com/codelabs/flutter-in-app-purchases#9 return true; } }
samples/game_template/lib/src/in_app_purchase/in_app_purchase.dart/0
{'file_path': 'samples/game_template/lib/src/in_app_purchase/in_app_purchase.dart', 'repo_id': 'samples', 'token_count': 2418}
// 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 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:logging/logging.dart'; CustomTransitionPage<T> buildMyTransition<T>({ required Widget child, required Color color, String? name, Object? arguments, String? restorationId, LocalKey? key, }) { return CustomTransitionPage<T>( child: child, transitionsBuilder: (context, animation, secondaryAnimation, child) { return _MyReveal( animation: animation, color: color, child: child, ); }, key: key, name: name, arguments: arguments, restorationId: restorationId, transitionDuration: const Duration(milliseconds: 700), ); } class _MyReveal extends StatefulWidget { final Widget child; final Animation<double> animation; final Color color; const _MyReveal({ required this.child, required this.animation, required this.color, }); @override State<_MyReveal> createState() => _MyRevealState(); } class _MyRevealState extends State<_MyReveal> { static final _log = Logger('_InkRevealState'); bool _finished = false; final _tween = Tween(begin: const Offset(0, -1), end: Offset.zero); @override void initState() { super.initState(); widget.animation.addStatusListener(_statusListener); } @override void didUpdateWidget(covariant _MyReveal oldWidget) { if (oldWidget.animation != widget.animation) { oldWidget.animation.removeStatusListener(_statusListener); widget.animation.addStatusListener(_statusListener); } super.didUpdateWidget(oldWidget); } @override void dispose() { widget.animation.removeStatusListener(_statusListener); super.dispose(); } @override Widget build(BuildContext context) { return Stack( fit: StackFit.expand, children: [ SlideTransition( position: _tween.animate( CurvedAnimation( parent: widget.animation, curve: Curves.easeOutCubic, reverseCurve: Curves.easeOutCubic, ), ), child: Container( color: widget.color, ), ), AnimatedOpacity( opacity: _finished ? 1 : 0, duration: const Duration(milliseconds: 300), child: widget.child, ), ], ); } void _statusListener(AnimationStatus status) { _log.fine(() => 'status: $status'); switch (status) { case AnimationStatus.completed: setState(() { _finished = true; }); case AnimationStatus.forward: case AnimationStatus.dismissed: case AnimationStatus.reverse: setState(() { _finished = false; }); } } }
samples/game_template/lib/src/style/my_transition.dart/0
{'file_path': 'samples/game_template/lib/src/style/my_transition.dart', 'repo_id': 'samples', 'token_count': 1172}
// 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:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:material_3_demo/main.dart' as app; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('verify app can run', (tester) async { app.main(); }); }
samples/material_3_demo/integration_test/integration_test.dart/0
{'file_path': 'samples/material_3_demo/integration_test/integration_test.dart', 'repo_id': 'samples', 'token_count': 152}
// Copyright 2021, 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 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:url_launcher/link.dart'; import '../auth.dart'; class SettingsScreen extends StatefulWidget { const SettingsScreen({super.key}); @override State<SettingsScreen> createState() => _SettingsScreenState(); } class _SettingsScreenState extends State<SettingsScreen> { @override Widget build(BuildContext context) => Scaffold( body: SafeArea( child: SingleChildScrollView( child: Align( alignment: Alignment.topCenter, child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 400), child: const Card( child: Padding( padding: EdgeInsets.symmetric(vertical: 18, horizontal: 12), child: SettingsContent(), ), ), ), ), ), ), ); } class SettingsContent extends StatelessWidget { const SettingsContent({ super.key, }); @override Widget build(BuildContext context) => Column( children: [ ...[ Text( 'Settings', style: Theme.of(context).textTheme.headlineMedium, ), FilledButton( onPressed: () { BookstoreAuth.of(context).signOut(); }, child: const Text('Sign out'), ), const Text('Example using the Link widget:'), Link( uri: Uri.parse('/books/all/book/0'), builder: (context, followLink) => TextButton( onPressed: followLink, child: const Text('/books/all/book/0'), ), ), const Text('Example using GoRouter.of(context).go():'), TextButton( child: const Text('/books/all/book/0'), onPressed: () { GoRouter.of(context).go('/books/all/book/0'); }, ), ].map((w) => Padding(padding: const EdgeInsets.all(8), child: w)), const Text('Displays a dialog on the root Navigator:'), TextButton( onPressed: () => showDialog<String>( context: context, builder: (context) => AlertDialog( title: const Text('Alert!'), content: const Text('The alert description goes here.'), actions: [ TextButton( onPressed: () => Navigator.pop(context, 'Cancel'), child: const Text('Cancel'), ), TextButton( onPressed: () => Navigator.pop(context, 'OK'), child: const Text('OK'), ), ], ), ), child: const Text('Show Dialog'), ) ], ); }
samples/navigation_and_routing/lib/src/screens/settings.dart/0
{'file_path': 'samples/navigation_and_routing/lib/src/screens/settings.dart', 'repo_id': 'samples', 'token_count': 1596}
// 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:go_router/go_router.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:provider/provider.dart'; import 'place.dart'; import 'place_details.dart'; import 'place_list.dart'; import 'place_map.dart'; import 'stub_data.dart'; enum PlaceTrackerViewType { map, list, } class PlaceTrackerApp extends StatelessWidget { const PlaceTrackerApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp.router( theme: ThemeData( useMaterial3: true, colorSchemeSeed: Colors.green, appBarTheme: AppBarTheme( backgroundColor: Colors.green[700], foregroundColor: Colors.white, ), floatingActionButtonTheme: FloatingActionButtonThemeData( backgroundColor: Colors.green[700], foregroundColor: Colors.white, ), ), routerConfig: GoRouter(routes: [ GoRoute( path: '/', builder: (context, state) => const _PlaceTrackerHomePage(), routes: [ GoRoute( path: 'place/:id', builder: (context, state) { final id = state.pathParameters['id']!; final place = context .read<AppState>() .places .singleWhere((place) => place.id == id); return PlaceDetails(place: place); }, ), ], ), ]), ); } } class _PlaceTrackerHomePage extends StatelessWidget { const _PlaceTrackerHomePage(); @override Widget build(BuildContext context) { var state = Provider.of<AppState>(context); return Scaffold( appBar: AppBar( title: const Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ Padding( padding: EdgeInsets.fromLTRB(0.0, 0.0, 8.0, 0.0), child: Icon(Icons.pin_drop, size: 24.0), ), Text('Place Tracker'), ], ), actions: [ Padding( padding: const EdgeInsets.fromLTRB(0.0, 0.0, 16.0, 0.0), child: IconButton( icon: Icon( state.viewType == PlaceTrackerViewType.map ? Icons.list : Icons.map, size: 32.0, ), onPressed: () { state.setViewType( state.viewType == PlaceTrackerViewType.map ? PlaceTrackerViewType.list : PlaceTrackerViewType.map, ); }, ), ), ], ), body: IndexedStack( index: state.viewType == PlaceTrackerViewType.map ? 0 : 1, children: const [ PlaceMap(center: LatLng(45.521563, -122.677433)), PlaceList() ], ), ); } } class AppState extends ChangeNotifier { AppState({ this.places = StubData.places, this.selectedCategory = PlaceCategory.favorite, this.viewType = PlaceTrackerViewType.map, }); List<Place> places; PlaceCategory selectedCategory; PlaceTrackerViewType viewType; void setViewType(PlaceTrackerViewType viewType) { this.viewType = viewType; notifyListeners(); } void setSelectedCategory(PlaceCategory newCategory) { selectedCategory = newCategory; notifyListeners(); } void setPlaces(List<Place> newPlaces) { places = newPlaces; notifyListeners(); } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is AppState && other.places == places && other.selectedCategory == selectedCategory && other.viewType == viewType; } @override int get hashCode => Object.hash(places, selectedCategory, viewType); }
samples/place_tracker/lib/place_tracker_app.dart/0
{'file_path': 'samples/place_tracker/lib/place_tracker_app.dart', 'repo_id': 'samples', 'token_count': 1871}
// 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 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:platform_channels/src/pet_list_message_channel.dart'; import 'package:platform_channels/src/pet_list_screen.dart'; void main() { group('PetListScreen tests', () { const basicMessageChannel = BasicMessageChannel<String?>('stringCodecDemo', StringCodec()); var petList = [ { 'petType': 'Dog', 'breed': 'Pug', } ]; PetListModel? petListModel; setUpAll(() { // Mock for the pet list received from the platform. TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockDecodedMessageHandler(basicMessageChannel, (message) async { petListModel = PetListModel.fromJson(message!); return null; }); // Mock for the index received from the Dart to delete the pet details, // and send the updated pet list back to Dart. TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockDecodedMessageHandler( const BasicMessageChannel<ByteData?>( 'binaryCodecDemo', BinaryCodec()), (message) async { // Convert the ByteData to String. final index = utf8.decoder.convert(message!.buffer .asUint8List(message.offsetInBytes, message.lengthInBytes)); // Remove the pet details at the given index. petList.removeAt(int.parse(index)); // Send the updated petList back. final map = {'petList': petList}; await basicMessageChannel.send(json.encode(map)); return null; }); }); test('convert json message to PetListModel', () { TestWidgetsFlutterBinding.ensureInitialized(); // Initially petListModel will be null. expect(petListModel, isNull); // Send the pet list using BasicMessageChannel. final map = {'petList': petList}; basicMessageChannel.send(json.encode(map)); // Get the details of first pet. final petDetails = petListModel!.petList.first; expect(petDetails.petType, 'Dog'); expect(petDetails.breed, 'Pug'); }); testWidgets('BuildPetList test', (tester) async { await tester.pumpWidget(MaterialApp( home: Scaffold( body: BuildPetList(petListModel!.petList), ), )); expect(find.text('Pet type: Dog'), findsOneWidget); expect(find.text('Pet breed: Pug'), findsOneWidget); // Delete the pet details. await tester.tap(find.byIcon(Icons.delete).first); expect(petListModel!.petList, isEmpty); }); }); }
samples/platform_channels/test/src/pet_list_screen_test.dart/0
{'file_path': 'samples/platform_channels/test/src/pet_list_screen_test.dart', 'repo_id': 'samples', 'token_count': 1094}
// 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_test/flutter_test.dart'; import 'package:provider/provider.dart'; import 'package:provider_shopper/models/cart.dart'; import 'package:provider_shopper/models/catalog.dart'; import 'package:provider_shopper/screens/cart.dart'; CartModel? cartModel; CatalogModel? catalogModel; Widget createCartScreen() => MultiProvider( providers: [ Provider(create: (context) => CatalogModel()), ChangeNotifierProxyProvider<CatalogModel, CartModel>( create: (context) => CartModel(), update: (context, catalog, cart) { catalogModel = catalog; cartModel = cart; cart!.catalog = catalogModel!; return cart; }, ), ], child: const MaterialApp( home: MyCart(), ), ); void main() { group('CartScreen widget tests', () { testWidgets('Tapping BUY button displays snackbar.', (tester) async { await tester.pumpWidget(createCartScreen()); // Verify no snackbar initially exists. expect(find.byType(SnackBar), findsNothing); await tester.tap(find.text('BUY')); // Schedule animation. await tester.pump(); // Verifying the snackbar upon clicking the button. expect(find.byType(SnackBar), findsOneWidget); }); testWidgets('Testing when the cart contains items', (tester) async { await tester.pumpWidget(createCartScreen()); // Adding five items in the cart and testing. for (var i = 0; i < 5; i++) { var item = catalogModel!.getByPosition(i); cartModel!.add(item); await tester.pumpAndSettle(); expect(find.text(item.name), findsOneWidget); } // Testing total price of the five items. expect(find.text('\$${42 * 5}'), findsOneWidget); expect(find.byIcon(Icons.done), findsNWidgets(5)); }); }); }
samples/provider_shopper/test/cart_widget_test.dart/0
{'file_path': 'samples/provider_shopper/test/cart_widget_test.dart', 'repo_id': 'samples', 'token_count': 805}
include: package:analysis_defaults/flutter.yaml
samples/simple_shader/analysis_options.yaml/0
{'file_path': 'samples/simple_shader/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_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:provider/provider.dart'; import 'package:testing_app/models/favorites.dart'; import 'package:testing_app/screens/favorites.dart'; late Favorites favoritesList; Widget createFavoritesScreen() => ChangeNotifierProvider<Favorites>( create: (context) { favoritesList = Favorites(); return favoritesList; }, child: const MaterialApp( home: FavoritesPage(), ), ); void main() { group('Testing App State Management Tests', () { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('Verifying add method', (tester) async { await tester.pumpWidget(createFavoritesScreen()); // Add an item to the list. favoritesList.add(30); await tester.pumpAndSettle(); // Check if the new item appears in the list. expect(find.text('Item 30'), findsOneWidget); }); testWidgets('Verifying remove method', (tester) async { await tester.pumpWidget(createFavoritesScreen()); // Remove an item from the list. favoritesList.remove(30); await tester.pumpAndSettle(); // Verify if it disappears. expect(find.text('Item 30'), findsNothing); }); }); }
samples/testing_app/integration_test/state_mgmt_test.dart/0
{'file_path': 'samples/testing_app/integration_test/state_mgmt_test.dart', 'repo_id': 'samples', 'token_count': 536}
// 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:veggieseasons/styles.dart'; import 'settings_item.dart'; // The widgets in this file present a group of Cupertino-style settings items to // the user. In the future, the Cupertino package in the Flutter SDK will // include dedicated widgets for this purpose, but for now they're done here. // // See https://github.com/flutter/flutter/projects/29 for more info. class SettingsGroupHeader extends StatelessWidget { const SettingsGroupHeader(this.title, {super.key}); final String title; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only( left: 15, right: 15, bottom: 6, ), child: Text( title.toUpperCase(), style: Styles.settingsGroupHeaderText(CupertinoTheme.of(context)), ), ); } } class SettingsGroupFooter extends StatelessWidget { const SettingsGroupFooter(this.title, {super.key}); final String title; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only( left: 15, right: 15, top: 7.5, ), child: Text(title, style: Styles.settingsGroupFooterText(CupertinoTheme.of(context))), ); } } class SettingsGroup extends StatelessWidget { SettingsGroup({ required this.items, this.header, this.footer, super.key, }) : assert(items.isNotEmpty); final List<SettingsItem> items; final Widget? header; final Widget? footer; @override Widget build(BuildContext context) { var brightness = CupertinoTheme.brightnessOf(context); final dividedItems = <Widget>[items[0]]; for (var i = 1; i < items.length; i++) { dividedItems.add(Container( color: Styles.settingsLineation(brightness), height: 0.3, )); dividedItems.add(items[i]); } return Padding( padding: EdgeInsets.only( top: header == null ? 35 : 22, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ if (header != null) header!, Container( decoration: BoxDecoration( color: CupertinoColors.white, border: Border( top: BorderSide( color: Styles.settingsLineation(brightness), width: 0, ), bottom: BorderSide( color: Styles.settingsLineation(brightness), width: 0, ), ), ), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: dividedItems, ), ), if (footer != null) footer!, ], ), ); } }
samples/veggieseasons/lib/widgets/settings_group.dart/0
{'file_path': 'samples/veggieseasons/lib/widgets/settings_group.dart', 'repo_id': 'samples', 'token_count': 1269}
// 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 'dart:convert'; import 'package:flutter/material.dart'; import 'package:web_startup_analyzer/web_startup_analyzer.dart'; main() async { var analyzer = WebStartupAnalyzer(additionalFrameCount: 10); print(json.encode(analyzer.startupTiming)); analyzer.onFirstFrame.addListener(() { print(json.encode({'firstFrame': analyzer.onFirstFrame.value})); }); analyzer.onFirstPaint.addListener(() { print(json.encode({ 'firstPaint': analyzer.onFirstPaint.value?.$1, 'firstContentfulPaint': analyzer.onFirstPaint.value?.$2, })); }); analyzer.onAdditionalFrames.addListener(() { print(json.encode({ 'additionalFrames': analyzer.onAdditionalFrames.value, })); }); runApp( WebStartupAnalyzerSample( analyzer: analyzer, ), ); } class WebStartupAnalyzerSample extends StatelessWidget { final WebStartupAnalyzer analyzer; const WebStartupAnalyzerSample({super.key, required this.analyzer}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter web app timing', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.green.shade100), useMaterial3: true, ), home: WebStartupAnalyzerScreen(analyzer: analyzer), ); } } class WebStartupAnalyzerScreen extends StatefulWidget { final WebStartupAnalyzer analyzer; const WebStartupAnalyzerScreen({super.key, required this.analyzer}); @override State<WebStartupAnalyzerScreen> createState() => _WebStartupAnalyzerScreenState(); } class _WebStartupAnalyzerScreenState extends State<WebStartupAnalyzerScreen> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.amber.shade50, body: Align( alignment: Alignment.topCenter, child: Container( margin: const EdgeInsets.all(8.0), constraints: const BoxConstraints(maxWidth: 400), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(8.0), ), child: ListenableBuilder( listenable: widget.analyzer.onChange, builder: (BuildContext context, child) { return ListView( shrinkWrap: true, children: [ TimingWidget( name: 'DCL', timingMs: widget.analyzer.domContentLoaded, ), TimingWidget( name: 'Load entrypoint', timingMs: widget.analyzer.loadEntrypoint, ), TimingWidget( name: 'Initialize engine', timingMs: widget.analyzer.initializeEngine, ), TimingWidget( name: 'Run app', timingMs: widget.analyzer.appRunnerRunApp, ), if (widget.analyzer.firstFrame != null) TimingWidget( name: 'First frame', timingMs: widget.analyzer.firstFrame!, ), if (widget.analyzer.firstPaint != null) TimingWidget( name: 'First paint', timingMs: widget.analyzer.firstPaint!), if (widget.analyzer.firstContentfulPaint != null) TimingWidget( name: 'First contentful paint', timingMs: widget.analyzer.firstContentfulPaint!), if (widget.analyzer.additionalFrames != null) ...[ for (var i in widget.analyzer.additionalFrames!) TimingWidget(name: 'Frame', timingMs: i.toDouble()), ] else TextButton( child: const Text('Trigger frames'), onPressed: () {}, ), ], ); }, ), ), ), ); } } class TimingWidget extends StatelessWidget { final String name; final double timingMs; const TimingWidget({ super.key, required this.name, required this.timingMs, }); @override Widget build(BuildContext context) { return ListTile( title: Text( name, style: const TextStyle(fontSize: 18), overflow: TextOverflow.ellipsis, ), trailing: Text( '${timingMs.truncate()}ms', style: const TextStyle(fontSize: 18), ), ); } }
samples/web/_packages/web_startup_analyzer/example/lib/main.dart/0
{'file_path': 'samples/web/_packages/web_startup_analyzer/example/lib/main.dart', 'repo_id': 'samples', 'token_count': 2264}