code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
# No integration tests to run:
- espresso
| plugins/script/configs/exclude_integration_android.yaml/0 | {'file_path': 'plugins/script/configs/exclude_integration_android.yaml', 'repo_id': 'plugins', 'token_count': 11} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/file.dart';
import 'package:platform/platform.dart';
import 'process_runner.dart';
const String _gradleWrapperWindows = 'gradlew.bat';
const String _gradleWrapperNonWindows = 'gradlew';
/// A utility class for interacting with Gradle projects.
class GradleProject {
/// Creates an instance that runs commands for [project] with the given
/// [processRunner].
GradleProject(
this.flutterProject, {
this.processRunner = const ProcessRunner(),
this.platform = const LocalPlatform(),
});
/// The directory of a Flutter project to run Gradle commands in.
final Directory flutterProject;
/// The [ProcessRunner] used to run commands. Overridable for testing.
final ProcessRunner processRunner;
/// The platform that commands are being run on.
final Platform platform;
/// The project's 'android' directory.
Directory get androidDirectory => flutterProject.childDirectory('android');
/// The path to the Gradle wrapper file for the project.
File get gradleWrapper => androidDirectory.childFile(
platform.isWindows ? _gradleWrapperWindows : _gradleWrapperNonWindows);
/// Whether or not the project is ready to have Gradle commands run on it
/// (i.e., whether the `flutter` tool has generated the necessary files).
bool isConfigured() => gradleWrapper.existsSync();
/// Runs a `gradlew` command with the given parameters.
Future<int> runCommand(
String target, {
List<String> arguments = const <String>[],
}) {
return processRunner.runAndStream(
gradleWrapper.path,
<String>[target, ...arguments],
workingDir: androidDirectory,
);
}
}
| plugins/script/tool/lib/src/common/gradle.dart/0 | {'file_path': 'plugins/script/tool/lib/src/common/gradle.dart', 'repo_id': 'plugins', 'token_count': 522} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io;
import 'package:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_plugin_tools/src/common/repository_package.dart';
import 'package:flutter_plugin_tools/src/make_deps_path_based_command.dart';
import 'package:mockito/mockito.dart';
import 'package:test/test.dart';
import 'common/plugin_command_test.mocks.dart';
import 'mocks.dart';
import 'util.dart';
void main() {
FileSystem fileSystem;
late Directory packagesDir;
late CommandRunner<void> runner;
late RecordingProcessRunner processRunner;
setUp(() {
fileSystem = MemoryFileSystem();
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
final MockGitDir gitDir = MockGitDir();
when(gitDir.path).thenReturn(packagesDir.parent.path);
when(gitDir.runCommand(any, throwOnError: anyNamed('throwOnError')))
.thenAnswer((Invocation invocation) {
final List<String> arguments =
invocation.positionalArguments[0]! as List<String>;
// Route git calls through the process runner, to make mock output
// consistent with other processes. Attach the first argument to the
// command to make targeting the mock results easier.
final String gitCommand = arguments.removeAt(0);
return processRunner.run('git-$gitCommand', arguments);
});
processRunner = RecordingProcessRunner();
final MakeDepsPathBasedCommand command =
MakeDepsPathBasedCommand(packagesDir, gitDir: gitDir);
runner = CommandRunner<void>(
'make-deps-path-based_command', 'Test for $MakeDepsPathBasedCommand');
runner.addCommand(command);
});
/// Adds dummy 'dependencies:' entries for each package in [dependencies]
/// to [package].
void _addDependencies(
RepositoryPackage package, Iterable<String> dependencies) {
final List<String> lines = package.pubspecFile.readAsLinesSync();
final int dependenciesStartIndex = lines.indexOf('dependencies:');
assert(dependenciesStartIndex != -1);
lines.insertAll(dependenciesStartIndex + 1, <String>[
for (final String dependency in dependencies) ' $dependency: ^1.0.0',
]);
package.pubspecFile.writeAsStringSync(lines.join('\n'));
}
test('no-ops for no plugins', () async {
RepositoryPackage(createFakePackage('foo', packagesDir, isFlutter: true));
final RepositoryPackage packageBar = RepositoryPackage(
createFakePackage('bar', packagesDir, isFlutter: true));
_addDependencies(packageBar, <String>['foo']);
final String originalPubspecContents =
packageBar.pubspecFile.readAsStringSync();
final List<String> output =
await runCapturingPrint(runner, <String>['make-deps-path-based']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('No target dependencies'),
]),
);
// The 'foo' reference should not have been modified.
expect(packageBar.pubspecFile.readAsStringSync(), originalPubspecContents);
});
test('rewrites references', () async {
final RepositoryPackage simplePackage = RepositoryPackage(
createFakePackage('foo', packagesDir, isFlutter: true));
final Directory pluginGroup = packagesDir.childDirectory('bar');
RepositoryPackage(createFakePackage('bar_platform_interface', pluginGroup,
isFlutter: true));
final RepositoryPackage pluginImplementation =
RepositoryPackage(createFakePlugin('bar_android', pluginGroup));
final RepositoryPackage pluginAppFacing =
RepositoryPackage(createFakePlugin('bar', pluginGroup));
_addDependencies(simplePackage, <String>[
'bar',
'bar_android',
'bar_platform_interface',
]);
_addDependencies(pluginAppFacing, <String>[
'bar_platform_interface',
'bar_android',
]);
_addDependencies(pluginImplementation, <String>[
'bar_platform_interface',
]);
final List<String> output = await runCapturingPrint(runner, <String>[
'make-deps-path-based',
'--target-dependencies=bar,bar_platform_interface'
]);
expect(
output,
containsAll(<String>[
'Rewriting references to: bar, bar_platform_interface...',
' Modified packages/bar/bar/pubspec.yaml',
' Modified packages/bar/bar_android/pubspec.yaml',
' Modified packages/foo/pubspec.yaml',
]));
expect(
output,
isNot(contains(
' Modified packages/bar/bar_platform_interface/pubspec.yaml')));
expect(
simplePackage.pubspecFile.readAsLinesSync(),
containsAllInOrder(<String>[
'# FOR TESTING ONLY. DO NOT MERGE.',
'dependency_overrides:',
' bar:',
' path: ../bar/bar',
' bar_platform_interface:',
' path: ../bar/bar_platform_interface',
]));
expect(
pluginAppFacing.pubspecFile.readAsLinesSync(),
containsAllInOrder(<String>[
'dependency_overrides:',
' bar_platform_interface:',
' path: ../../bar/bar_platform_interface',
]));
});
group('target-dependencies-with-non-breaking-updates', () {
test('no-ops for no published changes', () async {
final Directory package = createFakePackage('foo', packagesDir);
final String changedFileOutput = <File>[
package.childFile('pubspec.yaml'),
].map((File file) => file.path).join('\n');
processRunner.mockProcessesForExecutable['git-diff'] = <io.Process>[
MockProcess(stdout: changedFileOutput),
];
// Simulate no change to the version in the interface's pubspec.yaml.
processRunner.mockProcessesForExecutable['git-show'] = <io.Process>[
MockProcess(
stdout: RepositoryPackage(package).pubspecFile.readAsStringSync()),
];
final List<String> output = await runCapturingPrint(runner, <String>[
'make-deps-path-based',
'--target-dependencies-with-non-breaking-updates'
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('No target dependencies'),
]),
);
});
test('no-ops for no deleted packages', () async {
final String changedFileOutput = <File>[
// A change for a file that's not on disk simulates a deletion.
packagesDir.childDirectory('foo').childFile('pubspec.yaml'),
].map((File file) => file.path).join('\n');
processRunner.mockProcessesForExecutable['git-diff'] = <io.Process>[
MockProcess(stdout: changedFileOutput),
];
final List<String> output = await runCapturingPrint(runner, <String>[
'make-deps-path-based',
'--target-dependencies-with-non-breaking-updates'
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Skipping foo; deleted.'),
contains('No target dependencies'),
]),
);
});
test('includes bugfix version changes as targets', () async {
const String newVersion = '1.0.1';
final Directory package =
createFakePackage('foo', packagesDir, version: newVersion);
final File pubspecFile = RepositoryPackage(package).pubspecFile;
final String changedFileOutput = <File>[
pubspecFile,
].map((File file) => file.path).join('\n');
processRunner.mockProcessesForExecutable['git-diff'] = <io.Process>[
MockProcess(stdout: changedFileOutput),
];
final String gitPubspecContents =
pubspecFile.readAsStringSync().replaceAll(newVersion, '1.0.0');
// Simulate no change to the version in the interface's pubspec.yaml.
processRunner.mockProcessesForExecutable['git-show'] = <io.Process>[
MockProcess(stdout: gitPubspecContents),
];
final List<String> output = await runCapturingPrint(runner, <String>[
'make-deps-path-based',
'--target-dependencies-with-non-breaking-updates'
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Rewriting references to: foo...'),
]),
);
});
test('includes minor version changes to 1.0+ as targets', () async {
const String newVersion = '1.1.0';
final Directory package =
createFakePackage('foo', packagesDir, version: newVersion);
final File pubspecFile = RepositoryPackage(package).pubspecFile;
final String changedFileOutput = <File>[
pubspecFile,
].map((File file) => file.path).join('\n');
processRunner.mockProcessesForExecutable['git-diff'] = <io.Process>[
MockProcess(stdout: changedFileOutput),
];
final String gitPubspecContents =
pubspecFile.readAsStringSync().replaceAll(newVersion, '1.0.0');
// Simulate no change to the version in the interface's pubspec.yaml.
processRunner.mockProcessesForExecutable['git-show'] = <io.Process>[
MockProcess(stdout: gitPubspecContents),
];
final List<String> output = await runCapturingPrint(runner, <String>[
'make-deps-path-based',
'--target-dependencies-with-non-breaking-updates'
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Rewriting references to: foo...'),
]),
);
});
test('does not include major version changes as targets', () async {
const String newVersion = '2.0.0';
final Directory package =
createFakePackage('foo', packagesDir, version: newVersion);
final File pubspecFile = RepositoryPackage(package).pubspecFile;
final String changedFileOutput = <File>[
pubspecFile,
].map((File file) => file.path).join('\n');
processRunner.mockProcessesForExecutable['git-diff'] = <io.Process>[
MockProcess(stdout: changedFileOutput),
];
final String gitPubspecContents =
pubspecFile.readAsStringSync().replaceAll(newVersion, '1.0.0');
// Simulate no change to the version in the interface's pubspec.yaml.
processRunner.mockProcessesForExecutable['git-show'] = <io.Process>[
MockProcess(stdout: gitPubspecContents),
];
final List<String> output = await runCapturingPrint(runner, <String>[
'make-deps-path-based',
'--target-dependencies-with-non-breaking-updates'
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('No target dependencies'),
]),
);
});
test('does not include minor version changes to 0.x as targets', () async {
const String newVersion = '0.8.0';
final Directory package =
createFakePackage('foo', packagesDir, version: newVersion);
final File pubspecFile = RepositoryPackage(package).pubspecFile;
final String changedFileOutput = <File>[
pubspecFile,
].map((File file) => file.path).join('\n');
processRunner.mockProcessesForExecutable['git-diff'] = <io.Process>[
MockProcess(stdout: changedFileOutput),
];
final String gitPubspecContents =
pubspecFile.readAsStringSync().replaceAll(newVersion, '0.7.0');
// Simulate no change to the version in the interface's pubspec.yaml.
processRunner.mockProcessesForExecutable['git-show'] = <io.Process>[
MockProcess(stdout: gitPubspecContents),
];
final List<String> output = await runCapturingPrint(runner, <String>[
'make-deps-path-based',
'--target-dependencies-with-non-breaking-updates'
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('No target dependencies'),
]),
);
});
});
}
| plugins/script/tool/test/make_deps_path_based_command_test.dart/0 | {'file_path': 'plugins/script/tool/test/make_deps_path_based_command_test.dart', 'repo_id': 'plugins', 'token_count': 4536} |
name: Format, Analyze and Test
on: [push]
jobs:
default_run:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/setup-java@v1
with:
java-version: "12.x"
- uses: subosito/flutter-action@v1
with:
channel: "stable"
- run: flutter pub get
- run: flutter format --set-exit-if-changed -l 120 lib
- run: flutter analyze lib
- run: flutter test --no-pub
| pnyws/.github/workflows/main.yml/0 | {'file_path': 'pnyws/.github/workflows/main.yml', 'repo_id': 'pnyws', 'token_count': 217} |
import 'package:flutter/material.dart' show MaterialColor;
import 'package:flutter/widgets.dart';
class MkColors {
static const _basePrimary = 0xFF121212;
static const _baseSecondary = 0xFF03dac4;
static const MaterialColor white = MaterialColor(
0xFFFFFFFF,
<int, Color>{
50: Color(0xFFFFFFFF),
100: Color(0xFFfafafa),
200: Color(0xFFf5f5f5),
300: Color(0xFFf0f0f0),
400: Color(0xFFdedede),
500: Color(0xFFc2c2c2),
600: Color(0xFF979797),
700: Color(0xFF818181),
800: Color(0xFF606060),
900: Color(0xFF3c3c3c),
},
);
static const MaterialColor primaryAccent = MaterialColor(
_basePrimary,
<int, Color>{
50: Color(0xFFf7f7f7),
100: Color(0xFFeeeeee),
200: Color(0xFFe2e2e2),
300: Color(0xFFd0d0d0),
400: Color(0xFFababab),
500: Color(0xFF8a8a8a),
600: Color(0xFF636363),
700: Color(0xFF505050),
800: Color(0xFF323232),
900: Color(_basePrimary),
},
);
static const MaterialColor secondaryAccent = MaterialColor(
_baseSecondary,
<int, Color>{
50: Color(0xFFd4f6f2),
100: Color(0xFF92e9dc),
200: Color(_baseSecondary),
300: Color(0xFF00c7ab),
400: Color(0xFF00b798),
500: Color(0xFF00a885),
600: Color(0xFF009a77),
700: Color(0xFF008966),
800: Color(0xFF007957),
900: Color(0xFF005b39),
},
);
static const Color primary = Color(_basePrimary);
static const Color secondary = Color(_baseSecondary);
static const Color light_grey = Color(0xFF9B9B9B);
static const Color success = Color(0xFF7ED321);
static const Color danger = Color(0xFFEB5757);
static const Color info = Color(0xFF2D9CDB);
static const Color warning = Color(0xFFF1B61E);
}
| pnyws/lib/constants/mk_colors.dart/0 | {'file_path': 'pnyws/lib/constants/mk_colors.dart', 'repo_id': 'pnyws', 'token_count': 830} |
import 'package:cloud_firestore/cloud_firestore.dart';
class CloudDb {
CloudDb(this._instance)
: expenses = _ExpensesStore(_instance),
trips = _Store(_instance, "trips"),
accounts = _Store(_instance, "accounts");
final FirebaseFirestore _instance;
final _ExpensesStore expenses;
final _Store trips;
final _Store accounts;
DocumentReference get settings => _instance.doc('settings/common');
Future<void> batchAction(void Function(WriteBatch batch) action) {
final WriteBatch batch = _instance.batch();
action(batch);
return batch.commit();
}
}
class _Store {
_Store(this.store, this.path);
final FirebaseFirestore store;
final String path;
Query fetchAll(String userId) => store.collection(path).where('accountID', isEqualTo: userId);
DocumentReference fetchOne(String uuid) => store.doc('$path/$uuid');
}
class _ExpensesStore extends _Store {
_ExpensesStore(FirebaseFirestore store) : super(store, "expenses");
Query fetchByTrip(String tripId) => store.collection(path).where('tripID', isEqualTo: tripId);
}
| pnyws/lib/data/network/firebase/cloud_db.dart/0 | {'file_path': 'pnyws/lib/data/network/firebase/cloud_db.dart', 'repo_id': 'pnyws', 'token_count': 348} |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart' show DateFormat;
import 'package:pnyws/widgets/form/fake_text_form_field.dart';
class DateEditingController extends ValueNotifier<DateTime> {
DateEditingController([DateTime value]) : super(value);
}
class DateFormField extends StatefulWidget {
const DateFormField({
Key key,
this.controller,
this.initialValue,
this.onChanged,
this.onSaved,
this.autovalidate = false,
this.decoration = const InputDecoration(),
this.validator,
this.textAlign,
}) : super(key: key);
final DateEditingController controller;
final DateTime initialValue;
final ValueChanged<DateTime> onChanged;
final ValueChanged<DateTime> onSaved;
final FormFieldValidator<DateTime> validator;
final TextAlign textAlign;
final InputDecoration decoration;
final bool autovalidate;
@override
DateFormFieldState createState() => DateFormFieldState();
}
class DateFormFieldState extends State<DateFormField> {
DateTime _value;
@override
void initState() {
super.initState();
_value = widget.initialValue;
}
@override
Widget build(BuildContext context) {
return FakeTextFormField<DateTime>(
initialValue: _value,
validator: widget.validator,
decoration: widget.decoration,
textAlign: widget.textAlign,
child: Builder(builder: (context) {
if (_value == null) {
return Text(widget.decoration.hintText ?? "Select a date");
}
return Text(DateFormat.yMMMd().format(_value));
}),
onTap: showPicker(),
onSaved: widget.onSaved,
);
}
ValueChanged<FormFieldState<DateTime>> showPicker() {
return (FormFieldState<DateTime> field) async {
final value = await showDatePicker(
context: context,
initialDate: _value ?? DateTime.now(),
firstDate: DateTime(1900, 8),
lastDate: DateTime(2101),
);
if (value == null || value == _value) {
return;
}
setState(() {
_value = value;
field.didChange(value);
widget.controller?.value = value;
widget.onChanged?.call(value);
});
};
}
}
| pnyws/lib/widgets/form/date_form_field.dart/0 | {'file_path': 'pnyws/lib/widgets/form/date_form_field.dart', 'repo_id': 'pnyws', 'token_count': 850} |
import 'dart:math' show Random;
import '../components/player.dart';
import '../components/actor.dart';
import '../game.dart';
import 'action.dart';
import 'direction.dart';
class Engine {
Random random;
MyGame gameRef;
Engine(this.random, this.gameRef);
Iterable<Actor> get actors => gameRef.queryComponents.actors();
void queue(Action action) {
actors.forEach((a) {
a.queue(a is Player ? action : randomMove());
});
}
Action randomMove() {
return Action.move(randomDir());
}
Direction randomDir() {
return Direction.values[random.nextInt(Direction.values.length)];
}
} | pocket-dungeons/game/lib/engine/engine.dart/0 | {'file_path': 'pocket-dungeons/game/lib/engine/engine.dart', 'repo_id': 'pocket-dungeons', 'token_count': 215} |
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
final int id;
final String name;
final String username;
const User({this.id, this.name, this.username});
const User.initial()
: id = null,
name = '',
username = '';
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
| provider-example/lib/core/models/user.dart/0 | {'file_path': 'provider-example/lib/core/models/user.dart', 'repo_id': 'provider-example', 'token_count': 169} |
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:provider_example/core/enums/viewstate.dart';
import 'package:provider_example/core/viewmodels/login_model.dart';
import 'package:provider_example/ui/shared/app_colors.dart';
import 'package:provider_example/ui/widgets/login_header.dart';
class LoginView extends StatefulWidget {
const LoginView({Key key}) : super(key: key);
@override
_LoginViewState createState() => _LoginViewState();
}
class _LoginViewState extends State<LoginView> {
final TextEditingController _controller = TextEditingController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final model = Provider.of<LoginModel>(context);
return Scaffold(
backgroundColor: backgroundColor,
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
LoginHeader(
validationMessage: model.errorMessage,
controller: _controller,
),
model.state == ViewState.Busy
? const CircularProgressIndicator()
: FlatButton(
color: Colors.white,
child: const Text(
'Login',
style: TextStyle(color: Colors.black),
),
onPressed: () async {
var loginSuccess = await model.login(_controller.text);
if (loginSuccess) {
Navigator.pushNamed(context, '/');
}
},
)
],
),
);
}
}
| provider-example/lib/ui/views/login_view.dart/0 | {'file_path': 'provider-example/lib/ui/views/login_view.dart', 'repo_id': 'provider-example', 'token_count': 762} |
export 'package:nested/nested.dart' hide Nested;
| provider/lib/single_child_widget.dart/0 | {'file_path': 'provider/lib/single_child_widget.dart', 'repo_id': 'provider', 'token_count': 18} |
#!/usr/bin/env dart
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:io/ansi.dart';
import 'package:io/io.dart';
import 'package:path/path.dart' as p;
import 'package:pubviz/pubviz.dart';
import 'package:pubviz/src/options.dart';
import 'package:pubviz/viz/dot.dart' as dot;
import 'package:stack_trace/stack_trace.dart';
void main(List<String> args) async {
parser..addCommand('open')..addCommand('print');
Options options;
try {
options = parseOptions(args);
} on FormatException catch (e) {
print(red.wrap(e.message));
print('');
_printUsage();
exitCode = ExitCode.usage.code;
return;
}
if (options.help) {
_printUsage();
return;
}
final command = options.command;
if (command == null) {
print(red.wrap("Specify a command: ${parser.commands.keys.join(', ')}"));
print('');
_printUsage();
exitCode = ExitCode.usage.code;
return;
}
final path = _getPath(command.rest);
await Chain.capture(() async {
final vp = await VizRoot.forDirectory(path,
flagOutdated: options.flagOutdated,
ignorePackages: options.ignorePackages);
if (command.name == 'print') {
_printContent(vp, options.format, options.ignorePackages);
} else if (command.name == 'open') {
await _open(vp, options.format, options.ignorePackages);
} else {
throw StateError('Should never get here...');
}
}, onError: (error, Chain chain) {
stderr..writeln(error)..writeln(chain.terse);
exitCode = 1;
});
}
String _indent(String input) =>
LineSplitter.split(input).map((l) => ' $l'.trimRight()).join('\n');
void _printUsage() {
print('''Usage: pubviz [<args>] <command> [<package path>]
${styleBold.wrap('Commands:')}
open Populate a temporary file with the content and open it.
print Print the output to stdout.
${styleBold.wrap('Arguments:')}
${_indent(parser.usage)}
If <package path> is omitted, the current directory is used.''');
}
String _getContent(
VizRoot root, FormatOptions format, List<String> ignorePackages) {
switch (format) {
case FormatOptions.html:
return dot.toDotHtml(root, ignorePackages: ignorePackages);
case FormatOptions.dot:
return dot.toDot(root, ignorePackages: ignorePackages);
}
throw StateError('format "$format" is not supported');
}
String _getExtension(FormatOptions format) => format.toString().split('.')[1];
Future _open(
VizRoot root, FormatOptions format, List<String> ignorePackages) async {
final extension = _getExtension(format);
final name = root.root.name;
final dir = await Directory.systemTemp.createTemp('pubviz_${name}_');
final filePath = p.join(dir.path, '$name.$extension');
var file = File(filePath);
file = await file.create();
final content = _getContent(root, format, ignorePackages);
await file.writeAsString(content, mode: FileMode.write, flush: true);
print('File generated: $filePath');
String openCommand;
if (Platform.isMacOS) {
openCommand = 'open';
} else if (Platform.isLinux) {
openCommand = 'xdg-open';
} else if (Platform.isWindows) {
openCommand = 'start';
} else {
print("We don't know how to open a file in ${Platform.operatingSystem}");
exit(1);
}
return Process.run(openCommand, [filePath], runInShell: true);
}
void _printContent(
VizRoot root, FormatOptions format, List<String> ignorePackages) {
final content = _getContent(root, format, ignorePackages);
print(content);
}
String _getPath(List<String> args) {
if (args.length > 1) {
print('Only one argument is allowed. You provided ${args.length}.');
exit(1);
}
final path = args.isEmpty ? p.current : args.first;
if (!FileSystemEntity.isDirectorySync(path)) {
print('The provided path does not exist or is not a directory: $path');
exit(1);
}
final yamlPath = p.join(path, 'pubspec.yaml');
if (!FileSystemEntity.isFileSync(yamlPath)) {
print('Could not find a pubspec.yaml in the target path.: $path');
exit(1);
}
return path;
}
| pubviz/bin/pubviz.dart/0 | {'file_path': 'pubviz/bin/pubviz.dart', 'repo_id': 'pubviz', 'token_count': 1456} |
import 'dart:async';
import 'dart:io';
import 'package:collection/collection.dart';
import 'package:path/path.dart' as p;
import 'package:pub_semver/pub_semver.dart';
import 'package:pubspec_parse/pubspec_parse.dart' hide Dependency;
import 'dependency.dart';
import 'util.dart';
class VizPackage extends Comparable<VizPackage> {
final String name;
final Version version;
final Set<Dependency> dependencies;
final VersionConstraint sdkConstraint;
bool isPrimary = false;
bool _onlyDev = true;
bool get onlyDev => _onlyDev;
set onlyDev(bool value) {
assert(value == false);
assert(_onlyDev == true);
_onlyDev = value;
}
Version _latestVersion;
Version get latestVersion => _latestVersion;
VizPackage._(
this.name, this.version, Set<Dependency> deps, this.sdkConstraint)
: dependencies = UnmodifiableSetView(deps);
static Future<VizPackage> forDirectory(String path,
{bool flagOutdated = false}) async {
final dir = Directory(path);
assert(dir.existsSync());
final pubspecPath = p.join(path, 'pubspec.yaml');
final pubspec = Pubspec.parse(File(pubspecPath).readAsStringSync(),
sourceUrl: pubspecPath);
final deps = Dependency.getDependencies(pubspec);
final sdkConstraint = pubspec.environment['sdk'];
final package =
VizPackage._(pubspec.name, pubspec.version, deps, sdkConstraint);
if (flagOutdated) {
await package._updateLatestVersion();
}
return package;
}
@override
String toString() => '$name @ $version';
@override
int compareTo(VizPackage other) {
return name.compareTo(other.name);
}
@override
bool operator ==(Object other) {
if (other is VizPackage) {
final match = name == other.name;
if (match) {
assert(other.version == version);
return true;
}
}
return false;
}
@override
int get hashCode => name.hashCode;
Future<Version> _updateLatestVersion() async {
if (_latestVersion != null) return _latestVersion;
if (version == null) {
// Likely not published. Don't try.
return null;
}
_latestVersion = await getLatestVersion(name, version.isPreRelease);
if (_latestVersion != null) {
assert(_latestVersion.compareTo(version) >= 0);
}
return _latestVersion;
}
}
| pubviz/lib/src/viz_package.dart/0 | {'file_path': 'pubviz/lib/src/viz_package.dart', 'repo_id': 'pubviz', 'token_count': 843} |
export 'view/app.dart';
| put-flutter-to-work/flutter_nps/lib/app/app.dart/0 | {'file_path': 'put-flutter-to-work/flutter_nps/lib/app/app.dart', 'repo_id': 'put-flutter-to-work', 'token_count': 10} |
import 'package:app_ui/app_ui.dart';
import 'package:flutter/material.dart';
class SubmitButton extends StatelessWidget {
const SubmitButton({
Key? key,
required this.onPressed,
required this.buttonText,
}) : super(key: key);
final VoidCallback? onPressed;
final String buttonText;
@override
Widget build(BuildContext context) {
return ElevatedButton(
key: const Key('capturePage_submit_elevatedButton'),
onPressed: onPressed,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: Spacing.xxhuge,
vertical: Spacing.s,
),
child: Text(
buttonText,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
),
);
}
}
| put-flutter-to-work/flutter_nps/packages/app_ui/lib/src/widgets/submit_button.dart/0 | {'file_path': 'put-flutter-to-work/flutter_nps/packages/app_ui/lib/src/widgets/submit_button.dart', 'repo_id': 'put-flutter-to-work', 'token_count': 334} |
import 'package:nps_repository/src/score_submit_model.dart';
class NpsRepository {
const NpsRepository();
Future<void> sendCustomerSatisfaction({
required CustomerSatisfaction scoreSubmit,
}) {
// Add custom implementation here to report customer satisfaction.
return Future.value();
}
}
| put-flutter-to-work/flutter_nps/packages/nps_repository/lib/src/nps_repository.dart/0 | {'file_path': 'put-flutter-to-work/flutter_nps/packages/nps_repository/lib/src/nps_repository.dart', 'repo_id': 'put-flutter-to-work', 'token_count': 95} |
name: flutter_nps
description: A new Flutter module project.
version: 1.0.0+1
publish_to: none
environment:
sdk: '>=2.18.5 <3.0.0'
dependencies:
app_ui:
path: packages/app_ui
bloc: ^8.1.0
equatable: ^2.0.5
flutter:
sdk: flutter
flutter_bloc: ^8.1.1
flutter_localizations:
sdk: flutter
intl: any
nps_repository:
path: packages/nps_repository
platform_close:
path: packages/platform_close
dev_dependencies:
bloc_test: ^9.1.0
flutter_lints: ^2.0.1
flutter_test:
sdk: flutter
mocktail: ^1.0.0
flutter:
uses-material-design: true
generate: true
module:
androidX: true
androidPackage: com.example.flutter_nps
iosBundleIdentifier: com.example.flutterNps
| put-flutter-to-work/flutter_nps/pubspec.yaml/0 | {'file_path': 'put-flutter-to-work/flutter_nps/pubspec.yaml', 'repo_id': 'put-flutter-to-work', 'token_count': 320} |
class PaymentType {
PaymentType._();
static const ACCOUNT = 'account';
}
| quidpay.dart/lib/src/constants/payment.dart/0 | {'file_path': 'quidpay.dart/lib/src/constants/payment.dart', 'repo_id': 'quidpay.dart', 'token_count': 23} |
import 'package:quidpay/src/quidpay.dart';
import 'package:quidpay/src/utils/endpoints.dart';
import 'package:quidpay/src/utils/http_wrapper.dart';
import 'package:quidpay/src/utils/log.dart';
import 'package:quidpay/src/utils/response.dart';
class Tokenize {
Tokenize() : _http = HttpWrapper();
final HttpWrapper _http;
// TODO
Future<Response<dynamic>> _charge(
String url, {
required String amount,
required String email,
required String iP,
required String txRef,
String? token,
String? currency,
String? country,
String? firstname,
String? lastname,
String? narration,
String? meta,
String? deviceFingerprint,
}) async {
final payload = <String, dynamic>{
'SECKEY': Quidpay().secretKey,
'token': token,
'currency': currency,
'country': country,
'amount': amount,
'email': email,
'firstname': firstname,
'lastname': lastname,
'IP': iP,
'narration': narration,
'txRef': txRef,
'meta': meta,
'device_fingerprint': deviceFingerprint,
};
Log().debug('$runtimeType.charge()', payload);
final _response = Response<dynamic>(
await _http.post(url, payload),
onTransform: (dynamic data, _) => data,
);
Log().debug('$runtimeType._charge() -> Response', _response);
return _response;
}
Future<Response> card({
required String amount,
required String email,
required String iP,
required String txRef,
String? token,
String? currency,
String? country,
String? firstname,
String? lastname,
String? narration,
String? meta,
String? deviceFingerprint,
}) {
return _charge(
Endpoints.tokenizeCard,
amount: amount,
email: email,
iP: iP,
txRef: txRef,
token: token,
currency: currency,
country: country,
firstname: firstname,
lastname: lastname,
narration: narration,
meta: meta,
deviceFingerprint: deviceFingerprint,
);
}
Future<Response> account({
required String amount,
required String email,
required String iP,
required String txRef,
String? token,
String? currency,
String? country,
String? firstname,
String? lastname,
String? narration,
String? meta,
String? deviceFingerprint,
}) {
return _charge(
Endpoints.tokenizeAccount,
amount: amount,
email: email,
iP: iP,
txRef: txRef,
token: token,
currency: currency,
country: country,
firstname: firstname,
lastname: lastname,
narration: narration,
meta: meta,
deviceFingerprint: deviceFingerprint,
);
}
}
| quidpay.dart/lib/src/tokenize.dart/0 | {'file_path': 'quidpay.dart/lib/src/tokenize.dart', 'repo_id': 'quidpay.dart', 'token_count': 1088} |
import 'dart:convert';
import 'dart:io';
import 'package:quidpay/src/utils/log.dart';
import 'package:test/test.dart';
String? readInputSync({Encoding encoding = systemEncoding}) {
final input = <int>[];
while (true) {
var byte = stdin.readByteSync();
if (byte < 0) {
if (input.isEmpty) return null;
break;
}
input.add(byte);
}
return encoding.decode(input);
}
void main() {
group('Log', () {
setUp(() => Log.init(false));
test('-> Single Instance', () => expect(Log(), same(Log())));
test('-> generator dev', () {
final truthy = Log().generator('=', 'Tag').contains('= Tag');
expect(truthy, isTrue);
});
test('-> generator prod', () {
Log.init(true);
final truthy = Log().generator('=', 'Tag').isEmpty;
expect(truthy, isTrue);
});
test('-> generator w/ payload', () {
final truthy = Log().generator('=', 'Tag', 'Payload').contains('Payload');
expect(truthy, isTrue);
});
test('-> debug', () {
final truthy = Log().debug('Tag').contains('= Tag');
expect(truthy, isTrue);
});
test('-> error', () {
final truthy = Log().error('Tag').contains('* Tag');
expect(truthy, isTrue);
});
});
}
| quidpay.dart/test/log_test.dart/0 | {'file_path': 'quidpay.dart/test/log_test.dart', 'repo_id': 'quidpay.dart', 'token_count': 507} |
name: r13n_brick
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on: pull_request
jobs:
build:
uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/dart_package.yml@v1
with:
coverage_excludes: "*.g.dart"
dart_sdk: "stable"
working_directory: "bricks/r13n/hooks/"
analyze_directories: "post_gen.dart pre_gen.dart test"
report_on: "post_gen.dart pre_gen.dart"
| r13n/.github/workflows/r13n_brick.yaml/0 | {'file_path': 'r13n/.github/workflows/r13n_brick.yaml', 'repo_id': 'r13n', 'token_count': 197} |
name: arb_parser
description: A simple `arb` file parser.
publish_to: none
environment:
sdk: ">=2.18.0 <3.0.0"
dev_dependencies:
mocktail: ^0.3.0
test: ^1.19.2
very_good_analysis: ^3.1.0
| r13n/bricks/r13n/hooks/packages/arb_parser/pubspec.yaml/0 | {'file_path': 'r13n/bricks/r13n/hooks/packages/arb_parser/pubspec.yaml', 'repo_id': 'r13n', 'token_count': 91} |
export 'src/regionalizations.dart';
| r13n/lib/r13n.dart/0 | {'file_path': 'r13n/lib/r13n.dart', 'repo_id': 'r13n', 'token_count': 12} |
name: Radiance
repository: https://github.com/flame-engine/radiance
packages:
- "*"
- sandbox/*
command:
version:
linkToCommits: true
branch: main
workspaceChangelog: true
scripts:
lint:
run: melos run analyze && melos run format
description: Run all static analysis checks.
analyze:
run: melos exec flutter analyze
description: Run `flutter analyze` for all packages.
format:
run: melos exec flutter format .
description: Run `flutter format` for all packages.
coverage:
run: |
melos exec -- flutter test --coverage &&
melos exec -- genhtml coverage/lcov.info --output-directory=coverage/
select-package:
dir-exists: test
description: Generate coverage for the selected package.
| radiance/melos.yaml/0 | {'file_path': 'radiance/melos.yaml', 'repo_id': 'radiance', 'token_count': 261} |
import 'package:flutter/material.dart';
import '../main.dart';
class TopMenu extends StatelessWidget {
const TopMenu(this.app);
final SandboxState app;
@override
Widget build(BuildContext context) {
final canPause = app.engineState == EngineState.running;
final canStop = app.engineState != EngineState.stopped;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 10),
child: Row(
children: [
TextButton(
onPressed: canPause ? _handlePause : _handleStart,
child:
Icon(canPause ? Icons.pause_rounded : Icons.play_arrow_rounded),
),
TextButton(
onPressed: canStop ? _handleStop : null,
child: const Icon(Icons.stop_rounded),
),
TextButton(
onPressed: _handleVectors,
child: const Icon(Icons.transform),
),
],
),
);
}
void _handleStart() => app.startEngine();
void _handlePause() => app.pauseEngine();
void _handleStop() => app.stopEngine();
void _handleVectors() => app.toggleVectors();
}
| radiance/sandbox/lib/widgets/top_menu.dart/0 | {'file_path': 'radiance/sandbox/lib/widgets/top_menu.dart', 'repo_id': 'radiance', 'token_count': 483} |
name: rainbow_container
description: A magical container which changes colors whenever its build method is called.
version: 2.0.0
homepage: https://github.com/felangel/rainbow_container
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
random_color: ^1.0.6-nullsafety
dev_dependencies:
flutter_test:
sdk: flutter
| rainbow_container/pubspec.yaml/0 | {'file_path': 'rainbow_container/pubspec.yaml', 'repo_id': 'rainbow_container', 'token_count': 129} |
library rating_dialog;
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
class RatingDialog extends StatefulWidget {
/// The dialog's title
final String title;
/// The dialog's message/description text
final String message;
/// The top image used for the dialog to be displayed
final Widget image;
/// The rating bar (star icon & glow) color
final Color ratingColor;
/// Disables the cancel button and forces the user to leave a rating
final bool force;
/// The initial rating of the rating bar
final int initialRating;
/// The comment's TextField hint text
final String commentHint;
/// The submit button's label/text
final String submitButton;
/// Returns a RatingDialogResponse with user's rating and comment values
final Function(RatingDialogResponse) onSubmitted;
/// called when user cancels/closes the dialog
final Function? onCancelled;
const RatingDialog({
required this.title,
required this.message,
required this.image,
required this.submitButton,
required this.onSubmitted,
this.ratingColor = Colors.amber,
this.onCancelled,
this.force = false,
this.initialRating = 1,
this.commentHint = 'Tell us your comments',
});
@override
_RatingDialogState createState() => _RatingDialogState();
}
class _RatingDialogState extends State<RatingDialog> {
late final _commentController = TextEditingController();
late final _response = RatingDialogResponse(rating: widget.initialRating);
@override
Widget build(BuildContext context) {
final _content = Stack(
alignment: Alignment.topRight,
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: Padding(
padding: const EdgeInsets.fromLTRB(25, 30, 25, 5),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
child: widget.image,
padding: const EdgeInsets.only(top: 25, bottom: 25),
),
Text(
widget.title,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 15),
Text(
widget.message,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 15),
),
const SizedBox(height: 10),
Center(
child: RatingBar.builder(
initialRating: _response.rating.toDouble(),
glowColor: widget.ratingColor,
minRating: 1.0,
direction: Axis.horizontal,
allowHalfRating: false,
itemCount: 5,
itemPadding: EdgeInsets.symmetric(horizontal: 4.0),
onRatingUpdate: (rating) => _response.rating = rating.toInt(),
itemBuilder: (context, _) => Icon(
Icons.star,
color: widget.ratingColor,
),
),
),
TextButton(
child: Text(
widget.submitButton,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17,
),
),
onPressed: () {
if (!widget.force) Navigator.pop(context);
_response.comment = _commentController.text;
widget.onSubmitted.call(_response);
},
),
],
),
),
),
if (!widget.force && widget.onCancelled != null) ...[
IconButton(
icon: const Icon(Icons.close, size: 18),
onPressed: () {
Navigator.pop(context);
widget.onCancelled!.call();
},
)
]
],
);
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
titlePadding: EdgeInsets.zero,
scrollable: true,
title: _content,
);
}
}
class RatingDialogResponse {
RatingDialogResponse({this.comment = '', this.rating = 1});
/// The user's comment response
String comment;
/// The user's rating response
int rating;
}
| rating_dialog/lib/rating_dialog.dart/0 | {'file_path': 'rating_dialog/lib/rating_dialog.dart', 'repo_id': 'rating_dialog', 'token_count': 2239} |
import 'package:meta/meta.dart';
import 'package:ravepay/src/api/api.dart';
import 'package:ravepay/src/constants/endpoints.dart';
import 'package:ravepay/src/utils/log.dart';
import 'package:ravepay/src/utils/response.dart';
class Fees extends Api {
// TODO
Future<Response<dynamic>> card({
@required String amount,
@required String currency,
@required String card6,
}) async {
assert(amount != null);
assert(currency != null);
assert(card6 != null);
final payload = {
'PBFPubKey': keys.public,
'amount': amount,
'currency': currency,
'card6': card6,
};
Log().debug('$runtimeType.card()', payload);
final _response = Response<dynamic>(
await http.post(Endpoints.getFees, payload),
onTransform: (dynamic data, _) => data,
);
Log().debug('$runtimeType.card() -> Response', _response);
return _response;
}
// TODO
Future<Response<dynamic>> account({
@required String amount,
@required String currency,
int ptype,
}) async {
assert(amount != null);
assert(currency != null);
final payload = {
'PBFPubKey': keys.public,
'amount': amount,
'currency': currency,
'ptype': ptype ?? 2,
};
Log().debug('$runtimeType.account()', payload);
final _response = Response<dynamic>(
await http.post(Endpoints.getFees, payload),
onTransform: (dynamic data, _) => data,
);
Log().debug('$runtimeType.account() -> Response', _response);
return _response;
}
}
| ravepay.dart/lib/src/api/fees.dart/0 | {'file_path': 'ravepay.dart/lib/src/api/fees.dart', 'repo_id': 'ravepay.dart', 'token_count': 579} |
import 'package:flutter/material.dart';
import 'package:recipes_ui/core/widgets/animate_in_effect.dart';
import 'package:recipes_ui/features/ingredients/views/widgets/ingredient_item.dart';
import 'package:recipes_ui/features/recipes/models/recipe.dart';
class IngredientsSection extends StatelessWidget {
const IngredientsSection(
this.recipe, {
Key? key,
}) : super(key: key);
final Recipe recipe;
@override
Widget build(BuildContext context) {
return ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 20),
physics: const NeverScrollableScrollPhysics(),
itemCount: recipe.ingredients.length,
shrinkWrap: true,
itemBuilder: (context, i) {
return AnimateInEffect(
keepAlive: true,
intervalStart: i / recipe.ingredients.length,
child: IngredientItem(
recipe,
ingredient: recipe.ingredients[i],
),
);
},
);
}
}
| recipes_ui_app/lib/features/ingredients/views/widgets/ingredients_section.dart/0 | {'file_path': 'recipes_ui_app/lib/features/ingredients/views/widgets/ingredients_section.dart', 'repo_id': 'recipes_ui_app', 'token_count': 387} |
import 'package:flutter/material.dart';
import 'package:recipes_ui/core/enums/screen_size.dart';
import 'package:recipes_ui/core/styles/app_colors.dart';
import 'package:recipes_ui/features/recipes/models/recipe.dart';
import 'package:recipes_ui/features/recipes/views/widgets/recipe_list_item_text_wrapper.dart';
class RecipeListItemText extends StatelessWidget {
const RecipeListItemText(
this.menuItem, {
Key? key,
}) : super(key: key);
final Recipe menuItem;
@override
Widget build(BuildContext context) {
return RecipeListItemTextWrapper(
child: Padding(
padding: EdgeInsets.only(
left: 20,
right: 20,
top: ScreenSize.of(context).isLarge ? 40 : 20,
bottom: 20,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: ScreenSize.of(context).isLarge
? MainAxisAlignment.start
: MainAxisAlignment.end,
children: [
Hero(
tag: '__recipe_${menuItem.id}_title__',
child: Text(
menuItem.title,
style: Theme.of(context).textTheme.headline4!.copyWith(
color:
AppColors.textColorFromBackground(menuItem.bgColor),
),
),
),
const SizedBox(height: 10),
Flexible(
child: Hero(
tag: '__recipe_${menuItem.id}_description__',
child: Text(
menuItem.description,
style: Theme.of(context).textTheme.subtitle1!.copyWith(
color:
AppColors.textColorFromBackground(menuItem.bgColor),
),
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
),
),
],
),
),
);
}
}
| recipes_ui_app/lib/features/recipes/views/widgets/recipe_list_item_text.dart/0 | {'file_path': 'recipes_ui_app/lib/features/recipes/views/widgets/recipe_list_item_text.dart', 'repo_id': 'recipes_ui_app', 'token_count': 1044} |
import 'package:flutter/widgets.dart';
import 'package:rijksbook/app.dart';
import 'package:rijksbook/domain.dart';
import 'mocks.dart';
Widget makeApp({Widget? home, RijksRepository? repository}) =>
App(home: home, repository: repository ?? MockRijksRepository());
| rijksbook/test/utils.dart/0 | {'file_path': 'rijksbook/test/utils.dart', 'repo_id': 'rijksbook', 'token_count': 94} |
github: rrousselGit
| riverpod/.github/FUNDING.yml/0 | {'file_path': 'riverpod/.github/FUNDING.yml', 'repo_id': 'riverpod', 'token_count': 8} |
import 'package:dio/dio.dart';
// ignore: undefined_hidden_name
import 'package:flutter/material.dart' hide SearchBar;
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../marvel.dart';
import '../widgets/loading_image.dart';
import '../widgets/marvel_logo.dart';
import '../widgets/search_bar.dart';
part 'home.freezed.dart';
const kCharactersPageLimit = 50;
@freezed
class CharacterPagination with _$CharacterPagination {
factory CharacterPagination({
required int page,
String? name,
}) = _CharacterPagination;
}
class AbortedException implements Exception {}
final characterPages = FutureProvider.autoDispose
.family<MarvelListCharactersResponse, CharacterPagination>(
(ref, meta) async {
// Cancel the page request if the UI no longer needs it before the request
// is finished.
// This typically happen if the user scrolls very fast
final cancelToken = CancelToken();
ref.onDispose(cancelToken.cancel);
// Debouncing the request. By having this delay, it leaves the opportunity
// for consumers to subscribe to a different `meta` parameters. In which
// case, this request will be aborted.
await Future<void>.delayed(const Duration(milliseconds: 250));
if (cancelToken.isCancelled) throw AbortedException();
final repository = ref.watch(repositoryProvider);
final charactersResponse = await repository.fetchCharacters(
offset: meta.page * kCharactersPageLimit,
limit: kCharactersPageLimit,
nameStartsWith: meta.name,
cancelToken: cancelToken,
);
return charactersResponse;
},
);
final charactersCount =
Provider.autoDispose.family<AsyncValue<int>, String>((ref, name) {
final meta = CharacterPagination(page: 0, name: name);
return ref.watch(characterPages(meta)).whenData((value) => value.totalCount);
});
@freezed
class CharacterOffset with _$CharacterOffset {
factory CharacterOffset({
required int offset,
@Default('') String name,
}) = _CharacterOffset;
}
final characterAtIndex = Provider.autoDispose
.family<AsyncValue<Character>, CharacterOffset>((ref, query) {
final offsetInPage = query.offset % kCharactersPageLimit;
final meta = CharacterPagination(
page: query.offset ~/ kCharactersPageLimit,
name: query.name,
);
return ref.watch(characterPages(meta)).whenData(
(value) => value.characters[offsetInPage],
);
});
class Home extends HookConsumerWidget {
const Home({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
return ref.watch(charactersCount('')).when(
loading: () => Container(
color: Colors.white,
child: const Center(child: CircularProgressIndicator()),
),
error: (err, stack) {
return Scaffold(
appBar: AppBar(title: const Text('Error')),
body: Center(
child: Text(
switch (err) {
DioException() => err.message ?? '$err',
_ => '$err',
},
),
),
);
},
data: (charactersCount) {
return Scaffold(
body: CustomScrollView(
slivers: [
SliverAppBar(
expandedHeight: 200,
flexibleSpace: FlexibleSpaceBar(
title: SizedBox(
height: 40,
child: marvelLogo,
),
centerTitle: true,
background: Image.asset(
'assets/marvel_background.jpeg',
fit: BoxFit.cover,
colorBlendMode: BlendMode.multiply,
color: Colors.grey.shade500,
),
titlePadding: const EdgeInsetsDirectional.only(bottom: 8),
),
pinned: true,
actions: const [
SearchBar(),
],
),
SliverPadding(
padding: const EdgeInsets.only(top: 10, left: 3, right: 3),
sliver: SliverGrid(
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 0.8,
),
delegate: SliverChildBuilderDelegate(
childCount: charactersCount,
(c, index) {
return ProviderScope(
overrides: [
_characterIndex.overrideWithValue(index),
],
child: const CharacterItem(),
);
},
),
),
),
],
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () =>
Navigator.pushNamed(context, '/characters/1009368'),
label: const Text('Deep link to Iron-man'),
icon: const Icon(Icons.link),
),
);
},
);
}
}
final _characterIndex = Provider<int>((ref) => throw UnimplementedError());
class CharacterItem extends HookConsumerWidget {
const CharacterItem({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final index = ref.watch(_characterIndex);
final character = ref.watch(
characterAtIndex(CharacterOffset(offset: index)),
);
return character.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (err, stack) => Text('Error $err'),
data: (character) {
return GestureDetector(
onTap: () {
Navigator.pushNamed(context, '/characters/${character.id}');
},
child: Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
child: Hero(
tag: 'character-${character.id}',
child: LoadingImage(url: character.thumbnail.url),
),
),
Padding(
padding: const EdgeInsets.all(12),
child: Text(character.name),
),
],
),
),
);
},
);
}
}
| riverpod/examples/marvel/lib/src/screens/home.dart/0 | {'file_path': 'riverpod/examples/marvel/lib/src/screens/home.dart', 'repo_id': 'riverpod', 'token_count': 3290} |
name: marvel
description: A new Flutter project.
publish_to: "none"
environment:
sdk: ">=3.0.0 <4.0.0"
flutter: ">=1.17.0"
dependencies:
crypto: ^3.0.0
cupertino_icons: ^1.0.2
dio: ^5.1.1
flutter:
sdk: flutter
flutter_hooks: ^0.18.0
flutter_portal: ^0.4.0
flutter_svg: ^0.21.0+1
freezed_annotation: ^2.1.0
hooks_riverpod:
path: ../../packages/hooks_riverpod
json_annotation: ^4.6.0
dev_dependencies:
build_runner: ^2.0.0
flutter_test:
sdk: flutter
freezed: ^2.1.0
json_serializable: ^6.3.1
mockito: ^5.0.0
dependency_overrides:
flutter_riverpod:
path: ../../packages/flutter_riverpod
hooks_riverpod:
path: ../../packages/hooks_riverpod
riverpod:
path: ../../packages/riverpod
flutter:
uses-material-design: true
assets:
- assets/configurations.json
- assets/marvel.svg
- assets/marvel_background.jpeg | riverpod/examples/marvel/pubspec.yaml/0 | {'file_path': 'riverpod/examples/marvel/pubspec.yaml', 'repo_id': 'riverpod', 'token_count': 406} |
import 'package:flutter/material.dart';
class PackageDetailBodyScrollView extends StatelessWidget {
const PackageDetailBodyScrollView({
super.key,
this.packageDescription,
required this.packageName,
required this.packageVersion,
required this.likeCount,
required this.grantedPoints,
required this.maxPoints,
required this.popularityScore,
});
final String packageName;
final String packageVersion;
final String? packageDescription;
final int likeCount;
final int grantedPoints;
final int maxPoints;
final double popularityScore;
@override
Widget build(BuildContext context) {
return ListView(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
children: [
Text(
'$packageName $packageVersion',
style: const TextStyle(fontSize: 20),
),
const SizedBox(height: 10),
Text(packageDescription ?? ''),
const SizedBox(height: 40),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Column(
children: [
Text(
'$likeCount',
style: const TextStyle(
color: Color(0xff1967d2),
fontSize: 40,
),
),
const Text('LIKES', style: TextStyle(fontSize: 13)),
],
),
Column(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Text(
'$grantedPoints',
style: const TextStyle(
color: Color(0xff1967d2),
fontSize: 40,
),
),
Text(
'/$maxPoints',
style: const TextStyle(
color: Color(0xff1967d2),
fontSize: 20,
),
),
],
),
const Text(
'PUB POINTS',
style: TextStyle(fontSize: 13),
),
],
),
Column(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Text(
'${popularityScore.round()}',
style: const TextStyle(
color: Color(0xff1967d2),
fontSize: 40,
),
),
const Text(
'%',
style: TextStyle(
color: Color(0xff1967d2),
fontSize: 20,
),
),
],
),
const Text(
'POPULARITY',
style: TextStyle(fontSize: 13),
),
],
),
],
),
],
);
}
}
| riverpod/examples/pub/lib/pub_ui/package_detail_body.dart/0 | {'file_path': 'riverpod/examples/pub/lib/pub_ui/package_detail_body.dart', 'repo_id': 'riverpod', 'token_count': 1977} |
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
final client = Provider((ref) => Dio());
/// A Provider that exposes the current theme.
///
/// This is unimplemented by default, and will be overridden inside [MaterialApp]
/// with the current theme obtained using a [BuildContext].
final themeProvider = Provider<ThemeData>(
(ref) => throw UnimplementedError(),
// Specifying an empty "dependencies" signals riverpod_lint that this provider
// is scoped.
dependencies: const [],
);
class TimestampParser implements JsonConverter<DateTime, int> {
const TimestampParser();
@override
DateTime fromJson(int json) {
return DateTime.fromMillisecondsSinceEpoch(
json * 1000,
isUtc: true,
);
}
@override
int toJson(DateTime object) => object.millisecondsSinceEpoch;
}
| riverpod/examples/stackoverflow/lib/common.dart/0 | {'file_path': 'riverpod/examples/stackoverflow/lib/common.dart', 'repo_id': 'riverpod', 'token_count': 302} |
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'todo.dart';
/// Some keys used for testing
final addTodoKey = UniqueKey();
final activeFilterKey = UniqueKey();
final completedFilterKey = UniqueKey();
final allFilterKey = UniqueKey();
/// Creates a [TodoList] and initialise it with pre-defined values.
///
/// We are using [StateNotifierProvider] here as a `List<Todo>` is a complex
/// object, with advanced business logic like how to edit a todo.
final todoListProvider = NotifierProvider<TodoList, List<Todo>>(TodoList.new);
/// The different ways to filter the list of todos
enum TodoListFilter {
all,
active,
completed,
}
/// The currently active filter.
///
/// We use [StateProvider] here as there is no fancy logic behind manipulating
/// the value since it's just enum.
final todoListFilter = StateProvider((_) => TodoListFilter.all);
/// The number of uncompleted todos
///
/// By using [Provider], this value is cached, making it performant.\
/// Even multiple widgets try to read the number of uncompleted todos,
/// the value will be computed only once (until the todo-list changes).
///
/// This will also optimise unneeded rebuilds if the todo-list changes, but the
/// number of uncompleted todos doesn't (such as when editing a todo).
final uncompletedTodosCount = Provider<int>((ref) {
return ref.watch(todoListProvider).where((todo) => !todo.completed).length;
});
/// The list of todos after applying of [todoListFilter].
///
/// This too uses [Provider], to avoid recomputing the filtered list unless either
/// the filter of or the todo-list updates.
final filteredTodos = Provider<List<Todo>>((ref) {
final filter = ref.watch(todoListFilter);
final todos = ref.watch(todoListProvider);
switch (filter) {
case TodoListFilter.completed:
return todos.where((todo) => todo.completed).toList();
case TodoListFilter.active:
return todos.where((todo) => !todo.completed).toList();
case TodoListFilter.all:
return todos;
}
});
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Home(),
);
}
}
class Home extends HookConsumerWidget {
const Home({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(filteredTodos);
final newTodoController = useTextEditingController();
return GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: Scaffold(
body: ListView(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 40),
children: [
const Title(),
TextField(
key: addTodoKey,
controller: newTodoController,
decoration: const InputDecoration(
labelText: 'What needs to be done?',
),
onSubmitted: (value) {
ref.read(todoListProvider.notifier).add(value);
newTodoController.clear();
},
),
const SizedBox(height: 42),
const Toolbar(),
if (todos.isNotEmpty) const Divider(height: 0),
for (var i = 0; i < todos.length; i++) ...[
if (i > 0) const Divider(height: 0),
Dismissible(
key: ValueKey(todos[i].id),
onDismissed: (_) {
ref.read(todoListProvider.notifier).remove(todos[i]);
},
child: ProviderScope(
overrides: [
_currentTodo.overrideWithValue(todos[i]),
],
child: const TodoItem(),
),
),
],
],
),
),
);
}
}
class Toolbar extends HookConsumerWidget {
const Toolbar({
super.key,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final filter = ref.watch(todoListFilter);
Color? textColorFor(TodoListFilter value) {
return filter == value ? Colors.blue : Colors.black;
}
return Material(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
'${ref.watch(uncompletedTodosCount)} items left',
overflow: TextOverflow.ellipsis,
),
),
Tooltip(
key: allFilterKey,
message: 'All todos',
child: TextButton(
onPressed: () =>
ref.read(todoListFilter.notifier).state = TodoListFilter.all,
style: ButtonStyle(
visualDensity: VisualDensity.compact,
foregroundColor:
MaterialStateProperty.all(textColorFor(TodoListFilter.all)),
),
child: const Text('All'),
),
),
Tooltip(
key: activeFilterKey,
message: 'Only uncompleted todos',
child: TextButton(
onPressed: () => ref.read(todoListFilter.notifier).state =
TodoListFilter.active,
style: ButtonStyle(
visualDensity: VisualDensity.compact,
foregroundColor: MaterialStateProperty.all(
textColorFor(TodoListFilter.active),
),
),
child: const Text('Active'),
),
),
Tooltip(
key: completedFilterKey,
message: 'Only completed todos',
child: TextButton(
onPressed: () => ref.read(todoListFilter.notifier).state =
TodoListFilter.completed,
style: ButtonStyle(
visualDensity: VisualDensity.compact,
foregroundColor: MaterialStateProperty.all(
textColorFor(TodoListFilter.completed),
),
),
child: const Text('Completed'),
),
),
],
),
);
}
}
class Title extends StatelessWidget {
const Title({super.key});
@override
Widget build(BuildContext context) {
return const Text(
'todos',
textAlign: TextAlign.center,
style: TextStyle(
color: Color.fromARGB(38, 47, 47, 247),
fontSize: 100,
fontWeight: FontWeight.w100,
fontFamily: 'Helvetica Neue',
),
);
}
}
/// A provider which exposes the [Todo] displayed by a [TodoItem].
///
/// By retrieving the [Todo] through a provider instead of through its
/// constructor, this allows [TodoItem] to be instantiated using the `const` keyword.
///
/// This ensures that when we add/remove/edit todos, only what the
/// impacted widgets rebuilds, instead of the entire list of items.
final _currentTodo = Provider<Todo>((ref) => throw UnimplementedError());
/// The widget that that displays the components of an individual Todo Item
class TodoItem extends HookConsumerWidget {
const TodoItem({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todo = ref.watch(_currentTodo);
final itemFocusNode = useFocusNode();
final itemIsFocused = useIsFocused(itemFocusNode);
final textEditingController = useTextEditingController();
final textFieldFocusNode = useFocusNode();
return Material(
color: Colors.white,
elevation: 6,
child: Focus(
focusNode: itemFocusNode,
onFocusChange: (focused) {
if (focused) {
textEditingController.text = todo.description;
} else {
// Commit changes only when the textfield is unfocused, for performance
ref
.read(todoListProvider.notifier)
.edit(id: todo.id, description: textEditingController.text);
}
},
child: ListTile(
onTap: () {
itemFocusNode.requestFocus();
textFieldFocusNode.requestFocus();
},
leading: Checkbox(
value: todo.completed,
onChanged: (value) =>
ref.read(todoListProvider.notifier).toggle(todo.id),
),
title: itemIsFocused
? TextField(
autofocus: true,
focusNode: textFieldFocusNode,
controller: textEditingController,
)
: Text(todo.description),
),
),
);
}
}
bool useIsFocused(FocusNode node) {
final isFocused = useState(node.hasFocus);
useEffect(
() {
void listener() {
isFocused.value = node.hasFocus;
}
node.addListener(listener);
return () => node.removeListener(listener);
},
[node],
);
return isFocused.value;
}
| riverpod/examples/todos/lib/main.dart/0 | {'file_path': 'riverpod/examples/todos/lib/main.dart', 'repo_id': 'riverpod', 'token_count': 3943} |
name: flutter_riverpod_example
description: A new Flutter project.
publish_to: "none"
environment:
sdk: ">=2.17.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
flutter_riverpod:
path: ../../flutter_riverpod
hooks_riverpod:
path: ../../hooks_riverpod
riverpod:
path: ../../riverpod
dev_dependencies:
flutter_test:
sdk: flutter
dependency_overrides:
flutter_riverpod:
path: ../../flutter_riverpod
hooks_riverpod:
path: ../../hooks_riverpod
riverpod:
path: ../../riverpod
flutter:
uses-material-design: true
| riverpod/packages/flutter_riverpod/example/pubspec.yaml/0 | {'file_path': 'riverpod/packages/flutter_riverpod/example/pubspec.yaml', 'repo_id': 'riverpod', 'token_count': 236} |
// ignore_for_file: invalid_use_of_internal_member
import 'dart:async';
import 'package:flutter/material.dart' hide Listener;
import 'package:flutter_riverpod/src/internals.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'utils.dart';
void main() {
testWidgets('Supports recreating ProviderScope', (tester) async {
final provider = Provider<String>((ref) => 'foo');
await tester.pumpWidget(
ProviderScope(
child: Consumer(
builder: (context, ref, _) {
ref.watch(provider);
return Consumer(
builder: (context, ref, _) {
ref.watch(provider);
return Container();
},
);
},
),
),
);
await tester.pumpWidget(
ProviderScope(
key: UniqueKey(),
child: Consumer(
builder: (context, ref, _) {
ref.watch(provider);
return Consumer(
builder: (context, ref, _) {
ref.watch(provider);
return Container();
},
);
},
),
),
);
});
testWidgets('Supports multiple ProviderScope roots in the same tree',
(tester) async {
final a = StateProvider((_) => 0);
final b = Provider((ref) => ref.watch(a));
await tester.pumpWidget(
// No root scope. We want to test cases where there are multiple roots
Column(
mainAxisSize: MainAxisSize.min,
children: [
for (var i = 0; i < 2; i++)
SizedBox(
width: 100,
height: 100,
child: ProviderScope(
child: Consumer(
builder: (context, ref, _) {
ref.watch(a);
ref.watch(b);
return Container();
},
),
),
),
],
),
);
final containers = tester.allElements
.where((e) => e.widget is Consumer)
.map(ProviderScope.containerOf)
.toList();
expect(containers, hasLength(2));
for (final container in containers) {
container.read(a.notifier).state++;
}
await tester.pump();
});
testWidgets('ref.invalidate can invalidate a family', (tester) async {
final listener = Listener<String>();
final listener2 = Listener<String>();
var result = 0;
final provider = Provider.family<String, int>((r, i) => '$result-$i');
late WidgetRef ref;
await tester.pumpWidget(
ProviderScope(
child: Consumer(
builder: (context, r, _) {
ref = r;
ref.listen(provider(0), listener.call);
ref.listen(provider(1), listener2.call);
return Container();
},
),
),
);
verifyZeroInteractions(listener);
ref.invalidate(provider);
result = 1;
verifyZeroInteractions(listener);
await tester.pumpAndSettle();
verifyOnly(listener, listener('0-0', '1-0'));
verifyOnly(listener2, listener2('0-1', '1-1'));
});
testWidgets('ref.invalidate triggers a rebuild on next frame',
(tester) async {
final listener = Listener<int>();
var result = 0;
final provider = Provider((r) => result);
late WidgetRef ref;
await tester.pumpWidget(
ProviderScope(
child: Consumer(
builder: (context, r, _) {
ref = r;
ref.listen(provider, listener.call);
return Container();
},
),
),
);
verifyZeroInteractions(listener);
ref.invalidate(provider);
ref.invalidate(provider);
result = 1;
verifyZeroInteractions(listener);
await tester.pumpAndSettle();
verifyOnly(listener, listener(0, 1));
});
testWidgets('ProviderScope can receive a custom parent', (tester) async {
final provider = Provider((ref) => 0);
final container = createContainer(
overrides: [provider.overrideWithValue(42)],
);
await tester.pumpWidget(
ProviderScope(
parent: container,
child: Consumer(
builder: (context, ref, _) {
return Text(
'${ref.watch(provider)}',
textDirection: TextDirection.ltr,
);
},
),
),
);
expect(find.text('42'), findsOneWidget);
});
testWidgets('ProviderScope.parent cannot change', (tester) async {
final container = createContainer();
final container2 = createContainer();
await tester.pumpWidget(
ProviderScope(
parent: container,
child: Container(),
),
);
await tester.pumpWidget(
ProviderScope(
parent: container2,
child: Container(),
),
);
expect(tester.takeException(), isUnsupportedError);
});
testWidgets('ref.read works with providers that returns null',
(tester) async {
final nullProvider = Provider((ref) => null);
late WidgetRef ref;
await tester.pumpWidget(
ProviderScope(
child: Consumer(
builder: (context, r, _) {
ref = r;
return Container();
},
),
),
);
expect(ref.read(nullProvider), null);
});
testWidgets('ref.read can read ScopedProviders', (tester) async {
final provider = Provider((watch) => 42);
late WidgetRef ref;
await tester.pumpWidget(
ProviderScope(
child: Consumer(
builder: (context, r, _) {
ref = r;
return Container();
},
),
),
);
expect(ref.read(provider), 42);
});
testWidgets('ref.read obtains the nearest Provider possible', (tester) async {
late WidgetRef ref;
final provider = Provider((watch) => 42);
await tester.pumpWidget(
ProviderScope(
child: ProviderScope(
overrides: [provider.overrideWithValue(21)],
child: Consumer(
builder: (context, r, _) {
ref = r;
return Container();
},
),
),
),
);
expect(ref.read(provider), 21);
});
testWidgets('widgets cannot modify providers in their build method',
(tester) async {
final onError = FlutterError.onError;
Object? error;
FlutterError.onError = (details) {
error = details.exception;
};
final provider = StateProvider((ref) => 0);
final container = createContainer();
// using runZonedGuarded as StateNotifier will emit an handleUncaughtError
// if a listener threw
await runZonedGuarded(
() => tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: Consumer(
builder: (context, ref, _) {
ref.watch(provider.notifier).state++;
return Container();
},
),
),
),
(error, stack) {},
);
FlutterError.onError = onError;
expect(error, isNotNull);
});
testWidgets('ref.watch within a build method can flush providers',
(tester) async {
final container = createContainer();
final dep = StateProvider((ref) => 0);
final provider = Provider((ref) => ref.watch(dep));
// reading `provider` but not listening to it, so that it is active
// but with no listener – causing "ref.watch" inside Consumer to flush it
container.read(provider);
// We need to use runAsync as the container isn't attached to a ProviderScope
// yet, so the WidgetTester is preventing the scheduler from start microtasks
await tester.runAsync<void>(() async {
// marking `provider` as out of date
container.read(dep.notifier).state++;
});
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: Consumer(
builder: (context, ref, _) {
return Text(
ref.watch(provider).toString(),
textDirection: TextDirection.ltr,
);
},
),
),
);
expect(find.text('1'), findsOneWidget);
});
testWidgets('UncontrolledProviderScope gracefully handles vsync',
(tester) async {
final container = createContainer();
final container2 = createContainer(parent: container);
expect(container.scheduler.flutterVsyncs, isEmpty);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: Container(),
),
);
expect(container.scheduler.flutterVsyncs, hasLength(1));
expect(container2.scheduler.flutterVsyncs, isEmpty);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: UncontrolledProviderScope(
container: container2,
child: Container(),
),
),
);
expect(container.scheduler.flutterVsyncs, hasLength(1));
expect(container2.scheduler.flutterVsyncs, hasLength(1));
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: Container(),
),
);
expect(container.scheduler.flutterVsyncs, hasLength(1));
expect(container2.scheduler.flutterVsyncs, isEmpty);
await tester.pumpWidget(Container());
expect(container.scheduler.flutterVsyncs, isEmpty);
expect(container2.scheduler.flutterVsyncs, isEmpty);
});
testWidgets('When there are multiple vsyncs, rebuild providers only once',
(tester) async {
var buildCount = 0;
final dep = StateProvider((ref) => 0);
final provider = Provider((ref) {
buildCount++;
return ref.watch(dep);
});
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ProviderScope(
child: ProviderScope(
child: Consumer(
builder: (context, ref, _) {
return Text('Hello ${ref.watch(provider)}');
},
),
),
),
),
);
expect(buildCount, 1);
expect(find.text('Hello 0'), findsOneWidget);
expect(find.text('Hello 1'), findsNothing);
final consumerElement = tester.element(find.byType(Consumer));
final container = ProviderScope.containerOf(consumerElement);
container.read(dep.notifier).state++;
await tester.pump();
expect(buildCount, 2);
expect(find.text('Hello 1'), findsOneWidget);
expect(find.text('Hello 0'), findsNothing);
});
testWidgets(
'UncontrolledProviderScope gracefully handles debugCanModifyProviders',
(tester) async {
final container = createContainer();
expect(debugCanModifyProviders, null);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: Container(),
),
);
expect(debugCanModifyProviders, isNotNull);
await tester.pumpWidget(Container());
expect(debugCanModifyProviders, null);
});
testWidgets('ref.refresh forces a provider to refresh', (tester) async {
var future = Future<int>.value(21);
final provider = FutureProvider<int>((ref) => future);
late WidgetRef ref;
await tester.pumpWidget(
ProviderScope(
child: Consumer(
builder: (context, r, _) {
ref = r;
return Container();
},
),
),
);
await expectLater(ref.read(provider.future), completion(21));
future = Future<int>.value(42);
ref.invalidate(provider);
await expectLater(ref.read(provider.future), completion(42));
});
testWidgets('ref.refresh forces a provider of nullable type to refresh',
(tester) async {
int? value = 42;
final provider = Provider<int?>((ref) => value);
late WidgetRef ref;
await tester.pumpWidget(
ProviderScope(
child: Consumer(
builder: (context, r, _) {
ref = r;
return Container();
},
),
),
);
expect(ref.read(provider), 42);
value = null;
expect(ref.refresh(provider), null);
});
// testWidgets('ProviderScope allows specifying a ProviderContainer',
// (tester) async {
// final provider = FutureProvider((ref) async => 42);
// late WidgetRef ref;
// final container = createContainer(overrides: [
// provider.overrideWithValue(const AsyncValue.data(42)),
// ]);
// await tester.pumpWidget(
// UncontrolledProviderScope(
// container: container,
// child: Consumer(
// builder: (context, r, _) {
// ref = r;
// return Container();
// },
// ),
// ),
// );
// expect(ref.read(provider), const AsyncValue.data(42));
// });
testWidgets('AlwaysAliveProviderBase.read(context) inside initState',
(tester) async {
final provider = Provider((_) => 42);
int? result;
await tester.pumpWidget(
ProviderScope(
child: InitState(
initState: (context, ref) => result = ref.read(provider),
),
),
);
expect(result, 42);
});
testWidgets('AlwaysAliveProviderBase.read(context) inside build',
(tester) async {
final provider = Provider((_) => 42);
await tester.pumpWidget(
ProviderScope(
child: Consumer(
builder: (context, ref, _) {
// Allowed even if not a good practice. Will have a lint instead
final value = ref.read(provider);
return Text(
'$value',
textDirection: TextDirection.ltr,
);
},
),
),
);
expect(find.text('42'), findsOneWidget);
});
testWidgets('adding overrides throws', (tester) async {
final provider = Provider((_) => 0);
await tester.pumpWidget(
ProviderScope(
child: Container(),
),
);
expect(tester.takeException(), isNull);
await tester.pumpWidget(
ProviderScope(
overrides: [provider],
child: Container(),
),
);
expect(tester.takeException(), isAssertionError);
});
testWidgets('removing overrides throws', (tester) async {
final provider = Provider((_) => 0);
final consumer = Consumer(
builder: (context, ref, _) {
return Text(
ref.watch(provider).toString(),
textDirection: TextDirection.ltr,
);
},
);
await tester.pumpWidget(
ProviderScope(
overrides: [provider],
child: consumer,
),
);
expect(find.text('0'), findsOneWidget);
await tester.pumpWidget(ProviderScope(child: consumer));
expect(tester.takeException(), isAssertionError);
});
testWidgets('override origin mismatch throws', (tester) async {
final provider = Provider((_) => 0);
final provider2 = Provider((_) => 0);
await tester.pumpWidget(
ProviderScope(
overrides: [provider],
child: Container(),
),
);
expect(tester.takeException(), isNull);
await tester.pumpWidget(
ProviderScope(
overrides: [provider2],
child: Container(),
),
);
expect(tester.takeException(), isAssertionError);
});
testWidgets('throws if no ProviderScope found', (tester) async {
final provider = Provider((_) => 'foo');
await tester.pumpWidget(
Consumer(
builder: (context, ref, _) {
ref.watch(provider);
return Container();
},
),
);
expect(
tester.takeException(),
isA<StateError>()
.having((e) => e.message, 'message', 'No ProviderScope found'),
);
});
testWidgets('providers can be overridden', (tester) async {
final provider = Provider((_) => 'root');
final provider2 = Provider((_) => 'root2');
final builder = Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
Consumer(builder: (c, ref, _) => Text(ref.watch(provider))),
Consumer(builder: (c, ref, _) => Text(ref.watch(provider2))),
],
),
);
await tester.pumpWidget(
ProviderScope(
key: UniqueKey(),
child: builder,
),
);
expect(find.text('root'), findsOneWidget);
expect(find.text('root2'), findsOneWidget);
await tester.pumpWidget(
ProviderScope(
key: UniqueKey(),
overrides: [
provider.overrideWithValue('override'),
],
child: builder,
),
);
expect(find.text('root'), findsNothing);
expect(find.text('override'), findsOneWidget);
expect(find.text('root2'), findsOneWidget);
});
testWidgets('ProviderScope can be nested', (tester) async {
final provider = Provider((_) => 'root');
final provider2 = Provider((_) => 'root2');
await tester.pumpWidget(
ProviderScope(
overrides: [
provider.overrideWithValue('rootOverride'),
],
child: ProviderScope(
child: Consumer(
builder: (c, ref, _) {
final first = ref.watch(provider);
final second = ref.watch(provider2);
return Text(
'$first $second',
textDirection: TextDirection.ltr,
);
},
),
),
),
);
expect(find.text('root root2'), findsNothing);
expect(find.text('rootOverride root2'), findsOneWidget);
});
testWidgets('ProviderScope throws if ancestorOwner changed', (tester) async {
final key = GlobalKey();
await tester.pumpWidget(
ProviderScope(
child: ProviderScope(
key: key,
child: Container(),
),
),
);
expect(find.byType(Container), findsOneWidget);
await tester.pumpWidget(
ProviderScope(
child: ProviderScope(
child: ProviderScope(
key: key,
child: Container(),
),
),
),
);
expect(tester.takeException(), isUnsupportedError);
});
testWidgets('ProviderScope throws if ancestorOwner removed', (tester) async {
final key = GlobalKey();
await tester.pumpWidget(
Stack(
textDirection: TextDirection.ltr,
children: [
ProviderScope(
key: const Key('foo'),
child: ProviderScope(
key: key,
child: Container(),
),
),
],
),
);
expect(find.byType(Container), findsOneWidget);
await tester.pumpWidget(
Stack(
textDirection: TextDirection.ltr,
children: [
ProviderScope(
key: const Key('foo'),
child: Container(),
),
ProviderScope(
key: key,
child: Container(),
),
],
),
);
expect(tester.takeException(), isUnsupportedError);
// re-pump the original tree so that it disposes correctly
await tester.pumpWidget(
Stack(
textDirection: TextDirection.ltr,
children: [
ProviderScope(
key: const Key('foo'),
child: ProviderScope(
key: key,
child: Container(),
),
),
],
),
);
});
group('ProviderScope.containerOf', () {
testWidgets('throws if no container is found independently from `listen`',
(tester) async {
await tester.pumpWidget(Container());
final context = tester.element(find.byType(Container));
expect(
() => ProviderScope.containerOf(context, listen: false),
throwsStateError,
);
expect(
() => ProviderScope.containerOf(context),
throwsStateError,
);
});
});
testWidgets('autoDispose states are kept alive during pushReplacement',
(tester) async {
var disposeCount = 0;
final counterProvider = StateProvider.autoDispose((ref) {
ref.onDispose(() => disposeCount++);
return 0;
});
final container = createContainer();
final key = GlobalKey<NavigatorState>();
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: MaterialApp(
navigatorKey: key,
home: Consumer(
builder: (context, ref, _) {
final count = ref.watch(counterProvider);
return Text('$count');
},
),
),
),
);
expect(find.text('0'), findsOneWidget);
container.read(counterProvider.notifier).state++;
await tester.pump();
expect(find.text('1'), findsOneWidget);
// ignore: unawaited_futures
key.currentState!.pushReplacement<void, void>(
PageRouteBuilder<void>(
pageBuilder: (_, __, ___) {
return Consumer(
builder: (context, ref, _) {
final count = ref.watch(counterProvider);
return Text('new $count');
},
);
},
),
);
await tester.pumpAndSettle();
expect(find.text('1'), findsNothing);
expect(find.text('new 0'), findsNothing);
expect(find.text('new 1'), findsOneWidget);
});
}
class InitState extends ConsumerStatefulWidget {
const InitState({super.key, required this.initState});
// ignore: diagnostic_describe_all_properties
final void Function(BuildContext context, WidgetRef ref) initState;
@override
// ignore: library_private_types_in_public_api
_InitStateState createState() => _InitStateState();
}
class _InitStateState extends ConsumerState<InitState> {
@override
void initState() {
super.initState();
widget.initState(context, ref);
}
@override
Widget build(BuildContext context) {
return Container();
}
}
| riverpod/packages/flutter_riverpod/test/framework_test.dart/0 | {'file_path': 'riverpod/packages/flutter_riverpod/test/framework_test.dart', 'repo_id': 'riverpod', 'token_count': 9450} |
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
void main() {
runApp(
/// [MyApp] is wrapped in a [ProviderScope].
/// This widget is where the state of most of our providers will be stored.
/// This replaces `MultiProvider` if you've used `provider` before.
const ProviderScope(
child: MyApp(),
),
);
}
/// A provider that creates and listen to a [StateNotifier].
///
/// Providers are declared as global variables.
/// This does not hinder testability, as the state of a provider is instead
/// stored inside a [ProviderScope].
final counterProvider = StateNotifierProvider<Counter, int>((_) => Counter());
/// A simple [StateNotifier] that implements a counter.
///
/// It doesn't have to be a [StateNotifier], and could be anything else such as:
/// - [ChangeNotifier], with [ChangeNotifierProvider]
/// - [Stream], with [StreamProvider]
/// ...
class Counter extends StateNotifier<int> {
Counter() : super(0);
void increment() => state++;
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends HookConsumerWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
appBar: AppBar(
title: const Text('Riverpod counter example'),
),
body: Center(
// HookConsumer is a builder widget that allows you to read providers and utilise hooks.
child: HookConsumer(
builder: (context, ref, _) {
final count = ref.watch(counterProvider);
return Text(
'$count',
style: Theme.of(context).textTheme.headlineMedium,
);
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => ref.read(counterProvider.notifier).increment(),
child: const Icon(Icons.add),
),
);
}
}
| riverpod/packages/hooks_riverpod/example/lib/main.dart/0 | {'file_path': 'riverpod/packages/hooks_riverpod/example/lib/main.dart', 'repo_id': 'riverpod', 'token_count': 742} |
import 'package:meta/meta.dart';
import 'framework.dart';
import 'future_provider.dart' show FutureProvider;
import 'stack_trace.dart';
import 'stream_provider.dart' show StreamProvider;
/// An extension for [asyncTransition].
@internal
extension AsyncTransition<T> on ProviderElementBase<AsyncValue<T>> {
/// Internal utility for transitioning an [AsyncValue] after a provider refresh.
///
/// [seamless] controls how the previous state is preserved:
/// - seamless:true => import previous state and skip loading
/// - seamless:false => import previous state and prefer loading
void asyncTransition(
AsyncValue<T> newState, {
required bool seamless,
}) {
// ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member
final previous = getState()?.requireState;
if (previous == null) {
// ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member
setState(newState);
} else {
// ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member
setState(
newState._cast<T>().copyWithPrevious(previous, isRefresh: seamless),
);
}
}
}
/// A utility for safely manipulating asynchronous data.
///
/// By using [AsyncValue], you are guaranteed that you cannot forget to
/// handle the loading/error state of an asynchronous operation.
///
/// It also exposes some utilities to nicely convert an [AsyncValue] to
/// a different object.
/// For example, a Flutter Widget may use [when] to convert an [AsyncValue]
/// into either a progress indicator, an error screen, or to show the data:
///
/// ```dart
/// /// A provider that asynchronously exposes the current user
/// final userProvider = StreamProvider<User>((_) async* {
/// // fetch the user
/// });
///
/// class Example extends ConsumerWidget {
/// @override
/// Widget build(BuildContext context, WidgetRef ref) {
/// final AsyncValue<User> user = ref.watch(userProvider);
///
/// return user.when(
/// loading: () => CircularProgressIndicator(),
/// error: (error, stack) => Text('Oops, something unexpected happened'),
/// data: (user) => Text('Hello ${user.name}'),
/// );
/// }
/// }
/// ```
///
/// If a consumer of an [AsyncValue] does not care about the loading/error
/// state, consider using [value]/[valueOrNull] to read the state:
///
/// ```dart
/// Widget build(BuildContext context, WidgetRef ref) {
/// // Reading .value will be throw during error and return null on "loading" states.
/// final User user = ref.watch(userProvider).value;
///
/// // Reading .value will be throw both on loading and error states.
/// final User user2 = ref.watch(userProvider).requiredValue;
///
/// ...
/// }
/// ```
///
/// See also:
///
/// - [FutureProvider], [StreamProvider] which transforms a [Future] into
/// an [AsyncValue].
/// - [AsyncValue.guard], to simplify transforming a [Future] into an [AsyncValue].
@sealed
@immutable
abstract class AsyncValue<T> {
const AsyncValue._();
/// {@template asyncvalue.data}
/// Creates an [AsyncValue] with a data.
/// {@endtemplate}
// coverage:ignore-start
const factory AsyncValue.data(T value) = AsyncData<T>;
// coverage:ignore-end
/// {@template asyncvalue.loading}
/// Creates an [AsyncValue] in loading state.
///
/// Prefer always using this constructor with the `const` keyword.
/// {@endtemplate}
// coverage:ignore-start
const factory AsyncValue.loading() = AsyncLoading<T>;
// coverage:ignore-end
/// {@template asyncvalue.error_ctor}
/// Creates an [AsyncValue] in the error state.
///
/// _I don't have a [StackTrace], what can I do?_
/// You can still construct an [AsyncError] by passing [StackTrace.current]:
///
/// ```dart
/// AsyncValue.error(error, StackTrace.current);
/// ```
/// {@endtemplate}
// coverage:ignore-start
const factory AsyncValue.error(Object error, StackTrace stackTrace) =
AsyncError<T>;
// coverage:ignore-end
/// Transforms a [Future] that may fail into something that is safe to read.
///
/// This is useful to avoid having to do a tedious `try/catch`. Instead of
/// writing:
///
/// ```dart
/// class MyNotifier extends AsyncNotifier<MyData> {
/// @override
/// Future<MyData> build() => Future.value(MyData());
///
/// Future<void> sideEffect() async {
/// state = const AsyncValue.loading();
/// try {
/// final response = await dio.get('my_api/data');
/// final data = MyData.fromJson(response);
/// state = AsyncValue.data(data);
/// } catch (err, stack) {
/// state = AsyncValue.error(err, stack);
/// }
/// }
/// }
/// ```
///
/// We can use [guard] to simplify it:
///
/// ```dart
/// class MyNotifier extends AsyncNotifier<MyData> {
/// @override
/// Future<MyData> build() => Future.value(MyData());
///
/// Future<void> sideEffect() async {
/// state = const AsyncValue.loading();
/// // does the try/catch for us like previously
/// state = await AsyncValue.guard(() async {
/// final response = await dio.get('my_api/data');
/// return Data.fromJson(response);
/// });
/// }
/// }
///
/// An optional callback can be specified to catch errors only under a certain condition.
/// In the following example, we catch all exceptions beside FormatExceptions.
///
/// ```dart
/// AsyncValue.guard(
/// () async { /* ... */ },
/// // Catch all errors beside [FormatException]s.
/// (err) => err is! FormatException,
/// );
/// }
/// ```
static Future<AsyncValue<T>> guard<T>(
Future<T> Function() future, [
bool Function(Object)? test,
]) async {
try {
return AsyncValue.data(await future());
} catch (err, stack) {
if (test == null) {
return AsyncValue.error(err, stack);
}
if (test(err)) {
return AsyncValue.error(err, stack);
}
Error.throwWithStackTrace(err, stack);
}
}
/// Whether some new value is currently asynchronously loading.
///
/// Even if [isLoading] is true, it is still possible for [hasValue]/[hasError]
/// to also be true.
bool get isLoading;
/// Whether [value] is set.
///
/// Even if [hasValue] is true, it is still possible for [isLoading]/[hasError]
/// to also be true.
bool get hasValue;
/// The value currently exposed.
///
/// It will return the previous value during loading/error state.
/// If there is no previous value, reading [value] during loading state will
/// return null. While during error state, the error will be rethrown instead.
///
/// If you do not want to return previous value during loading/error states,
/// consider using [unwrapPrevious] with [valueOrNull]:
///
/// ```dart
/// ref.watch(provider).unwrapPrevious().valueOrNull;
/// ```
///
/// This will return null during loading/error states.
T? get value;
/// The [error].
Object? get error;
/// The stacktrace of [error].
StackTrace? get stackTrace;
/// Casts the [AsyncValue] to a different type.
AsyncValue<R> _cast<R>();
/// Perform some action based on the current state of the [AsyncValue].
///
/// This allows reading the content of an [AsyncValue] in a type-safe way,
/// without potentially ignoring to handle a case.
R map<R>({
required R Function(AsyncData<T> data) data,
required R Function(AsyncError<T> error) error,
required R Function(AsyncLoading<T> loading) loading,
});
/// Clone an [AsyncValue], merging it with [previous].
///
/// When doing so, the resulting [AsyncValue] can contain the information
/// about multiple state at once.
/// For example, this allows an [AsyncError] to contain a [value], or even
/// [AsyncLoading] to contain both a [value] and an [error].
///
/// The optional [isRefresh] flag (true by default) represents whether the
/// provider rebuilt by [Ref.refresh]/[Ref.invalidate] (if true)
/// or instead by [Ref.watch] (if false).
/// This changes the default behavior of [when] and sets the [isReloading]/
/// [isRefreshing] flags accordingly.
AsyncValue<T> copyWithPrevious(
AsyncValue<T> previous, {
bool isRefresh = true,
});
/// The opposite of [copyWithPrevious], reverting to the raw [AsyncValue]
/// with no information on the previous state.
AsyncValue<T> unwrapPrevious() {
return map(
data: (d) {
if (d.isLoading) return AsyncLoading<T>();
return AsyncData(d.value);
},
error: (e) {
if (e.isLoading) return AsyncLoading<T>();
return AsyncError(e.error, e.stackTrace);
},
loading: (l) => AsyncLoading<T>(),
);
}
@override
String toString() {
final content = [
if (isLoading && this is! AsyncLoading) 'isLoading: $isLoading',
if (hasValue) 'value: $value',
if (hasError) ...[
'error: $error',
'stackTrace: $stackTrace',
],
].join(', ');
return '$runtimeType($content)';
}
@override
bool operator ==(Object other) {
return runtimeType == other.runtimeType &&
other is AsyncValue<T> &&
other.isLoading == isLoading &&
other.hasValue == hasValue &&
other.error == error &&
other.stackTrace == stackTrace &&
other.valueOrNull == valueOrNull;
}
@override
int get hashCode => Object.hash(
runtimeType,
isLoading,
hasValue,
valueOrNull,
error,
stackTrace,
);
}
/// {@macro asyncvalue.data}
class AsyncData<T> extends AsyncValue<T> {
/// {@macro asyncvalue.data}
const AsyncData(T value)
: this._(
value,
isLoading: false,
error: null,
stackTrace: null,
);
const AsyncData._(
this.value, {
required this.isLoading,
required this.error,
required this.stackTrace,
}) : super._();
@override
final T value;
@override
bool get hasValue => true;
@override
final bool isLoading;
@override
final Object? error;
@override
final StackTrace? stackTrace;
@override
R map<R>({
required R Function(AsyncData<T> data) data,
required R Function(AsyncError<T> error) error,
required R Function(AsyncLoading<T> loading) loading,
}) {
return data(this);
}
@override
AsyncData<T> copyWithPrevious(
AsyncValue<T> previous, {
bool isRefresh = true,
}) {
return this;
}
@override
AsyncValue<R> _cast<R>() {
if (T == R) return this as AsyncValue<R>;
return AsyncData<R>._(
value as R,
isLoading: isLoading,
error: error,
stackTrace: stackTrace,
);
}
}
/// {@macro asyncvalue.loading}
class AsyncLoading<T> extends AsyncValue<T> {
/// {@macro asyncvalue.loading}
const AsyncLoading()
: hasValue = false,
value = null,
error = null,
stackTrace = null,
super._();
const AsyncLoading._({
required this.hasValue,
required this.value,
required this.error,
required this.stackTrace,
}) : super._();
@override
bool get isLoading => true;
@override
final bool hasValue;
@override
final T? value;
@override
final Object? error;
@override
final StackTrace? stackTrace;
@override
AsyncValue<R> _cast<R>() {
if (T == R) return this as AsyncValue<R>;
return AsyncLoading<R>._(
hasValue: hasValue,
value: value as R?,
error: error,
stackTrace: stackTrace,
);
}
@override
R map<R>({
required R Function(AsyncData<T> data) data,
required R Function(AsyncError<T> error) error,
required R Function(AsyncLoading<T> loading) loading,
}) {
return loading(this);
}
@override
AsyncValue<T> copyWithPrevious(
AsyncValue<T> previous, {
bool isRefresh = true,
}) {
if (isRefresh) {
return previous.map(
data: (d) => AsyncData._(
d.value,
isLoading: true,
error: d.error,
stackTrace: d.stackTrace,
),
error: (e) => AsyncError._(
e.error,
isLoading: true,
value: e.valueOrNull,
stackTrace: e.stackTrace,
hasValue: e.hasValue,
),
loading: (_) => this,
);
} else {
return previous.map(
data: (d) => AsyncLoading._(
hasValue: true,
value: d.valueOrNull,
error: d.error,
stackTrace: d.stackTrace,
),
error: (e) => AsyncLoading._(
hasValue: e.hasValue,
value: e.valueOrNull,
error: e.error,
stackTrace: e.stackTrace,
),
loading: (e) => e,
);
}
}
}
/// {@macro asyncvalue.error_ctor}
class AsyncError<T> extends AsyncValue<T> {
/// {@macro asyncvalue.error_ctor}
const AsyncError(Object error, StackTrace stackTrace)
: this._(
error,
stackTrace: stackTrace,
isLoading: false,
hasValue: false,
value: null,
);
const AsyncError._(
this.error, {
required this.stackTrace,
required T? value,
required this.hasValue,
required this.isLoading,
}) : _value = value,
super._();
@override
final bool isLoading;
@override
final bool hasValue;
final T? _value;
@override
T? get value {
if (!hasValue) {
throwErrorWithCombinedStackTrace(error, stackTrace);
}
return _value;
}
@override
final Object error;
@override
final StackTrace stackTrace;
@override
AsyncValue<R> _cast<R>() {
if (T == R) return this as AsyncValue<R>;
return AsyncError<R>._(
error,
stackTrace: stackTrace,
isLoading: isLoading,
value: _value as R?,
hasValue: hasValue,
);
}
@override
R map<R>({
required R Function(AsyncData<T> data) data,
required R Function(AsyncError<T> error) error,
required R Function(AsyncLoading<T> loading) loading,
}) {
return error(this);
}
@override
AsyncError<T> copyWithPrevious(
AsyncValue<T> previous, {
bool isRefresh = true,
}) {
return AsyncError._(
error,
stackTrace: stackTrace,
isLoading: isLoading,
value: previous.valueOrNull,
hasValue: previous.hasValue,
);
}
}
/// An extension that adds methods like [when] to an [AsyncValue].
extension AsyncValueX<T> on AsyncValue<T> {
/// If [hasValue] is true, returns the value.
/// Otherwise if [hasError], rethrows the error.
/// Finally if in loading state, throws a [StateError].
///
/// This is typically used for when the UI assumes that [value] is always present.
T get requireValue {
if (hasValue) return value as T;
if (hasError) {
throwErrorWithCombinedStackTrace(error!, stackTrace!);
}
throw StateError(
'Tried to call `requireValue` on an `AsyncValue` that has no value: $this',
);
}
/// Return the value or previous value if in loading/error state.
///
/// If there is no previous value, null will be returned during loading/error state.
///
/// This is different from [value], which will rethrow the error instead of returning null.
///
/// If you do not want to return previous value during loading/error states,
/// consider using [unwrapPrevious] :
///
/// ```dart
/// ref.watch(provider).unwrapPrevious()?.valueOrNull;
/// ```
T? get valueOrNull {
if (hasValue) return value;
return null;
}
/// Whether the associated provider was forced to recompute even though
/// none of its dependencies has changed, after at least one [value]/[error] was emitted.
///
/// This is usually the case when rebuilding a provider with either
/// [Ref.invalidate]/[Ref.refresh].
///
/// If a provider rebuilds because one of its dependencies changes (using [Ref.watch]),
/// then [isRefreshing] will be false, and instead [isReloading] will be true.
bool get isRefreshing =>
isLoading && (hasValue || hasError) && this is! AsyncLoading;
/// Whether the associated provider was recomputed because of a dependency change
/// (using [Ref.watch]), after at least one [value]/[error] was emitted.
///
/// If a provider rebuilds because one of its dependencies changed (using [Ref.watch]),
/// then [isReloading] will be true.
/// If a provider rebuilds only due to [Ref.invalidate]/[Ref.refresh], then
/// [isReloading] will be false (and [isRefreshing] will be true).
///
/// See also [isRefreshing] for manual provider rebuild.
bool get isReloading => (hasValue || hasError) && this is AsyncLoading;
/// Whether [error] is not null.
///
/// Even if [hasError] is true, it is still possible for [hasValue]/[isLoading]
/// to also be true.
// It is safe to check it through `error != null` because `error` is non-nullable
// on the AsyncError constructor.
bool get hasError => error != null;
/// Upcast [AsyncValue] into an [AsyncData], or return null if the [AsyncValue]
/// is an [AsyncLoading]/[AsyncError].
///
/// Note that an [AsyncData] may still be in loading/error state, such
/// as during a pull-to-refresh.
AsyncData<T>? get asData {
return map(
data: (d) => d,
error: (e) => null,
loading: (l) => null,
);
}
/// Upcast [AsyncValue] into an [AsyncError], or return null if the [AsyncValue]
/// is an [AsyncLoading]/[AsyncData].
///
/// Note that an [AsyncError] may still be in loading state, such
/// as during a pull-to-refresh.
AsyncError<T>? get asError => map(
data: (_) => null,
error: (e) => e,
loading: (_) => null,
);
/// Shorthand for [when] to handle only the `data` case.
///
/// For loading/error cases, creates a new [AsyncValue] with the corresponding
/// generic type while preserving the error/stacktrace.
AsyncValue<R> whenData<R>(R Function(T value) cb) {
return map(
data: (d) {
try {
return AsyncData._(
cb(d.value),
isLoading: d.isLoading,
error: d.error,
stackTrace: d.stackTrace,
);
} catch (err, stack) {
return AsyncError._(
err,
stackTrace: stack,
isLoading: d.isLoading,
value: null,
hasValue: false,
);
}
},
error: (e) => AsyncError._(
e.error,
stackTrace: e.stackTrace,
isLoading: e.isLoading,
value: null,
hasValue: false,
),
loading: (l) => AsyncLoading<R>(),
);
}
/// Switch-case over the state of the [AsyncValue] while purposefully not handling
/// some cases.
///
/// If [AsyncValue] was in a case that is not handled, will return [orElse].
///
/// {@macro asyncvalue.skip_flags}
R maybeWhen<R>({
bool skipLoadingOnReload = false,
bool skipLoadingOnRefresh = true,
bool skipError = false,
R Function(T data)? data,
R Function(Object error, StackTrace stackTrace)? error,
R Function()? loading,
required R Function() orElse,
}) {
return when(
skipError: skipError,
skipLoadingOnRefresh: skipLoadingOnRefresh,
skipLoadingOnReload: skipLoadingOnReload,
data: data ?? (_) => orElse(),
error: error ?? (err, stack) => orElse(),
loading: loading ?? () => orElse(),
);
}
/// Performs an action based on the state of the [AsyncValue].
///
/// All cases are required, which allows returning a non-nullable value.
///
/// {@template asyncvalue.skip_flags}
/// By default, [when] skips "loading" states if triggered by a [Ref.refresh]
/// or [Ref.invalidate] (but does not skip loading states if triggered by [Ref.watch]).
///
/// In the event that an [AsyncValue] is in multiple states at once (such as
/// when reloading a provider or emitting an error after a valid data),
/// [when] offers various flags to customize whether it should call
/// [loading]/[error]/[data] :
///
/// - [skipLoadingOnReload] (false by default) customizes whether [loading]
/// should be invoked if a provider rebuilds because of [Ref.watch].
/// In that situation, [when] will try to invoke either [error]/[data]
/// with the previous state.
///
/// - [skipLoadingOnRefresh] (true by default) controls whether [loading]
/// should be invoked if a provider rebuilds because of [Ref.refresh]
/// or [Ref.invalidate].
/// In that situation, [when] will try to invoke either [error]/[data]
/// with the previous state.
///
/// - [skipError] (false by default) decides whether to invoke [data] instead
/// of [error] if a previous [value] is available.
/// {@endtemplate}
R when<R>({
bool skipLoadingOnReload = false,
bool skipLoadingOnRefresh = true,
bool skipError = false,
required R Function(T data) data,
required R Function(Object error, StackTrace stackTrace) error,
required R Function() loading,
}) {
if (isLoading) {
bool skip;
if (isRefreshing) {
skip = skipLoadingOnRefresh;
} else if (isReloading) {
skip = skipLoadingOnReload;
} else {
skip = false;
}
if (!skip) return loading();
}
if (hasError && (!hasValue || !skipError)) {
return error(this.error!, stackTrace!);
}
return data(requireValue);
}
/// Perform actions conditionally based on the state of the [AsyncValue].
///
/// Returns null if [AsyncValue] was in a state that was not handled.
/// This is similar to [maybeWhen] where `orElse` returns null.
///
/// {@macro asyncvalue.skip_flags}
R? whenOrNull<R>({
bool skipLoadingOnReload = false,
bool skipLoadingOnRefresh = true,
bool skipError = false,
R? Function(T data)? data,
R? Function(Object error, StackTrace stackTrace)? error,
R? Function()? loading,
}) {
return when(
skipError: skipError,
skipLoadingOnRefresh: skipLoadingOnRefresh,
skipLoadingOnReload: skipLoadingOnReload,
data: data ?? (_) => null,
error: error ?? (err, stack) => null,
loading: loading ?? () => null,
);
}
/// Perform some actions based on the state of the [AsyncValue], or call orElse
/// if the current state was not tested.
R maybeMap<R>({
R Function(AsyncData<T> data)? data,
R Function(AsyncError<T> error)? error,
R Function(AsyncLoading<T> loading)? loading,
required R Function() orElse,
}) {
return map(
data: (d) {
if (data != null) return data(d);
return orElse();
},
error: (d) {
if (error != null) return error(d);
return orElse();
},
loading: (d) {
if (loading != null) return loading(d);
return orElse();
},
);
}
/// Perform some actions based on the state of the [AsyncValue], or return null
/// if the current state wasn't tested.
R? mapOrNull<R>({
R? Function(AsyncData<T> data)? data,
R? Function(AsyncError<T> error)? error,
R? Function(AsyncLoading<T> loading)? loading,
}) {
return map(
data: (d) => data?.call(d),
error: (d) => error?.call(d),
loading: (d) => loading?.call(d),
);
}
}
| riverpod/packages/riverpod/lib/src/common.dart/0 | {'file_path': 'riverpod/packages/riverpod/lib/src/common.dart', 'repo_id': 'riverpod', 'token_count': 8590} |
import 'package:meta/meta.dart';
import 'package:stack_trace/stack_trace.dart';
/// Rethrows [error] with a stacktrace that is the combination of [stackTrace]
/// and [StackTrace.current].
@internal
Never throwErrorWithCombinedStackTrace(Object error, StackTrace stackTrace) {
final chain = Chain([
Trace.current(),
...Chain.forTrace(stackTrace).traces,
]).foldFrames((frame) => frame.package == 'riverpod');
Error.throwWithStackTrace(error, chain.toTrace().vmTrace);
}
| riverpod/packages/riverpod/lib/src/stack_trace.dart/0 | {'file_path': 'riverpod/packages/riverpod/lib/src/stack_trace.dart', 'repo_id': 'riverpod', 'token_count': 161} |
name: riverpod
description: >
A reactive caching and data-binding framework.
Riverpod makes working with asynchronous code a breeze.
version: 2.4.9
homepage: https://riverpod.dev
repository: https://github.com/rrousselGit/riverpod
issue_tracker: https://github.com/rrousselGit/riverpod/issues
funding:
- https://github.com/sponsors/rrousselGit/
environment:
sdk: ">=2.17.0 <3.0.0"
dependencies:
meta: ^1.9.0
stack_trace: ^1.10.0
state_notifier: ">=0.7.2 <2.0.0"
dev_dependencies:
analyzer: ">=5.12.0 <7.0.0"
expect_error: ^1.0.0
mockito: ^5.0.0
test: ^1.16.0
trotter: ^2.0.0-dev.1
| riverpod/packages/riverpod/pubspec.yaml/0 | {'file_path': 'riverpod/packages/riverpod/pubspec.yaml', 'repo_id': 'riverpod', 'token_count': 261} |
import 'package:mockito/mockito.dart';
import 'package:riverpod/src/internals.dart';
import 'package:test/test.dart';
import '../utils.dart';
void main() {
late ProviderContainer container;
setUp(() {
container = ProviderContainer();
});
tearDown(() {
container.dispose();
});
test(
'Catches circular dependency when dependencies are setup during provider initialization',
() {
// regression for #1766
final container = createContainer();
final authInterceptorProvider = Provider((ref) => ref);
final dioProvider = Provider<int>((ref) {
ref.watch(authInterceptorProvider);
return 0;
});
final accessTokenProvider = Provider<int>((ref) {
return ref.watch(dioProvider);
});
container.read(dioProvider);
final interceptor = container.read(authInterceptorProvider);
expect(
() => interceptor.read(accessTokenProvider),
throwsA(isA<CircularDependencyError>()),
);
});
group('ProviderContainer.debugVsyncs', () {
// test('are called before modifying a provider', () {
// final provider = StateProvider((ref) => 0);
// final container = ProviderContainer();
// final vsync = VsyncMock();
// final vsync2 = VsyncMock();
// container.debugVsyncs.addAll([vsync, vsync2]);
// final state = container.read(provider);
// verifyZeroInteractions(vsync);
// verifyZeroInteractions(vsync2);
// state.state++;
// verifyOnly(vsync, vsync());
// verifyOnly(vsync2, vsync2());
// });
// test('are not called when flushing a provider', () {
// final dep = StateProvider((ref) => 0);
// final provider = Provider((ref) {
// return ref.watch(dep);
// });
// final container = ProviderContainer();
// final vsync = VsyncMock();
// final sub = container.listen(provider, (_) {});
// container.read(dep.notifier).state++;
// container.debugVsyncs.add(vsync);
// sub.flush();
// verifyZeroInteractions(vsync);
// });
// test('are not called when re-creating a provider', () {
// final provider = Provider((ref) => 0);
// final container = ProviderContainer();
// final vsync = VsyncMock();
// final sub = container.listen(provider, (_) {});
// container.refresh(provider);
// container.debugVsyncs.add(vsync);
// sub.flush();
// verifyZeroInteractions(vsync);
// });
});
test('rebuilding a provider can modify other providers', () async {
final dep = StateProvider((ref) => 0);
final provider = Provider((ref) => ref.watch(dep));
final another = StateProvider<int>((ref) {
ref.listen(provider, (prev, value) => ref.controller.state++);
return 0;
});
final container = createContainer();
expect(container.read(another), 0);
container.read(dep.notifier).state = 42;
expect(container.read(another), 1);
});
group('ref.watch cannot end-up in a circular dependency', () {
test('direct dependency', () {
final provider = Provider((ref) => ref);
final provider2 = Provider((ref) => ref);
final container = ProviderContainer();
final ref = container.read(provider);
final ref2 = container.read(provider2);
ref.watch(provider2);
expect(
() => ref2.watch(provider),
throwsA(isA<CircularDependencyError>()),
);
});
test('indirect dependency', () {
final provider = Provider((ref) => ref);
final provider2 = Provider((ref) => ref);
final provider3 = Provider((ref) => ref);
final provider4 = Provider((ref) => ref);
final container = ProviderContainer();
final ref = container.read(provider);
final ref2 = container.read(provider2);
final ref3 = container.read(provider3);
final ref4 = container.read(provider4);
ref.watch(provider2);
ref2.watch(provider3);
ref3.watch(provider4);
expect(
() => ref4.watch(provider),
throwsA(isA<CircularDependencyError>()),
);
});
});
group('ref.read cannot end-up in a circular dependency', () {
test('direct dependency', () {
final provider = Provider((ref) => ref);
final provider2 = Provider((ref) => ref);
final container = ProviderContainer();
final ref = container.read(provider);
final ref2 = container.read(provider2);
ref.watch(provider2);
expect(
() => ref2.read(provider),
throwsA(isA<CircularDependencyError>()),
);
});
test('indirect dependency', () {
final provider = Provider((ref) => ref);
final provider2 = Provider((ref) => ref);
final provider3 = Provider((ref) => ref);
final provider4 = Provider((ref) => ref);
final container = ProviderContainer();
final ref = container.read(provider);
final ref2 = container.read(provider2);
final ref3 = container.read(provider3);
final ref4 = container.read(provider4);
ref.watch(provider2);
ref2.watch(provider3);
ref3.watch(provider4);
expect(
() => ref4.read(provider),
throwsA(isA<CircularDependencyError>()),
);
});
});
test("initState can't dirty ancestors", () {
final ancestor = StateProvider((_) => 0);
final child = Provider((ref) {
ref.watch(ancestor.notifier).state++;
return ref.watch(ancestor);
});
expect(errorsOf(() => container.read(child)), isNotEmpty);
});
test("initState can't dirty siblings", () {
final ancestor = StateProvider((_) => 0, name: 'ancestor');
final counter = Counter();
final sibling = StateNotifierProvider<Counter, int>(
name: 'sibling',
(ref) {
ref.watch(ancestor);
return counter;
},
);
var didWatchAncestor = false;
final child = Provider(
name: 'child',
(ref) {
ref.watch(ancestor);
didWatchAncestor = true;
counter.increment();
},
);
container.read(sibling);
expect(errorsOf(() => container.read(child)), isNotEmpty);
expect(didWatchAncestor, true);
});
test("initState can't mark dirty other provider", () {
final provider = StateProvider((ref) => 0);
final provider2 = Provider((ref) {
ref.watch(provider.notifier).state = 42;
return 0;
});
expect(container.read(provider), 0);
expect(errorsOf(() => container.read(provider2)), isNotEmpty);
});
test("nested initState can't mark dirty other providers", () {
final counter = Counter();
final provider = StateNotifierProvider<Counter, int>((_) => counter);
final nested = Provider((_) => 0);
final provider2 = Provider((ref) {
ref.watch(nested);
counter.increment();
return 0;
});
expect(container.read(provider), 0);
expect(errorsOf(() => container.read(provider2)), isNotEmpty);
});
test('auto dispose can dirty providers', () async {
final counter = Counter();
final provider = StateNotifierProvider<Counter, int>((_) => counter);
var didDispose = false;
final provider2 = Provider.autoDispose((ref) {
ref.onDispose(() {
didDispose = true;
counter.increment();
});
});
container.read(provider);
final sub = container.listen<void>(provider2, (_, __) {});
sub.close();
expect(counter.state, 0);
await container.pump();
expect(didDispose, true);
expect(counter.state, 1);
});
test("Provider can't dirty anything on create", () {
final counter = Counter();
final provider = StateNotifierProvider<Counter, int>((_) => counter);
late List<Object> errors;
final computed = Provider((ref) {
errors = errorsOf(counter.increment);
return 0;
});
final listener = Listener<int>();
expect(container.read(provider), 0);
container.listen(computed, listener.call, fireImmediately: true);
verify(listener(null, 0)).called(1);
verifyNoMoreInteractions(listener);
expect(errors, isNotEmpty);
});
}
// class VsyncMock extends Mock {
// void call();
// }
| riverpod/packages/riverpod/test/framework/uni_directional_test.dart/0 | {'file_path': 'riverpod/packages/riverpod/test/framework/uni_directional_test.dart', 'repo_id': 'riverpod', 'token_count': 3052} |
part of '../riverpod_ast.dart';
abstract class ProviderListenableExpressionParent implements RiverpodAst {}
class ProviderListenableExpression extends RiverpodAst {
ProviderListenableExpression._({
required this.node,
required this.provider,
required this.providerPrefix,
required this.providerElement,
required this.familyArguments,
});
static ProviderListenableExpression? _parse(Expression? expression) {
if (expression == null) return null;
SimpleIdentifier? provider;
SimpleIdentifier? providerPrefix;
ProviderDeclarationElement? providerElement;
ArgumentList? familyArguments;
void parseExpression(Expression? expression) {
// Can be reached when the code contains syntax errors
if (expression == null) return;
if (expression is SimpleIdentifier) {
// watch(expression)
provider = expression;
final element = expression.staticElement;
if (element is PropertyAccessorElement) {
// watch(provider)
DartObject? annotation;
try {
annotation =
providerForType.firstAnnotationOfExact(element.variable);
} catch (_) {
return;
}
if (annotation == null) {
providerElement =
LegacyProviderDeclarationElement.parse(element.variable);
} else {
providerElement = _parseGeneratedProviderFromAnnotation(annotation);
}
}
} else if (expression is FunctionExpressionInvocation) {
// watch(expression())
familyArguments = expression.argumentList;
parseExpression(expression.function);
} else if (expression is MethodInvocation) {
// watch(expression.method())
parseExpression(expression.target);
} else if (expression is PrefixedIdentifier) {
// watch(expression.modifier)
final element = expression.prefix.staticElement;
if (element is PrefixElement) {
providerPrefix = expression.prefix;
parseExpression(expression.identifier);
} else {
parseExpression(expression.prefix);
}
} else if (expression is IndexExpression) {
// watch(expression[])
parseExpression(expression.target);
} else if (expression is PropertyAccess) {
// watch(expression.property)
parseExpression(expression.target);
}
}
parseExpression(expression);
return ProviderListenableExpression._(
node: expression,
provider: provider,
providerPrefix: providerPrefix,
providerElement: providerElement,
// Make sure `(){}()` doesn't report an argument list even though it's not a provider
familyArguments: provider == null ? null : familyArguments,
);
}
static GeneratorProviderDeclarationElement?
_parseGeneratedProviderFromAnnotation(
DartObject annotation,
) {
final generatedProviderDefinition = annotation.getField('value')!;
final function = generatedProviderDefinition.toFunctionValue();
if (function != null) {
return FunctionalProviderDeclarationElement.parse(
function,
annotation: null,
);
}
late final type = generatedProviderDefinition.toTypeValue()?.element;
if (type != null && type is ClassElement) {
return ClassBasedProviderDeclarationElement.parse(
type,
annotation: null,
);
} else {
throw StateError('Unknown value $generatedProviderDefinition');
}
}
final Expression node;
final SimpleIdentifier? providerPrefix;
final SimpleIdentifier? provider;
final ProviderDeclarationElement? providerElement;
/// If [provider] is a provider with arguments (family), represents the arguments
/// passed to the provider.
final ArgumentList? familyArguments;
@override
void accept(RiverpodAstVisitor visitor) {
visitor.visitProviderListenableExpression(this);
}
@override
void visitChildren(RiverpodAstVisitor visitor) {}
}
| riverpod/packages/riverpod_analyzer_utils/lib/src/riverpod_ast/provider_listenable_expression.dart/0 | {'file_path': 'riverpod/packages/riverpod_analyzer_utils/lib/src/riverpod_ast/provider_listenable_expression.dart', 'repo_id': 'riverpod', 'token_count': 1411} |
dependency_overrides:
flutter_riverpod: ^1.0.4
hooks_riverpod: ^1.0.4
riverpod: ^1.0.3+1
| riverpod/packages/riverpod_cli/fixtures/unified_syntax/golden/pubspec_overrides.yaml/0 | {'file_path': 'riverpod/packages/riverpod_cli/fixtures/unified_syntax/golden/pubspec_overrides.yaml', 'repo_id': 'riverpod', 'token_count': 48} |
import 'dart:io';
import 'package:pub_semver/pub_semver.dart';
import 'package:riverpod_cli/src/migrate/notifiers.dart';
import 'package:test/test.dart';
import 'goldens.dart';
void main() {
group('notifiers', () {
Future<void> testNotifier(
String type,
VersionConstraint versionConstraint,
) async {
final sourceFile =
await fileContextForInput('./fixtures/notifiers/input/$type.dart');
final expected =
File('./fixtures/notifiers/golden/$type.dart').readAsStringSync();
await expectSuggestorGeneratesFormattedPatches(
RiverpodNotifierChangesMigrationSuggestor(versionConstraint).call,
sourceFile,
expected,
);
}
Future<void> testAlreadyMigrated(
String type,
VersionConstraint versionConstraint,
) async {
final sourceFile =
await fileContextForInput('./fixtures/notifiers/golden/$type.dart');
final expected =
File('./fixtures/notifiers/golden/$type.dart').readAsStringSync();
await expectSuggestorGeneratesFormattedPatches(
RiverpodNotifierChangesMigrationSuggestor(versionConstraint).call,
sourceFile,
expected,
);
}
test('ChangeNotifier', () async {
await testNotifier(
'change_notifier_provider',
VersionConstraint.parse('^0.13.0'),
);
});
test('StateNotifier', () async {
await testNotifier(
'state_notifier_provider',
VersionConstraint.parse('^0.13.0'),
);
});
test('StateProvider', () async {
await testNotifier(
'state_provider',
VersionConstraint.parse('^0.13.0'),
);
});
group('Already Migrated', () {
test('ChangeNotifier', () async {
await testAlreadyMigrated(
'change_notifier_provider',
VersionConstraint.parse('^0.14.0'),
);
});
test('StateNotifier', () async {
await testAlreadyMigrated(
'state_notifier_provider',
VersionConstraint.parse('^0.14.0'),
);
});
test('StateProvider', () async {
await testAlreadyMigrated(
'state_provider',
VersionConstraint.parse('^0.14.0'),
);
});
});
});
}
| riverpod/packages/riverpod_cli/test/notifiers_test.dart/0 | {'file_path': 'riverpod/packages/riverpod_cli/test/notifiers_test.dart', 'repo_id': 'riverpod', 'token_count': 992} |
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
import 'src/riverpod_generator.dart';
/// Builds generators for `build_runner` to run
Builder riverpodBuilder(BuilderOptions options) {
return SharedPartBuilder(
[RiverpodGenerator(options.config)],
'riverpod',
);
}
| riverpod/packages/riverpod_generator/lib/builder.dart/0 | {'file_path': 'riverpod/packages/riverpod_generator/lib/builder.dart', 'repo_id': 'riverpod', 'token_count': 103} |
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:test/test.dart';
import 'integration/dependencies.dart';
void main() {
test('Supports specifying dependencies', () {
expect(depProvider.dependencies, null);
expect(dep2Provider.dependencies, null);
expect(familyProvider.dependencies, null);
expect(family2Provider.dependencies, null);
expect(
providerProvider.dependencies,
[depProvider, familyProvider, dep2Provider, family2Provider],
);
expect(
provider2Provider.dependencies,
[depProvider, familyProvider, dep2Provider, family2Provider],
);
expect(
provider3Provider.dependencies,
[depProvider, familyProvider, dep2Provider, family2Provider],
);
expect(
provider4Provider.dependencies,
[depProvider, familyProvider, dep2Provider, family2Provider],
);
expect(transitiveDependenciesProvider.dependencies, [providerProvider]);
expect(
emptyDependenciesFunctionalProvider.dependencies,
same(const <ProviderOrFamily>[]),
);
expect(
emptyDependenciesClassBasedProvider.dependencies,
same(const <ProviderOrFamily>[]),
);
});
test('Generates transitive dependencies', () {
expect(depProvider.allTransitiveDependencies, null);
expect(dep2Provider.allTransitiveDependencies, null);
expect(familyProvider.allTransitiveDependencies, null);
expect(family2Provider.allTransitiveDependencies, null);
expect(
providerProvider.allTransitiveDependencies,
[depProvider, familyProvider, dep2Provider, family2Provider],
);
expect(
provider2Provider.allTransitiveDependencies,
[depProvider, familyProvider, dep2Provider, family2Provider],
);
expect(
provider3Provider.allTransitiveDependencies,
[depProvider, familyProvider, dep2Provider, family2Provider],
);
expect(
provider4Provider.allTransitiveDependencies,
[depProvider, familyProvider, dep2Provider, family2Provider],
);
expect(
transitiveDependenciesProvider.allTransitiveDependencies,
[
providerProvider,
depProvider,
familyProvider,
dep2Provider,
family2Provider,
],
);
expect(
emptyDependenciesFunctionalProvider.allTransitiveDependencies,
same(const <ProviderOrFamily>{}),
);
expect(
emptyDependenciesClassBasedProvider.allTransitiveDependencies,
same(const <ProviderOrFamily>{}),
);
});
test('Caches dependencies', () {
expect(
providerProvider.dependencies,
same(providerProvider.dependencies),
);
expect(
provider2Provider.dependencies,
same(provider2Provider.dependencies),
);
expect(
provider3Provider.dependencies,
same(provider3Provider.dependencies),
);
expect(
provider4Provider.dependencies,
same(provider4Provider.dependencies),
);
expect(
transitiveDependenciesProvider.dependencies,
same(transitiveDependenciesProvider.dependencies),
);
expect(
smallTransitiveDependencyCountProvider.dependencies,
same(smallTransitiveDependencyCountProvider.dependencies),
);
expect(
emptyDependenciesFunctionalProvider.dependencies,
same(emptyDependenciesFunctionalProvider.dependencies),
);
expect(
emptyDependenciesClassBasedProvider.dependencies,
same(emptyDependenciesClassBasedProvider.dependencies),
);
expect(
provider3Provider.allTransitiveDependencies,
same(provider3Provider.allTransitiveDependencies),
);
expect(
provider4Provider.allTransitiveDependencies,
same(provider4Provider.allTransitiveDependencies),
);
expect(
transitiveDependenciesProvider.allTransitiveDependencies,
same(transitiveDependenciesProvider.allTransitiveDependencies),
);
expect(
smallTransitiveDependencyCountProvider.allTransitiveDependencies,
same(smallTransitiveDependencyCountProvider.allTransitiveDependencies),
);
});
}
| riverpod/packages/riverpod_generator/test/dependencies_test.dart/0 | {'file_path': 'riverpod/packages/riverpod_generator/test/dependencies_test.dart', 'repo_id': 'riverpod', 'token_count': 1462} |
name: riverpod_graph_golden_generated
description: A new Flutter project.
publish_to: "none"
environment:
sdk: ">=3.0.0 <4.0.0"
flutter: ">=1.17.0"
dependencies:
cupertino_icons: ^1.0.2
flutter:
sdk: flutter
flutter_riverpod:
path: ../../../../../../packages/flutter_riverpod
riverpod:
path: ../../../../../../packages/riverpod
riverpod_annotation:
path: ../../../../../../packages/riverpod_annotation
dev_dependencies:
build_runner: ^2.2.0
flutter_test:
sdk: flutter
riverpod_generator:
path: ../../../../../../packages/riverpod_generator
flutter:
uses-material-design: true
| riverpod/packages/riverpod_graph/test/integration/generated/golden/pubspec.yaml/0 | {'file_path': 'riverpod/packages/riverpod_graph/test/integration/generated/golden/pubspec.yaml', 'repo_id': 'riverpod', 'token_count': 257} |
import 'package:analyzer/error/listener.dart';
import 'package:custom_lint_builder/custom_lint_builder.dart';
class AvoidExposingWidgetRef extends DartLintRule {
const AvoidExposingWidgetRef() : super(code: _code);
static const _code = LintCode(
name: 'avoid_exposing_widget_ref',
problemMessage:
'The "ref" of a widget should not be accessible outside of that widget.',
);
@override
void run(
CustomLintResolver resolver,
ErrorReporter reporter,
CustomLintContext context,
) {
// TODO: implement run
}
}
| riverpod/packages/riverpod_lint/lib/src/legacy_backup/avoid_exposing_widget_ref.dart/0 | {'file_path': 'riverpod/packages/riverpod_lint/lib/src/legacy_backup/avoid_exposing_widget_ref.dart', 'repo_id': 'riverpod', 'token_count': 192} |
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';
String _generatedClassName(ProviderDeclaration declaration) {
return '_\$${declaration.name.lexeme.public}';
}
class NotifierExtends extends RiverpodLintRule {
const NotifierExtends() : super(code: _code);
static const _code = LintCode(
name: 'notifier_extends',
problemMessage: r'Classes annotated by @riverpod must extend _$ClassName',
);
@override
void run(
CustomLintResolver resolver,
ErrorReporter reporter,
CustomLintContext context,
) {
riverpodRegistry(context).addClassBasedProviderDeclaration((declaration) {
final extendsClause = declaration.node.extendsClause;
if (extendsClause == null) {
// No ref parameter, underlining the function name
reporter.reportErrorForToken(_code, declaration.name);
return;
}
final expectedClassName = _generatedClassName(declaration);
if (extendsClause.superclass.name2.lexeme != expectedClassName) {
// No type specified. Underlining the ref name
reporter.reportErrorForNode(_code, extendsClause.superclass);
return;
}
});
}
@override
List<Fix> getFixes() => [NotifierExtendsFix()];
}
class NotifierExtendsFix extends RiverpodFix {
@override
void run(
CustomLintResolver resolver,
ChangeReporter reporter,
CustomLintContext context,
AnalysisError analysisError,
List<AnalysisError> others,
) {
riverpodRegistry(context).addClassBasedProviderDeclaration((declaration) {
// This provider is not the one that triggered the error
if (!analysisError.sourceRange.intersects(declaration.node.sourceRange)) {
return;
}
final expectedClassName = _generatedClassName(declaration);
final extendsClause = declaration.node.extendsClause;
final changeBuilder = reporter.createChangeBuilder(
message: 'Extend $expectedClassName',
priority: 90,
);
changeBuilder.addDartFileEdit((builder) {
if (extendsClause == null) {
// No "extends" clause
builder.addSimpleInsertion(
declaration.name.end,
' extends $expectedClassName',
);
return;
}
// There is an "extends" clause but the extended type is wrong
builder.addSimpleReplacement(
extendsClause.superclass.sourceRange,
expectedClassName,
);
});
});
}
}
| riverpod/packages/riverpod_lint/lib/src/lints/notifier_extends.dart/0 | {'file_path': 'riverpod/packages/riverpod_lint/lib/src/lints/notifier_extends.dart', 'repo_id': 'riverpod', 'token_count': 997} |
include: ../analysis_options.yaml
analyzer:
exclude:
- build/**
errors:
todo: ignore
linter:
rules:
require_trailing_commas: false
| riverpod/website/analysis_options.yaml/0 | {'file_path': 'riverpod/website/analysis_options.yaml', 'repo_id': 'riverpod', 'token_count': 60} |
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'codegen_keep_alive.g.dart';
/* SNIPPET START */
// We can specify "keepAlive" in the annotation to disable
// the automatic state destruction
@Riverpod(keepAlive: true)
int example(ExampleRef ref) {
return 0;
}
| riverpod/website/docs/essentials/auto_dispose/codegen_keep_alive.dart/0 | {'file_path': 'riverpod/website/docs/essentials/auto_dispose/codegen_keep_alive.dart', 'repo_id': 'riverpod', 'token_count': 93} |
// ignore_for_file: unnecessary_this, avoid_print
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../first_request/raw/activity.dart';
FutureOr<Activity> fetchActivity(String activityType) =>
throw UnimplementedError();
/* SNIPPET START */
// A "functional" provider
final activityProvider = FutureProvider.autoDispose
// We use the ".family" modifier.
// The "String" generic type corresponds to the argument type.
// Our provider now receives an extra argument on top of "ref": the activity type.
.family<Activity, String>((ref, activityType) async {
// TODO: perform a network request to fetch an activity using "activityType"
return fetchActivity(activityType);
});
// A "notifier" provider
final activityProvider2 = AsyncNotifierProvider.autoDispose
// Again, we use the ".family" modifier, and specify the argument as type "String".
.family<ActivityNotifier, Activity, String>(
ActivityNotifier.new,
);
// When using ".family" with notifiers, we need to change the notifier subclass:
// AsyncNotifier -> FamilyAsyncNotifier
// AutoDisposeAsyncNotifier -> AutoDisposeFamilyAsyncNotifier
class ActivityNotifier
extends AutoDisposeFamilyAsyncNotifier<Activity, String> {
/// Family arguments are passed to the build method and accessible with this.arg
@override
Future<Activity> build(String activityType) async {
// Arguments are also available with "this.arg"
print(this.arg);
// TODO: perform a network request to fetch an activity
return fetchActivity(activityType);
}
}
| riverpod/website/docs/essentials/passing_args/raw/family.dart/0 | {'file_path': 'riverpod/website/docs/essentials/passing_args/raw/family.dart', 'repo_id': 'riverpod', 'token_count': 452} |
// 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 => [/* ... */];
/* SNIPPET START */
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()),
);
// Once the post request is done, we can mark the local cache as dirty.
// This will cause "build" on our notifier to asynchronously be called again,
// and will notify listeners when doing so.
ref.invalidateSelf();
// (Optional) We can then wait for the new state to be computed.
// This ensures "addTodo" does not complete until the new state is available.
await future;
}
/* SNIPPET END */
}
| riverpod/website/docs/essentials/side_effects/raw/invalidate_self_add_todo.dart/0 | {'file_path': 'riverpod/website/docs/essentials/side_effects/raw/invalidate_self_add_todo.dart', 'repo_id': 'riverpod', 'token_count': 414} |
import 'package:riverpod/riverpod.dart';
import 'package:test/test.dart';
/// A testing utility which creates a [ProviderContainer] and automatically
/// disposes it at the end of the test.
ProviderContainer createContainer({
ProviderContainer? parent,
List<Override> overrides = const [],
List<ProviderObserver>? observers,
}) {
// Create a ProviderContainer, and optionally allow specifying parameters.
final container = ProviderContainer(
parent: parent,
overrides: overrides,
observers: observers,
);
// When the test ends, dispose the container.
addTearDown(container.dispose);
return container;
}
| riverpod/website/docs/essentials/testing/create_container.dart/0 | {'file_path': 'riverpod/website/docs/essentials/testing/create_container.dart', 'repo_id': 'riverpod', 'token_count': 174} |
// ignore_for_file: omit_local_variable_types
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
/* SNIPPET START */
final myProvider = ChangeNotifierProvider<ValueNotifier<int>>((ref) {
// Will listen to and dispose of the ValueNotifier.
// Widgets can then "ref.watch" this provider to listen to updates.
return ValueNotifier(0);
});
| riverpod/website/docs/essentials/websockets_sync/change_notifier_provider.dart/0 | {'file_path': 'riverpod/website/docs/essentials/websockets_sync/change_notifier_provider.dart', 'repo_id': 'riverpod', 'token_count': 122} |
// 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) {
// Benutze "read" um die Updates eines Providers zu ignorieren
final counter = ref.read(counterProvider.notifier);
return ElevatedButton(
onPressed: () => counter.state++,
child: const Text('button'),
);
}
| riverpod/website/i18n/de/docusaurus-plugin-content-docs/current/concepts/reading_read_build.dart/0 | {'file_path': 'riverpod/website/i18n/de/docusaurus-plugin-content-docs/current/concepts/reading_read_build.dart', 'repo_id': 'riverpod', 'token_count': 160} |
// ignore_for_file: avoid_print
/* SNIPPET START */
import 'package:riverpod/riverpod.dart';
// Wir erstellen einen "Provider", der einen Wert speichern wird (hier "Hello world").
// Durch die Nutzung eines Provider, ist es uns erlaubt den gelieferten Wert
// zu mocken oder zu überschreiben
final helloWorldProvider = Provider((_) => 'Hello world');
void main() {
// Das ist das Objekt, in dem der Zustand unserer Provider gespeichert wird.
final container = ProviderContainer();
// Dank des "container" können wir unseren provider lesen.
final value = container.read(helloWorldProvider);
print(value); // Hello world
}
| riverpod/website/i18n/de/docusaurus-plugin-content-docs/current/getting_started_hello_world_dart.dart/0 | {'file_path': 'riverpod/website/i18n/de/docusaurus-plugin-content-docs/current/getting_started_hello_world_dart.dart', 'repo_id': 'riverpod', 'token_count': 212} |
// 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) {
// Widget neu aufbauen, wenn sich die ToDo-Liste ändert
List<Todo> todos = ref.watch(todosProvider);
// Lassen Sie uns die ToDos in einer scrollbaren Listenansicht darstellen
return ListView(
children: [
for (final todo in todos)
CheckboxListTile(
value: todo.completed,
// Wenn Sie auf das ToDo tippen, änder es seinen Erledigungsstatus
onChanged: (value) =>
ref.read(todosProvider.notifier).toggle(todo.id),
title: Text(todo.description),
),
],
);
}
}
| riverpod/website/i18n/de/docusaurus-plugin-content-docs/current/providers/state_notifier_provider/todos_consumer.dart/0 | {'file_path': 'riverpod/website/i18n/de/docusaurus-plugin-content-docs/current/providers/state_notifier_provider/todos_consumer.dart', 'repo_id': 'riverpod', 'token_count': 406} |
// ignore_for_file: omit_local_variable_types
import 'package:flutter_riverpod/flutter_riverpod.dart';
enum FilterType {
none,
completed,
}
abstract class Todo {
bool get isCompleted;
}
class TodoList extends StateNotifier<List<Todo>> {
TodoList(): super([]);
}
/* SNIPPET START */
final filterTypeProvider = StateProvider<FilterType>((ref) => FilterType.none);
final todosProvider = StateNotifierProvider<TodoList, List<Todo>>((ref) => TodoList());
final filteredTodoListProvider = Provider((ref) {
// récupère à la fois le filtre et la liste des todos
final FilterType filter = ref.watch(filterTypeProvider);
final List<Todo> todos = ref.watch(todosProvider);
switch (filter) {
case FilterType.completed:
// renvoie la liste complétée des todos
return todos.where((todo) => todo.isCompleted).toList();
case FilterType.none:
// renvoie la liste non filtrée des todos
return todos;
}
}); | riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/concepts/reading_watch.dart/0 | {'file_path': 'riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/concepts/reading_watch.dart', 'repo_id': 'riverpod', 'token_count': 331} |
import 'package:hooks_riverpod/hooks_riverpod.dart';
class Todo {}
/* SNIPPET START */
class Repository {
Future<List<Todo>> fetchTodos() async => [];
}
// Nous exposons notre instance de référentiel dans un provider
final repositoryProvider = Provider((ref) => Repository());
/// La liste des todos. Ici, nous les récupérons simplement sur le serveur en utilisant
/// [Repository] et ne faisons rien d'autre.
final todoListProvider = FutureProvider((ref) async {
// Obtenir une l'instance Repository
final repository = ref.watch(repositoryProvider);
// Récupérer les todos et les exposer à l'interface utilisateur.
return repository.fetchTodos();
});
| riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/cookbooks/testing_repository.dart/0 | {'file_path': 'riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/cookbooks/testing_repository.dart', 'repo_id': 'riverpod', 'token_count': 216} |
// 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);
class PreviousButton extends ConsumerWidget {
const PreviousButton({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
// si ce n'est pas sur la première page, le bouton précédent est actif
final canGoToPreviousPage = ref.watch(pageIndexProvider) != 0;
void goToPreviousPage() {
ref.read(pageIndexProvider.notifier).update((state) => state - 1);
}
return ElevatedButton(
onPressed: canGoToPreviousPage ? goToPreviousPage : null,
child: const Text('previous'),
);
}
} | riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/providers/provider/unoptimized_previous_button.dart/0 | {'file_path': 'riverpod/website/i18n/fr/docusaurus-plugin-content-docs/current/providers/provider/unoptimized_previous_button.dart', 'repo_id': 'riverpod', 'token_count': 256} |
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'auto_dispose.g.dart';
/* SNIPPET START */
// Provider autoDispose (keepAlive è false di default)
@riverpod
String example1(Example1Ref ref) => 'foo';
// Provider non autoDispose
@Riverpod(keepAlive: true)
String example2(Example2Ref ref) => 'foo';
| riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/concepts/about_codegen/provider_type/auto_dispose.dart/0 | {'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/concepts/about_codegen/provider_type/auto_dispose.dart', 'repo_id': 'riverpod', 'token_count': 109} |
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'sync_class.g.dart';
/* SNIPPET START */
@riverpod
class Example extends _$Example {
@override
String build() {
return 'foo';
}
// Aggiungere i metodi per mutare lo stato
}
| riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/concepts/about_codegen/provider_type/sync_class.dart/0 | {'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/concepts/about_codegen/provider_type/sync_class.dart', 'repo_id': 'riverpod', 'token_count': 94} |
// ignore_for_file: unused_local_variable
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'codegen.g.dart';
final otherProvider = Provider<int>((ref) => 0);
/* SNIPPET START */
@riverpod
class MyNotifier extends _$MyNotifier {
@override
int build() {
// Non buono! Non usare "read" qui dato che non è reattivo
ref.read(otherProvider);
return 0;
}
void increment() {
ref.read(otherProvider); // Usare "read" qui va bene
}
}
| riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/combining_requests/read_example/codegen.dart/0 | {'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/combining_requests/read_example/codegen.dart', 'repo_id': 'riverpod', 'token_count': 174} |
// ignore_for_file: unused_local_variable, use_key_in_widget_constructors
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'codegen.g.dart';
/* SNIPPET START */
// Un provider inizializzato anticipatamente.
@riverpod
Future<String> example(ExampleRef ref) async => 'Hello world';
class MyConsumer extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final result = ref.watch(exampleProvider);
// Se il provider è stato correttamente inizializzato anticipatamente, allora puoi
// direttamente leggere il dato con "requireValue".
return Text(result.requireValue);
}
}
/* SNIPPET END */
| riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/eager_initialization/require_value/codegen.dart/0 | {'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/eager_initialization/require_value/codegen.dart', 'repo_id': 'riverpod', 'token_count': 252} |
// 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';
final activityProvider = Provider.family<Object, Object>((ref, id) {
throw UnimplementedError();
});
class Example extends ConsumerWidget {
const Example({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
/* SNIPPET START */
// Potremmo aggiornare activityProvider per accettare direttamente una lista di stringhe.
// Poi essere tentati di creare quella lista direttamente nella chiamata di watch.
ref.watch(activityProvider(['recreational', 'cooking']));
/* SNIPPET END */
return Container();
}
}
| riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/passing_args/raw/consumer_list_family.dart/0 | {'file_path': 'riverpod/website/i18n/it/docusaurus-plugin-content-docs/current/essentials/passing_args/raw/consumer_list_family.dart', 'repo_id': 'riverpod', 'token_count': 240} |
// 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 HookConsumerWidget {
const HomeView({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
// build メソッド内でフックを使用できます。
final state = useState(0);
// `ref` オブジェクトを使ってプロバイダを監視することもできます。
final counter = ref.watch(counterProvider);
return Text('$counter');
}
} | riverpod/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/reading_consumer_hook_widget.dart/0 | {'file_path': 'riverpod/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/reading_consumer_hook_widget.dart', 'repo_id': 'riverpod', 'token_count': 229} |
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class Repository {
Future<List<Todo>> fetchTodos() async => [];
}
class Todo {
Todo({
required this.id,
required this.label,
required this.completed,
});
final String id;
final String label;
final bool completed;
}
// Repository インスタンスを公開するプロバイダ
final repositoryProvider = Provider((ref) => Repository());
/// Todo リストを公開するプロバイダ
/// [Repository] を使用して値をサーバから取得
final todoListProvider = FutureProvider((ref) async {
// Repository インスタンスを取得する
final repository = ref.read(repositoryProvider);
// Todo リストを取得して、プロバイダを監視する UI 側に値を公開する
return repository.fetchTodos();
});
/// あらかじめ定義した Todo リストを返す Repository のフェイク実装
class FakeRepository implements Repository {
@override
Future<List<Todo>> fetchTodos() async {
return [
Todo(id: '42', label: 'Hello world', completed: false),
];
}
}
class TodoItem extends StatelessWidget {
const TodoItem({super.key, required this.todo});
final Todo todo;
@override
Widget build(BuildContext context) {
return Text(todo.label);
}
}
void main() {
testWidgets('override repositoryProvider', (tester) async {
await tester.pumpWidget(
ProviderScope(
overrides: [
repositoryProvider.overrideWithValue(FakeRepository())
],
// todoListProvider の値を監視して Todo リストを表示するアプリ
// 以下を抽出して MyApp ウィジェットとしても可
child: MaterialApp(
home: Scaffold(
body: Consumer(builder: (context, ref, _) {
final todos = ref.watch(todoListProvider);
// Todo リストのステートが loading か error の場合
if (todos.asData == null) {
return const CircularProgressIndicator();
}
return ListView(
children: [
for (final todo in todos.asData!.value) TodoItem(todo: todo)
],
);
}),
),
),
),
);
// 最初のフレームのステートが loading になっているか確認
expect(find.byType(CircularProgressIndicator), findsOneWidget);
// 再描画。このあたりで TodoListProvider は 値の取得が終わっているはず
await tester.pump();
// loading 以外のステートになっているか確認
expect(find.byType(CircularProgressIndicator), findsNothing);
// FakeRepository が公開した値から TodoItem が一つ描画されているか確認
expect(tester.widgetList(find.byType(TodoItem)), [
isA<TodoItem>()
.having((s) => s.todo.id, 'todo.id', '42')
.having((s) => s.todo.label, 'todo.label', 'Hello world')
.having((s) => s.todo.completed, 'todo.completed', false),
]);
});
} | riverpod/website/i18n/ja/docusaurus-plugin-content-docs/current/cookbooks/testing_full.dart/0 | {'file_path': 'riverpod/website/i18n/ja/docusaurus-plugin-content-docs/current/cookbooks/testing_full.dart', 'repo_id': 'riverpod', 'token_count': 1356} |
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'todo.dart';
/* SNIPPET START */
final completedTodosProvider = Provider<List<Todo>>((ref) {
// todosProvider から Todo リストの内容をすべて取得
final todos = ref.watch(todosProvider);
// 完了タスクのみをリストにして値として返す
return todos.where((todo) => todo.isCompleted).toList();
});
| riverpod/website/i18n/ja/docusaurus-plugin-content-docs/current/providers/provider/completed_todos.dart/0 | {'file_path': 'riverpod/website/i18n/ja/docusaurus-plugin-content-docs/current/providers/provider/completed_todos.dart', 'repo_id': 'riverpod', 'token_count': 153} |
// ignore_for_file: avoid_print, use_key_in_widget_constructors
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'activity/codegen.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(
onRefresh: () => ref.refresh(activityProvider.future),
child: ListView(
children: [
switch (activity) {
// 일부 데이터를 사용할 수 있는 경우 해당 데이터를 표시합니다.
// 새로 고침 중에도 데이터를 계속 사용할 수 있습니다.
AsyncValue<Activity>(:final valueOrNull?) => Text(valueOrNull.activity),
// 오류를 사용할 수 있으므로 렌더링합니다.
AsyncValue(:final error?) => Text('Error: $error'),
// 데이터/오류가 없으므로 로딩 상태입니다.
_ => const CircularProgressIndicator(),
},
],
),
),
);
}
}
| riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/case_studies/pull_to_refresh/display_activity4.dart/0 | {'file_path': 'riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/case_studies/pull_to_refresh/display_activity4.dart', 'repo_id': 'riverpod', 'token_count': 669} |
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'codegen.g.dart';
/* SNIPPET START */
// 이른 초기화된 provider.
@riverpod
Future<String> example(ExampleRef ref) async => 'Hello world';
/* SNIPPET END */
| riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/testing/provider_to_mock/codegen.dart/0 | {'file_path': 'riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/essentials/testing/provider_to_mock/codegen.dart', 'repo_id': 'riverpod', 'token_count': 90} |
// ignore_for_file: use_key_in_widget_constructors, omit_local_variable_types
/* SNIPPET START */
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'main.g.dart';
// 값을 저장할 “provider"를 생성합니다(여기서는 "Hello world").
// 프로바이더를 사용하면, 노출된 값을 모의(Mock)하거나 재정의(Override)할 수 있습니다.
@riverpod
String helloWorld(HelloWorldRef ref) {
return 'Hello world';
}
void main() {
runApp(
// 위젯이 프로바이더를 읽을 수 있도록 하려면,
// 전체 애플리케이션을 "ProviderScope" 위젯으로 감싸야 합니다.
// 여기에 프로바이더의 상태가 저장됩니다.
ProviderScope(
child: MyApp(),
),
);
}
// HookWidget 대신 Riverpod에서 제공되는 HookConsumerWidget을 확장합니다.
class MyApp extends HookConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
// HookConsumerWidget 내부에서 Hook을 사용할 수 있습니다.
final counter = useState(0);
final String value = ref.watch(helloWorldProvider);
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Example')),
body: Center(
child: Text('$value ${counter.value}'),
),
),
);
}
}
| riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/introduction/getting_started/hello_world/hooks_codegen/main.dart/0 | {'file_path': 'riverpod/website/i18n/ko/docusaurus-plugin-content-docs/current/introduction/getting_started/hello_world/hooks_codegen/main.dart', 'repo_id': 'riverpod', 'token_count': 756} |
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
/* SNIPPET START */
class Todo {
Todo({
required this.id,
required this.description,
required this.completed,
});
String id;
String description;
bool completed;
}
class TodosNotifier extends ChangeNotifier {
final todos = <Todo>[];
// Добавление задач
void addTodo(Todo todo) {
todos.add(todo);
notifyListeners();
}
// Удаление задач
void removeTodo(String todoId) {
todos.remove(todos.firstWhere((element) => element.id == todoId));
notifyListeners();
}
// Задача выполнена/не выполнена
void toggle(String todoId) {
for (final todo in todos) {
if (todo.id == todoId) {
todo.completed = !todo.completed;
notifyListeners();
}
}
}
}
// Используем ChangeNotifierProvider для взаимодействия с TodosNotifier
final todosProvider = ChangeNotifierProvider<TodosNotifier>((ref) {
return TodosNotifier();
});
| riverpod/website/i18n/ru/docusaurus-plugin-content-docs/current/providers/change_notifier_provider/todos.dart/0 | {'file_path': 'riverpod/website/i18n/ru/docusaurus-plugin-content-docs/current/providers/change_notifier_provider/todos.dart', 'repo_id': 'riverpod', 'token_count': 460} |
// ignore_for_file: use_key_in_widget_constructors, unused_local_variable
import 'package:flutter/widgets.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../providers/creating_a_provider/codegen.dart';
class MyValue {}
/* SNIPPET START */
class Example extends StatelessWidget {
@override
Widget build(BuildContext context) {
// 我们可以使用这两个软件包提供的构建器
return Consumer(
builder: (context, ref, child) {
return HookBuilder(builder: (context) {
final counter = useState(0);
final value = ref.watch(myProvider);
return Text('Hello $counter $value');
});
},
);
}
}
| riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/concepts/about_hooks/hook_and_consumer.dart/0 | {'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/concepts/about_hooks/hook_and_consumer.dart', 'repo_id': 'riverpod', 'token_count': 310} |
// ignore_for_file: unused_local_variable
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'codegen.g.dart';
late WidgetRef ref;
/* SNIPPET START */
@riverpod
String label(LabelRef ref, String userName) {
return 'Hello $userName';
}
// ...
void onTap() {
// 使该提供者程序所有可能的参数组合无效。
ref.invalidate(labelProvider);
// 仅使特定组合无效
ref.invalidate(labelProvider('John'));
}
/* SNIPPET END */
| riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/auto_dispose/invalidate_family_example/codegen.dart/0 | {'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/auto_dispose/invalidate_family_example/codegen.dart', 'repo_id': 'riverpod', 'token_count': 217} |
// ignore_for_file: omit_local_variable_types, prefer_const_constructors, unused_local_variable
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'activity.dart';
import 'provider.dart';
/* SNIPPET START */ /// 我们将“ConsumerWidget”替代“StatelessWidget”进行子类化。
/// 这相当于使用“StatelessWidget”并返回“Consumer”小组件。
class Home extends ConsumerWidget {
const Home({super.key});
@override
// 请注意“build”现在如何接收一个额外的参数:“ref”
Widget build(BuildContext context, WidgetRef ref) {
// 我们可以像使用“Consumer”一样,在小部件中使用“ref.watch”
final AsyncValue<Activity> activity = ref.watch(activityProvider);
// 渲染逻辑保持不变
return Center(/* ... */);
}
}
| riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/first_request/raw/consumer_widget.dart/0 | {'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/first_request/raw/consumer_widget.dart', 'repo_id': 'riverpod', 'token_count': 361} |
// ignore_for_file: omit_local_variable_types, unused_local_variable, prefer_final_locals
import 'dart:convert';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;
import '../../first_request/raw/activity.dart';
/* SNIPPET START */
// 我们定义一条记录,表示我们想要传递给提供者程序的参数。
// 创建 typedef 是可选的,但可以使代码更具可读性。
typedef ActivityParameters = ({String type, int maxPrice});
final activityProvider = FutureProvider.autoDispose
// 我们现在使用新定义的记录作为参数类型。
.family<Activity, ActivityParameters>((ref, arguments) async {
final response = await http.get(
Uri(
scheme: 'https',
host: 'boredapi.com',
path: '/api/activity',
queryParameters: {
// 最后,我们可以使用参数来更新请求的查询参数。
'type': arguments.type,
'price': arguments.maxPrice,
},
),
);
final json = jsonDecode(response.body) as Map<String, dynamic>;
return Activity.fromJson(json);
});
| riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/passing_args/raw/tuple_family.dart/0 | {'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/passing_args/raw/tuple_family.dart', 'repo_id': 'riverpod', 'token_count': 492} |
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'rest_add_todo.dart';
import 'todo_list_notifier.dart' show Todo;
void main() {
runApp(
const ProviderScope(child: MyApp()),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: Example());
}
}
/* SNIPPET START */
class Example extends ConsumerStatefulWidget {
const Example({super.key});
@override
ConsumerState<ConsumerStatefulWidget> createState() => _ExampleState();
}
class _ExampleState extends ConsumerState<Example> {
// 待处理的 addTodo 操作。如果没有待处理的,则为 null。
Future<void>? _pendingAddTodo;
@override
Widget build(BuildContext context) {
return FutureBuilder(
// 我们监听待处理的操作,以相应地更新 UI。
future: _pendingAddTodo,
builder: (context, snapshot) {
// 计算是否存在错误状态。
// 检查 connectionState 用于在重试操作时进行处理。
final isErrored = snapshot.hasError &&
snapshot.connectionState != ConnectionState.waiting;
return Row(
children: [
ElevatedButton(
style: ButtonStyle(
// 如果出现错误,我们会将该按钮显示为红色
backgroundColor: MaterialStateProperty.all(
isErrored ? Colors.red : null,
),
),
onPressed: () {
// 我们将 addTodo 返回的 future 保存在变量中
final future = ref
.read(todoListProvider.notifier)
.addTodo(Todo(description: 'This is a new todo'));
// 我们将这个 future 存储在本地的状态中
setState(() {
_pendingAddTodo = future;
});
},
child: const Text('Add todo'),
),
// 操作正在等待,让我们显示一个进度指示器
if (snapshot.connectionState == ConnectionState.waiting) ...[
const SizedBox(width: 8),
const CircularProgressIndicator(),
]
],
);
},
);
}
}
/* SNIPPET END */ | riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/side_effects/raw/render_add_todo.dart/0 | {'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/side_effects/raw/render_add_todo.dart', 'repo_id': 'riverpod', 'token_count': 1197} |
// ignore_for_file: unused_local_variable
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'create_container.dart';
import 'full_widget_test.dart';
import 'provider_to_mock/raw.dart';
void main() {
testWidgets('Some description', (tester) async {
await tester.pumpWidget(
const ProviderScope(child: YourWidgetYouWantToTest()),
);
/* SNIPPET START */
// 在单元测试中,重用我们之前的 "createContainer "工具。
final container = createContainer(
// 我们可以指定要模拟的提供者程序列表:
overrides: [
// 在本例中,我们模拟的是 "exampleProvider"。
exampleProvider.overrideWith((ref) {
// 该函数是典型的提供者程序初始化函数。
// 通常在此调用 "ref.watch "并返回初始状态。
// 让我们用自定义值替换默认的 "Hello world"。
// 然后,与 `exampleProvider` 交互时将返回此值。
return 'Hello from tests';
}),
],
);
// 我们还可以使用 ProviderScope 在 widget 测试中做同样的事情:
await tester.pumpWidget(
ProviderScope(
// ProviderScopes 具有完全相同的 "overrides" 参数
overrides: [
// 和之前一样
exampleProvider.overrideWith((ref) => 'Hello from tests'),
],
child: const YourWidgetYouWantToTest(),
),
);
/* SNIPPET END */
});
}
| riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/testing/mock_provider.dart/0 | {'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/testing/mock_provider.dart', 'repo_id': 'riverpod', 'token_count': 763} |
// ignore_for_file: omit_local_variable_types, prefer_final_locals, use_key_in_widget_constructors
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'raw_usage.g.dart';
/* SNIPPET START */
@riverpod
Raw<Stream<int>> rawStream(RawStreamRef ref) {
// “Raw”是一个 typedef。
// 无需包装返回值的“原始”构造函数中的值。
return const Stream<int>.empty();
}
class Consumer extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
// 该值不再转换为 AsyncValue,
// 并且按原样返回创建的流。
Stream<int> stream = ref.watch(rawStreamProvider);
return StreamBuilder<int>(
stream: stream,
builder: (context, snapshot) {
return Text('${snapshot.data}');
},
);
}
}
| riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/websockets_sync/raw_usage.dart/0 | {'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/essentials/websockets_sync/raw_usage.dart', 'repo_id': 'riverpod', 'token_count': 373} |
// ignore_for_file: avoid_print
/* SNIPPET START */
import 'package:riverpod/riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'main.g.dart';
// 我们创建了一个 "provider",它可以存储一个值(这里是 "Hello world")。
// 通过使用提供者程序,这可以允许我们模拟或者覆盖一个暴露的值。
@riverpod
String helloWorld(HelloWorldRef ref) {
return 'Hello world';
}
void main() {
// 这个对象是我们的提供者程序的状态将被存储的地方。
final container = ProviderContainer();
// 多亏有了 "container",我们可以读取我们的提供者程序。
final value = container.read(helloWorldProvider);
print(value); // Hello world
}
| riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/introduction/getting_started/dart_hello_world/main.dart/0 | {'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/introduction/getting_started/dart_hello_world/main.dart', 'repo_id': 'riverpod', 'token_count': 348} |
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../utils.dart';
part 'old_lifecycles.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 {
await ref.read(repositoryProvider).update(state + 1);
// `mounted` 已不复存在!
state++; // 这可能会抛出。
}
}
| riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/migration/from_state_notifier/old_lifecycles/old_lifecycles.dart/0 | {'file_path': 'riverpod/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/migration/from_state_notifier/old_lifecycles/old_lifecycles.dart', 'repo_id': 'riverpod', 'token_count': 341} |
import 'package:flame/components/component.dart';
import 'package:flame/components/mixins/has_game_ref.dart';
import 'package:flame/time.dart';
import 'dart:ui';
import 'dart:math';
import '../game.dart';
import './enemy_component.dart';
class EnemyCreator extends Component with HasGameRef<SpaceShooterGame>{
Timer enemyCreator;
Random random = Random();
EnemyCreator() {
enemyCreator = Timer(1.0, repeat: true, callback: () {
gameRef.add(EnemyComponent((gameRef.size.width - 25) * random.nextDouble(), 0));
});
enemyCreator.start();
}
@override
void update(double dt) {
enemyCreator.update(dt);
}
@override
void render(Canvas canvas) { }
}
| rogue_shooter/game/lib/components/enemy_creator.dart/0 | {'file_path': 'rogue_shooter/game/lib/components/enemy_creator.dart', 'repo_id': 'rogue_shooter', 'token_count': 250} |
include: package:pedantic/analysis_options.1.9.0.yaml
analyzer:
strong-mode:
implicit-casts: false
implicit-dynamic: false
exclude:
- 'example/**'
linter:
rules:
- public_member_api_docs
| rxdart/analysis_options.yaml/0 | {'file_path': 'rxdart/analysis_options.yaml', 'repo_id': 'rxdart', 'token_count': 84} |
import 'package:flutter/material.dart';
class SearchIntro extends StatelessWidget {
const SearchIntro({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
alignment: FractionalOffset.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.info, color: Colors.green[200], size: 80.0),
Container(
padding: EdgeInsets.only(top: 16.0),
child: Text(
"Enter a search term to begin",
style: TextStyle(
color: Colors.green[100],
),
),
)
],
),
);
}
}
| rxdart/example/flutter/github_search/lib/search_intro_widget.dart/0 | {'file_path': 'rxdart/example/flutter/github_search/lib/search_intro_widget.dart', 'repo_id': 'rxdart', 'token_count': 339} |
import 'dart:async';
/// Convert a [Stream] that emits [Stream]s (aka a 'Higher Order Stream') into a
/// single [Stream] that emits the items emitted by the most-recently-emitted of
/// those [Stream]s.
///
/// This stream will unsubscribe from the previously-emitted Stream when a new
/// Stream is emitted from the source Stream.
///
/// ### Example
///
/// ```dart
/// final switchLatestStream = SwitchLatestStream<String>(
/// Stream.fromIterable(<Stream<String>>[
/// Rx.timer('A', Duration(seconds: 2)),
/// Rx.timer('B', Duration(seconds: 1)),
/// Stream.value('C'),
/// ]),
/// );
///
/// // Since the first two Streams do not emit data for 1-2 seconds, and the 3rd
/// // Stream will be emitted before that time, only data from the 3rd Stream
/// // will be emitted to the listener.
/// switchLatestStream.listen(print); // prints 'C'
/// ```
class SwitchLatestStream<T> extends Stream<T> {
// ignore: close_sinks
final StreamController<T> _controller;
/// Constructs a [Stream] that emits [Stream]s (aka a 'Higher Order Stream") into a
/// single [Stream] that emits the items emitted by the most-recently-emitted of
/// those [Stream]s.
SwitchLatestStream(Stream<Stream<T>> streams)
: _controller = _buildController(streams);
@override
StreamSubscription<T> listen(
void Function(T event) onData, {
Function onError,
void Function() onDone,
bool cancelOnError,
}) =>
_controller.stream.listen(
onData,
onError: onError,
onDone: onDone,
cancelOnError: cancelOnError,
);
static StreamController<T> _buildController<T>(Stream<Stream<T>> streams) {
StreamController<T> controller;
StreamSubscription<Stream<T>> subscription;
StreamSubscription<T> otherSubscription;
var leftClosed = false, rightClosed = false, hasMainEvent = false;
controller = StreamController<T>(
sync: true,
onListen: () {
final closeLeft = () {
leftClosed = true;
if (rightClosed || !hasMainEvent) controller.close();
};
final closeRight = () {
rightClosed = true;
if (leftClosed) controller.close();
};
subscription = streams.listen((stream) {
try {
otherSubscription?.cancel();
hasMainEvent = true;
otherSubscription = stream.listen(
controller.add,
onError: controller.addError,
onDone: closeRight,
);
} catch (e, s) {
controller.addError(e, s);
}
}, onError: controller.addError, onDone: closeLeft);
},
onPause: () {
subscription.pause();
otherSubscription?.pause();
},
onResume: () {
subscription.resume();
otherSubscription?.resume();
},
onCancel: () async {
await subscription.cancel();
if (hasMainEvent) await otherSubscription.cancel();
});
return controller;
}
}
| rxdart/lib/src/streams/switch_latest.dart/0 | {'file_path': 'rxdart/lib/src/streams/switch_latest.dart', 'repo_id': 'rxdart', 'token_count': 1236} |
import 'dart:async';
import 'package:rxdart/src/transformers/backpressure/backpressure.dart';
/// Creates a [Stream] where each item is a [Stream] containing the items
/// from the source sequence.
///
/// This [List] is emitted every time the window [Stream]
/// emits an event.
///
/// ### Example
///
/// Stream.periodic(const Duration(milliseconds: 100), (i) => i)
/// .window(Stream.periodic(const Duration(milliseconds: 160), (i) => i))
/// .asyncMap((stream) => stream.toList())
/// .listen(print); // prints [0, 1] [2, 3] [4, 5] ...
class WindowStreamTransformer<T>
extends BackpressureStreamTransformer<T, Stream<T>> {
/// Constructs a [StreamTransformer] which buffers events into a [Stream] and
/// emits this [Stream] whenever [window] fires an event.
///
/// The [Stream] is recreated and starts empty upon every [window] event.
WindowStreamTransformer(Stream Function(T event) window)
: super(WindowStrategy.firstEventOnly, window,
onWindowEnd: (List<T> queue) => Stream.fromIterable(queue),
ignoreEmptyWindows: false) {
if (window == null) throw ArgumentError.notNull('window');
}
}
/// Buffers a number of values from the source Stream by count then emits the
/// buffer as a [Stream] and clears it, and starts a new buffer each
/// startBufferEvery values. If startBufferEvery is not provided, then new
/// buffers are started immediately at the start of the source and when each
/// buffer closes and is emitted.
///
/// ### Example
/// count is the maximum size of the buffer emitted
///
/// Rx.range(1, 4)
/// .windowCount(2)
/// .asyncMap((stream) => stream.toList())
/// .listen(print); // prints [1, 2], [3, 4] done!
///
/// ### Example
/// if startBufferEvery is 2, then a new buffer will be started
/// on every other value from the source. A new buffer is started at the
/// beginning of the source by default.
///
/// Rx.range(1, 5)
/// .bufferCount(3, 2)
/// .listen(print); // prints [1, 2, 3], [3, 4, 5], [5] done!
class WindowCountStreamTransformer<T>
extends BackpressureStreamTransformer<T, Stream<T>> {
/// Constructs a [StreamTransformer] which buffers events into a [Stream] and
/// emits this [Stream] whenever its length is equal to [count].
///
/// A new buffer is created for every n-th event emitted
/// by the [Stream] that is being transformed, as specified by
/// the [startBufferEvery] parameter.
///
/// If [startBufferEvery] is omitted or equals 0, then a new buffer is started whenever
/// the previous one reaches a length of [count].
WindowCountStreamTransformer(int count, [int startBufferEvery = 0])
: super(WindowStrategy.onHandler, null,
onWindowEnd: (List<T> queue) => Stream.fromIterable(queue),
startBufferEvery: startBufferEvery,
closeWindowWhen: (Iterable<T> queue) => queue.length == count) {
if (count == null) throw ArgumentError.notNull('count');
if (startBufferEvery == null) {
throw ArgumentError.notNull('startBufferEvery');
}
if (count < 1) throw ArgumentError.value(count, 'count');
if (startBufferEvery < 0) {
throw ArgumentError.value(startBufferEvery, 'startBufferEvery');
}
}
}
/// Creates a [Stream] where each item is a [Stream] containing the items
/// from the source sequence, batched whenever test passes.
///
/// ### Example
///
/// Stream.periodic(const Duration(milliseconds: 100), (int i) => i)
/// .windowTest((i) => i % 2 == 0)
/// .asyncMap((stream) => stream.toList())
/// .listen(print); // prints [0], [1, 2] [3, 4] [5, 6] ...
class WindowTestStreamTransformer<T>
extends BackpressureStreamTransformer<T, Stream<T>> {
/// Constructs a [StreamTransformer] which buffers events into a [Stream] and
/// emits this [Stream] whenever the [test] Function yields true.
WindowTestStreamTransformer(bool Function(T value) test)
: super(WindowStrategy.onHandler, null,
onWindowEnd: (List<T> queue) => Stream.fromIterable(queue),
closeWindowWhen: (Iterable<T> queue) => test(queue.last)) {
if (test == null) throw ArgumentError.notNull('test');
}
}
/// Extends the Stream class with the ability to window
extension WindowExtensions<T> on Stream<T> {
/// Creates a Stream where each item is a [Stream] containing the items from
/// the source sequence.
///
/// This [List] is emitted every time [window] emits an event.
///
/// ### Example
///
/// Stream.periodic(Duration(milliseconds: 100), (i) => i)
/// .window(Stream.periodic(Duration(milliseconds: 160), (i) => i))
/// .asyncMap((stream) => stream.toList())
/// .listen(print); // prints [0, 1] [2, 3] [4, 5] ...
Stream<Stream<T>> window(Stream window) =>
transform(WindowStreamTransformer((_) => window));
/// Buffers a number of values from the source Stream by [count] then emits
/// the buffer as a [Stream] and clears it, and starts a new buffer each
/// [startBufferEvery] values. If [startBufferEvery] is not provided, then new
/// buffers are started immediately at the start of the source and when each
/// buffer closes and is emitted.
///
/// ### Example
/// [count] is the maximum size of the buffer emitted
///
/// RangeStream(1, 4)
/// .windowCount(2)
/// .asyncMap((stream) => stream.toList())
/// .listen(print); // prints [1, 2], [3, 4] done!
///
/// ### Example
/// if [startBufferEvery] is 2, then a new buffer will be started
/// on every other value from the source. A new buffer is started at the
/// beginning of the source by default.
///
/// RangeStream(1, 5)
/// .bufferCount(3, 2)
/// .listen(print); // prints [1, 2, 3], [3, 4, 5], [5] done!
Stream<Stream<T>> windowCount(int count, [int startBufferEvery = 0]) =>
transform(WindowCountStreamTransformer(count, startBufferEvery));
/// Creates a Stream where each item is a [Stream] containing the items from
/// the source sequence, batched whenever test passes.
///
/// ### Example
///
/// Stream.periodic(Duration(milliseconds: 100), (int i) => i)
/// .windowTest((i) => i % 2 == 0)
/// .asyncMap((stream) => stream.toList())
/// .listen(print); // prints [0], [1, 2] [3, 4] [5, 6] ...
Stream<Stream<T>> windowTest(bool Function(T event) onTestHandler) =>
transform(WindowTestStreamTransformer(onTestHandler));
/// Creates a Stream where each item is a [Stream] containing the items from
/// the source sequence, sampled on a time frame with [duration].
///
/// ### Example
///
/// Stream.periodic(Duration(milliseconds: 100), (int i) => i)
/// .windowTime(Duration(milliseconds: 220))
/// .doOnData((_) => print('next window'))
/// .flatMap((s) => s)
/// .listen(print); // prints next window 0, 1, next window 2, 3, ...
Stream<Stream<T>> windowTime(Duration duration) {
if (duration == null) throw ArgumentError.notNull('duration');
return window(Stream<void>.periodic(duration));
}
}
| rxdart/lib/src/transformers/backpressure/window.dart/0 | {'file_path': 'rxdart/lib/src/transformers/backpressure/window.dart', 'repo_id': 'rxdart', 'token_count': 2402} |
import 'dart:async';
import 'package:rxdart/src/utils/min_max.dart';
/// Extends the Stream class with the ability to transform into a Future
/// that completes with the smallest item emitted by the Stream.
extension MinExtension<T> on Stream<T> {
/// Converts a Stream into a Future that completes with the smallest item
/// emitted by the Stream.
///
/// This is similar to finding the min value in a list, but the values are
/// asynchronous!
///
/// ### Example
///
/// final min = await Stream.fromIterable([1, 2, 3]).min();
///
/// print(min); // prints 1
///
/// ### Example with custom [Comparator]
///
/// final stream = Stream.fromIterable(['short', 'looooooong']);
/// final min = await stream.min((a, b) => a.length - b.length);
///
/// print(min); // prints 'short'
Future<T> min([Comparator<T> comparator]) => minMax(this, true, comparator);
}
| rxdart/lib/src/transformers/min.dart/0 | {'file_path': 'rxdart/lib/src/transformers/min.dart', 'repo_id': 'rxdart', 'token_count': 297} |
/// An Object which acts as a tuple containing both an error and the
/// corresponding stack trace.
class ErrorAndStackTrace {
/// A reference to the wrapped error object.
final Object error;
/// A reference to the wrapped [StackTrace]
final StackTrace stackTrace;
/// Constructs an object containing both an [error] and the
/// corresponding [stackTrace].
ErrorAndStackTrace(this.error, this.stackTrace);
@override
String toString() =>
'ErrorAndStackTrace{error: $error, stackTrace: $stackTrace}';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is ErrorAndStackTrace &&
runtimeType == other.runtimeType &&
error == other.error &&
stackTrace == other.stackTrace;
@override
int get hashCode => error.hashCode ^ stackTrace.hashCode;
}
| rxdart/lib/src/utils/error_and_stacktrace.dart/0 | {'file_path': 'rxdart/lib/src/utils/error_and_stacktrace.dart', 'repo_id': 'rxdart', 'token_count': 273} |
import 'package:rxdart/rxdart.dart';
import 'package:test/test.dart';
void main() {
test('Rx.fromCallable.sync', () {
var called = false;
var stream = Rx.fromCallable(() {
called = true;
return 2;
});
expect(called, false);
expectLater(stream, emitsInOrder(<dynamic>[2, emitsDone]));
expect(called, true);
});
test('Rx.fromCallable.async', () {
var called = false;
var stream = FromCallableStream(() async {
called = true;
await Future<void>.delayed(const Duration(milliseconds: 10));
return 2;
});
expect(called, false);
expectLater(stream, emitsInOrder(<dynamic>[2, emitsDone]));
expect(called, true);
});
test('Rx.fromCallable.reusable', () {
var stream = Rx.fromCallable(() => 2, reusable: true);
expect(stream.isBroadcast, isTrue);
stream.listen(null);
stream.listen(null);
expect(true, true);
});
test('Rx.fromCallable.singleSubscription', () {
{
var stream = Rx.fromCallable(() =>
Future.delayed(const Duration(milliseconds: 10), () => 'Value'));
expect(stream.isBroadcast, isFalse);
stream.listen(null);
expect(() => stream.listen(null), throwsStateError);
}
{
var stream = Rx.fromCallable(() => Future<String>.error(Exception()));
expect(stream.isBroadcast, isFalse);
stream.listen(null, onError: (Object e) {});
expect(
() => stream.listen(null, onError: (Object e) {}), throwsStateError);
}
});
test('Rx.fromCallable.asBroadcastStream', () async {
final stream = Rx.fromCallable(() => 2).asBroadcastStream();
// listen twice on same stream
stream.listen(null);
stream.listen(null);
// code should reach here
await expectLater(stream.isBroadcast, isTrue);
});
test('Rx.fromCallable.sync.shouldThrow', () {
var stream = Rx.fromCallable<String>(() => throw Exception());
expectLater(
stream,
emitsInOrder(<dynamic>[emitsError(isException), emitsDone]),
);
});
test('Rx.fromCallable.async.shouldThrow', () {
{
var stream = Rx.fromCallable<String>(() async => throw Exception());
expectLater(
stream,
emitsInOrder(<dynamic>[emitsError(isException), emitsDone]),
);
}
{
var stream = Rx.fromCallable<String>(() => Future.error(Exception()));
expectLater(
stream,
emitsInOrder(<dynamic>[emitsError(isException), emitsDone]),
);
}
});
test('Rx.fromCallable.sync.pause.resume', () {
var stream = Rx.fromCallable(() => 'Value');
stream
.listen(
expectAsync1(
(v) => expect(v, 'Value'),
count: 1,
),
)
.pause(Future<void>.delayed(const Duration(milliseconds: 50)));
});
test('Rx.fromCallable.async.pause.resume', () {
var stream = Rx.fromCallable(() async {
await Future<void>.delayed(const Duration(milliseconds: 10));
return 'Value';
});
stream
.listen(
expectAsync1(
(v) => expect(v, 'Value'),
count: 1,
),
)
.pause(Future<void>.delayed(const Duration(milliseconds: 50)));
});
}
| rxdart/test/streams/from_callable_test.dart/0 | {'file_path': 'rxdart/test/streams/from_callable_test.dart', 'repo_id': 'rxdart', 'token_count': 1345} |
import 'dart:async';
import 'package:rxdart/rxdart.dart';
import 'package:test/test.dart';
void main() {
test('Rx.windowTest', () async {
await expectLater(
Rx.range(1, 4)
.windowTest((i) => i % 2 == 0)
.asyncMap((stream) => stream.toList()),
emitsInOrder(<dynamic>[
const [1, 2],
const [3, 4],
emitsDone
]));
});
test('Rx.windowTest.reusable', () async {
final transformer = WindowTestStreamTransformer<int>((i) => i % 2 == 0);
await expectLater(
Stream.fromIterable(const [1, 2, 3, 4])
.transform(transformer)
.asyncMap((stream) => stream.toList()),
emitsInOrder(<dynamic>[
const [1, 2],
const [3, 4],
emitsDone
]));
await expectLater(
Stream.fromIterable(const [1, 2, 3, 4])
.transform(transformer)
.asyncMap((stream) => stream.toList()),
emitsInOrder(<dynamic>[
const [1, 2],
const [3, 4],
emitsDone
]));
});
test('Rx.windowTest.asBroadcastStream', () async {
final future = Stream.fromIterable(const [1, 2, 3, 4])
.asBroadcastStream()
.windowTest((i) => i % 2 == 0)
.drain<void>();
// listen twice on same stream
await expectLater(future, completes);
await expectLater(future, completes);
});
test('Rx.windowTest.error.shouldThrowA', () async {
await expectLater(
Stream<int>.error(Exception()).windowTest((i) => i % 2 == 0),
emitsError(isException));
});
test('Rx.windowTest.skip.shouldThrowB', () {
expect(() => Stream.fromIterable(const [1, 2, 3, 4]).windowTest(null),
throwsArgumentError);
});
}
| rxdart/test/transformers/backpressure/window_test_test.dart/0 | {'file_path': 'rxdart/test/transformers/backpressure/window_test_test.dart', 'repo_id': 'rxdart', 'token_count': 807} |
import 'dart:async';
import 'package:rxdart/rxdart.dart';
import 'package:test/test.dart';
Stream<int> _getStream() => Stream.fromIterable(const [0, 1, 2, 3, 4]);
void main() {
test('Rx.interval', () async {
const expectedOutput = [0, 1, 2, 3, 4];
var count = 0, lastInterval = -1;
final stopwatch = Stopwatch()..start();
_getStream().interval(const Duration(milliseconds: 1)).listen(
expectAsync1((result) {
expect(expectedOutput[count++], result);
if (lastInterval != -1) {
expect(stopwatch.elapsedMilliseconds - lastInterval >= 1, true);
}
lastInterval = stopwatch.elapsedMilliseconds;
}, count: expectedOutput.length),
onDone: stopwatch.stop);
});
test('Rx.interval.reusable', () async {
final transformer =
IntervalStreamTransformer<int>(const Duration(milliseconds: 1));
const expectedOutput = [0, 1, 2, 3, 4];
var countA = 0, countB = 0;
final stopwatch = Stopwatch()..start();
_getStream().transform(transformer).listen(
expectAsync1((result) {
expect(expectedOutput[countA++], result);
}, count: expectedOutput.length),
onDone: stopwatch.stop);
_getStream().transform(transformer).listen(
expectAsync1((result) {
expect(expectedOutput[countB++], result);
}, count: expectedOutput.length),
onDone: stopwatch.stop);
});
test('Rx.interval.asBroadcastStream', () async {
final stream = _getStream()
.asBroadcastStream()
.interval(const Duration(milliseconds: 20));
// listen twice on same stream
stream.listen(null);
stream.listen(null);
// code should reach here
await expectLater(true, true);
});
test('Rx.interval.error.shouldThrowA', () async {
final streamWithError = Stream<void>.error(Exception())
.interval(const Duration(milliseconds: 20));
streamWithError.listen(null,
onError: expectAsync2((Exception e, StackTrace s) {
expect(e, isException);
}));
});
test('Rx.interval.error.shouldThrowB', () async {
runZoned(() {
final streamWithError =
Stream.value(1).interval(const Duration(milliseconds: 20));
streamWithError.listen(null,
onError: expectAsync2(
(Exception e, StackTrace s) => expect(e, isException)));
},
zoneSpecification: ZoneSpecification(
createTimer: (self, parent, zone, duration, void Function() f) =>
throw Exception('Zone createTimer error')));
});
test('Rx.interval accidental broadcast', () async {
final controller = StreamController<int>();
final stream = controller.stream.interval(const Duration(milliseconds: 10));
stream.listen(null);
expect(() => stream.listen(null), throwsStateError);
controller.add(1);
});
}
| rxdart/test/transformers/interval_test.dart/0 | {'file_path': 'rxdart/test/transformers/interval_test.dart', 'repo_id': 'rxdart', 'token_count': 1124} |
import 'dart:async';
import 'package:rxdart/rxdart.dart';
import 'package:test/test.dart';
Stream<int> _getStream() {
final controller = StreamController<int>();
Timer(const Duration(milliseconds: 10), () => controller.add(1));
Timer(const Duration(milliseconds: 20), () => controller.add(2));
Timer(const Duration(milliseconds: 30), () => controller.add(3));
Timer(const Duration(milliseconds: 40), () {
controller.add(4);
controller.close();
});
return controller.stream;
}
Stream<int> _getOtherStream(int value) {
final controller = StreamController<int>();
Timer(const Duration(milliseconds: 15), () => controller.add(value + 1));
Timer(const Duration(milliseconds: 25), () => controller.add(value + 2));
Timer(const Duration(milliseconds: 35), () => controller.add(value + 3));
Timer(const Duration(milliseconds: 45), () {
controller.add(value + 4);
controller.close();
});
return controller.stream;
}
Stream<int> range() =>
Stream.fromIterable(const [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
void main() {
test('Rx.switchMap', () async {
const expectedOutput = [5, 6, 7, 8];
var count = 0;
_getStream().switchMap(_getOtherStream).listen(expectAsync1((result) {
expect(result, expectedOutput[count++]);
}, count: expectedOutput.length));
});
test('Rx.switchMap.reusable', () async {
final transformer = SwitchMapStreamTransformer<int, int>(_getOtherStream);
const expectedOutput = [5, 6, 7, 8];
var countA = 0, countB = 0;
_getStream().transform(transformer).listen(expectAsync1((result) {
expect(result, expectedOutput[countA++]);
}, count: expectedOutput.length));
_getStream().transform(transformer).listen(expectAsync1((result) {
expect(result, expectedOutput[countB++]);
}, count: expectedOutput.length));
});
test('Rx.switchMap.asBroadcastStream', () async {
final stream = _getStream().asBroadcastStream().switchMap(_getOtherStream);
// listen twice on same stream
stream.listen(null);
stream.listen(null);
// code should reach here
await expectLater(true, true);
});
test('Rx.switchMap.error.shouldThrowA', () async {
final streamWithError =
Stream<int>.error(Exception()).switchMap(_getOtherStream);
streamWithError.listen(null,
onError: expectAsync2((Exception e, StackTrace s) {
expect(e, isException);
}));
});
test('Rx.switchMap.error.shouldThrowB', () async {
final streamWithError = Stream.value(1).switchMap(
(_) => Stream<void>.error(Exception('Catch me if you can!')));
streamWithError.listen(null,
onError: expectAsync2((Exception e, StackTrace s) {
expect(e, isException);
}));
});
test('Rx.switchMap.error.shouldThrowC', () async {
final streamWithError = Stream.value(1).switchMap<void>((_) {
throw Exception('oh noes!');
});
streamWithError.listen(null,
onError: expectAsync2((Exception e, StackTrace s) {
expect(e, isException);
}));
});
test('Rx.switchMap.pause.resume', () async {
StreamSubscription<int> subscription;
final stream = Stream.value(0).switchMap((_) => Stream.value(1));
subscription = stream.listen(expectAsync1((value) {
expect(value, 1);
subscription.cancel();
}, count: 1));
subscription.pause();
subscription.resume();
});
test('Rx.switchMap stream close after switch', () async {
final controller = StreamController<int>();
final list = controller.stream
.switchMap((it) => Stream.fromIterable([it, it]))
.toList();
controller.add(1);
await Future<void>.delayed(Duration(microseconds: 1));
controller.add(2);
await controller.close();
expect(await list, [1, 1, 2, 2]);
});
test('Rx.switchMap accidental broadcast', () async {
final controller = StreamController<int>();
final stream = controller.stream.switchMap((_) => Stream<int>.empty());
stream.listen(null);
expect(() => stream.listen(null), throwsStateError);
controller.add(1);
});
test('Rx.switchMap closes after the last inner Stream closed - issue/511',
() async {
final outer = StreamController<bool>();
final inner = BehaviorSubject.seeded(false);
final stream = outer.stream.switchMap((_) => inner.stream);
expect(stream, emitsThrough(emitsDone));
outer.add(true);
await Future<void>.delayed(Duration.zero);
await inner.close();
await outer.close();
});
}
| rxdart/test/transformers/switch_map_test.dart/0 | {'file_path': 'rxdart/test/transformers/switch_map_test.dart', 'repo_id': 'rxdart', 'token_count': 1628} |
name: flutter_module
description: An example Flutter module.
version: 1.0.0+1
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
provider: ^6.0.2
dev_dependencies:
analysis_defaults:
path: ../../../analysis_defaults
flutter_test:
sdk: flutter
flutter_driver:
sdk: flutter
espresso: ">=0.2.0 <0.4.0"
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
iosBundleIdentifier: dev.flutter.example.flutterModule
| samples/add_to_app/fullscreen/flutter_module/pubspec.yaml/0 | {'file_path': 'samples/add_to_app/fullscreen/flutter_module/pubspec.yaml', 'repo_id': 'samples', 'token_count': 312} |
/*
* Copyright (C) 2021 The Android Open Source Project
*
* 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.
*/
import 'package:flutter/material.dart';
Future<void> main() async {
runApp(const MyApp());
}
/* Main widget that contains the Flutter starter app. */
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 MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
const Padding(
padding: EdgeInsets.only(top: 42, bottom: 250),
child: Align(
alignment: Alignment.topCenter, child: CustomAppBar())),
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
/* A Flutter implementation of the last frame of the splashscreen animation */
class CustomAppBar extends StatelessWidget {
const CustomAppBar({super.key});
@override
Widget build(BuildContext context) {
Widget titleSection = Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 12, right: 4),
child: ClipRRect(
borderRadius: BorderRadius.circular(36.0),
child: Image.asset(
'images/androidIcon.png',
width: 72.0,
height: 72.0,
fit: BoxFit.fill,
),
),
),
const Padding(
padding: EdgeInsets.only(top: 3),
child: Text("Super Splash Screen Demo",
style: TextStyle(color: Colors.black54, fontSize: 24)),
),
],
);
return titleSection;
}
}
| samples/android_splash_screen/lib/main.dart/0 | {'file_path': 'samples/android_splash_screen/lib/main.dart', 'repo_id': 'samples', 'token_count': 1269} |
// 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 TweenSequenceDemo extends StatefulWidget {
const TweenSequenceDemo({super.key});
static const String routeName = 'basics/chaining_tweens';
@override
State<TweenSequenceDemo> createState() => _TweenSequenceDemoState();
}
class _TweenSequenceDemoState extends State<TweenSequenceDemo>
with SingleTickerProviderStateMixin {
static const Duration duration = Duration(seconds: 3);
late final AnimationController controller;
late final Animation<Color?> animation;
static final colors = [
Colors.red,
Colors.orange,
Colors.yellow,
Colors.green,
Colors.blue,
Colors.indigo,
Colors.purple,
];
@override
void initState() {
super.initState();
final sequenceItems = <TweenSequenceItem<Color?>>[];
for (var i = 0; i < colors.length; i++) {
final beginColor = colors[i];
final endColor = colors[(i + 1) % colors.length];
final weight = 1 / colors.length;
sequenceItems.add(
TweenSequenceItem<Color?>(
tween: ColorTween(begin: beginColor, end: endColor),
weight: weight,
),
);
}
controller = AnimationController(duration: duration, vsync: this);
animation = TweenSequence<Color?>(sequenceItems).animate(controller);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Tween Sequences'),
),
body: Center(
child: AnimatedBuilder(
animation: animation,
builder: (context, child) {
return MaterialButton(
color: animation.value,
onPressed: () async {
await controller.forward();
controller.reset();
},
child: child,
);
},
child: const Text('Animate', style: TextStyle(color: Colors.white)),
),
),
);
}
}
| samples/animations/lib/src/basics/tween_sequence.dart/0 | {'file_path': 'samples/animations/lib/src/basics/tween_sequence.dart', 'repo_id': 'samples', 'token_count': 870} |
import 'package:shared/shared.dart';
import 'package:test/test.dart';
void main() {
test('Increment serialization', () {
expect(Increment(by: 3).toJson(), <String, dynamic>{'by': 3});
});
test('Increment derialization', () {
expect(Increment.fromJson(<String, dynamic>{'by': 5}), Increment(by: 5));
});
test('Count serialization', () {
expect(Count(3).toJson(), <String, dynamic>{'value': 3});
});
test('Count derialization', () {
expect(Count.fromJson(<String, dynamic>{'value': 5}), Count(5));
});
}
| samples/code_sharing/shared/test/shared_test.dart/0 | {'file_path': 'samples/code_sharing/shared/test/shared_test.dart', 'repo_id': 'samples', 'token_count': 201} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.