### Basic Mocking Example in Dart Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/mocking.md Illustrates a fundamental example of mocking a service using Mockito. It sets up a mock service, defines its behavior using 'when' and 'thenAnswer', and then verifies that the service method was called correctly. ```dart import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @GenerateMocks([ApiService]) void main() { late MockApiService mockApiService; late MyService myService; setUp(() { mockApiService = MockApiService(); myService = MyService(mockApiService); }); test('calls API and returns data', () async { // Arrange when(mockApiService.fetchData()) .thenAnswer((_) async => {'data': 'value'}); // Act final result = await myService.getData(); // Assert expect(result['data'], 'value'); verify(mockApiService.fetchData()).called(1); }); } ``` -------------------------------- ### Manual Localization Setup with intl Package (Dart) Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-internationalization/SKILL.md Demonstrates the manual setup for internationalization using the `intl` package. This involves creating localization classes, delegates, and generating ARB files for translations. ```dart class DemoLocalizations { DemoLocalizations(this.localeName); static Future load(Locale locale) { final String name = Intl.canonicalizedLocale(locale.toString()); return initializeMessages(name).then((_) => DemoLocalizations(name)); } static DemoLocalizations of(BuildContext context) { return Localizations.of(context, DemoLocalizations)!; } String get title { return Intl.message( 'Hello World', name: 'title', desc: 'Title', locale: localeName, ); } } class DemoLocalizationsDelegate extends LocalizationsDelegate { const DemoLocalizationsDelegate(); @override bool isSupported(Locale locale) => ['en', 'es'].contains(locale.languageCode); @override Future load(Locale locale) => DemoLocalizations.load(locale); @override bool shouldReload(DemoLocalizationsDelegate old) => false; } ``` -------------------------------- ### Complete Hero Animation Example in Dart Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-animations/SKILL.md Provides a comprehensive example of implementing Hero animations, including a reusable `PhotoHero` widget and the navigation logic to transition between screens. It showcases how to wrap content in `Hero` and manage the transition using `Navigator.push`. ```dart class PhotoHero extends StatelessWidget { const PhotoHero({ super.key, required this.photo, this.onTap, required this.width, }); final String photo; final VoidCallback? onTap; final double width; @override Widget build(BuildContext context) { return SizedBox( width: width, child: Hero( tag: photo, child: Material( color: Colors.transparent, child: InkWell( onTap: onTap, child: Image.asset(photo, fit: BoxFit.contain), ), ), ), ); } } ``` ```dart Navigator.of(context).push( MaterialPageRoute( builder: (context) { return Scaffold( appBar: AppBar(title: const Text('Detail')), body: Center( child: PhotoHero( photo: 'images/logo.png', width: 300.0, onTap: () => Navigator.of(context).pop(), ), ), ); }, ), ); ``` -------------------------------- ### Complete Login Flow Example in Dart Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-networking/references/authentication.md This Dart code provides a complete login flow example using an `AuthService`. It handles user login with email and password, token storage, and custom exceptions for invalid credentials. ```dart import 'dart:convert'; class AuthService { final http.Client _client; final TokenStorage _tokenStorage; AuthService(this._client, this._tokenStorage); Future login(String email, String password) async { final response = await _client.post( Uri.parse('https://api.example.com/auth/login'), headers: {'Content-Type': 'application/json'}, body: jsonEncode({ 'email': email, 'password': password, }), ); if (response.statusCode == 200) { final data = jsonDecode(response.body) as Map; final token = data['token'] as String; final user = User.fromJson(data['user'] as Map); await _tokenStorage.saveToken(token); return user; } else if (response.statusCode == 401) { throw InvalidCredentialsException(); } else { throw Exception('Login failed'); } } Future logout() async { await _tokenStorage.clearToken(); } } class User { final int id; final String email; final String name; User({required this.id, required this.email, required this.name}); factory User.fromJson(Map json) { return User( id: json['id'] as int, email: json['email'] as String, name: json['name'] as String, ); } } class InvalidCredentialsException implements Exception { @override String toString() => 'Invalid email or password'; } ``` -------------------------------- ### Dart Drift PostgreSQL Setup and Usage Source: https://github.com/madteacher/mad-agents-skills/blob/main/dart-drift/SKILL.md Illustrates how to configure drift for PostgreSQL, including adding dependencies, setting up build configurations, and opening a PostgreSQL connection. ```yaml dependencies: drift: ^2.30.0 postgres: ^3.5.9 drift_postgres: ^1.3.1 dev_dependencies: drift_dev: ^2.30.0 build_runner: ^2.10.4 ``` ```yaml targets: $default: builders: drift_dev: options: sql: dialects: - postgres ``` ```dart import 'package:drift/drift.dart'; import 'package:drift_postgres/drift_postgres.dart'; // Assuming AppDatabase and TodoItems are defined elsewhere // import 'your_database_definition.dart'; AppDatabase openPostgresConnection() { final endpoint = HostEndpoint( host: 'localhost', port: 5432, database: 'mydb', username: 'user', password: 'password', ); return AppDatabase( PgDatabase( endpoint: endpoint, ), ); } ``` -------------------------------- ### Basic go_router Configuration Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-navigation/references/go_router-guide.md Configure go_router by defining a list of GoRoute objects, each specifying a path and a builder for the corresponding screen. This setup is then passed to MaterialApp.router. ```dart import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; final _router = GoRouter( routes: [ GoRoute(path: '/', builder: (context, state) => HomeScreen()), GoRoute(path: '/details', builder: (context, state) => DetailsScreen()), ], ); void main() { runApp(MaterialApp.router(routerConfig: _router)); } ``` -------------------------------- ### Define Database Class (SQLite) Source: https://github.com/madteacher/mad-agents-skills/blob/main/dart-drift/references/setup.md Create a database class that extends drift's _$AppDatabase and defines your tables. This example shows a simple TodoItems table. ```dart import 'package:drift/drift.dart'; part 'database.g.dart'; class TodoItems extends Table { IntColumn get id => integer().autoIncrement()(); TextColumn get title => text()(); DateTimeColumn get createdAt => dateTime().nullable()(); } @DriftDatabase(tables: [TodoItems]) class AppDatabase extends _$AppDatabase { AppDatabase(QueryExecutor e) : super(e); @override int get schemaVersion => 1; } ``` -------------------------------- ### Dart Drift SQLite Setup and Usage Source: https://github.com/madteacher/mad-agents-skills/blob/main/dart-drift/SKILL.md Demonstrates how to set up dependencies, define a database, open a SQLite connection, and perform basic operations in a Dart CLI application using the drift library. ```yaml dependencies: drift: ^2.30.0 sqlite3: ^3.1.3 dev_dependencies: drift_dev: ^2.30.0 build_runner: ^2.10.4 ``` ```dart @DriftDatabase(tables: [TodoItems]) class AppDatabase extends _$AppDatabase { AppDatabase(QueryExecutor e) : super(e); @override int get schemaVersion => 1; } ``` ```dart import 'dart:io'; import 'package:drift/drift.dart'; import 'package:drift/native.dart'; import 'package:sqlite3/sqlite3.dart'; // Assuming TodoItems is defined elsewhere // import 'your_table_definition.dart'; AppDatabase openConnection() { final file = File('db.sqlite'); return AppDatabase(LazyDatabase(() async { final db = sqlite3.open(file.path); return NativeDatabase.createInBackground(db); })); } ``` ```bash dart run build_runner build ``` ```dart void main(List args) async { final db = openConnection(); // Assuming TodoItems table and select are defined // final todos = await db.select(db.todoItems).get(); // print('Found ${todos.length} todos'); await db.close(); } ``` -------------------------------- ### Dart Drift Backend Service with PostgreSQL Source: https://github.com/madteacher/mad-agents-skills/blob/main/dart-drift/SKILL.md Provides an example of a backend service using drift with PostgreSQL, demonstrating how to create a service class for managing todos and integrating with a connection pool. ```dart import 'package:drift/drift.dart'; import 'package:postgres/postgres_pool.dart'; import 'package:drift_postgres/drift_postgres.dart'; // Assuming AppDatabase, TodoItem, TodoItems, and TodoItemsCompanion are defined elsewhere // import 'your_database_definition.dart'; class TodoService { final AppDatabase db; TodoService(this.db); Future> getAllTodos() async { // Assuming db.todoItems and select are defined // return await db.select(db.todoItems).get(); return []; // Placeholder } Future createTodo(String title) async { // Assuming db.todoItems and into are defined // return await db.into(db.todoItems).insert( // TodoItemsCompanion.insert(title: title), // ); return 0; // Placeholder } } Future openPooledConnection() { final pool = PgPool( PgEndpoint( host: 'localhost', port: 5432, database: 'mydb', username: 'user', password: 'password', ), settings: PoolSettings(maxSize: 20), ); return AppDatabase(PgDatabase.opened(pool)); } void main() async { final db = await openPooledConnection(); final service = TodoService(db); final todoId = await service.createTodo('New task'); print('Created todo with id: $todoId'); final todos = await service.getAllTodos(); print('Total todos: ${todos.length}'); // Close the pool when the application shuts down // await db.close(); // This might need to close the pool specifically } ``` -------------------------------- ### Simulating User Drags in Dart Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/widget-testing.md Provides code examples for simulating drag gestures on widgets. It shows how to initiate a drag from a specific widget and move it by a given offset, followed by settling animations. ```dart // Drag a widget await tester.drag( find.byType(MyWidget), const Offset(0, -300), ); await tester.pumpAndSettle(); ``` -------------------------------- ### Perform Basic GET Request in Flutter Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-networking/SKILL.md Demonstrates how to perform a basic HTTP GET request in Flutter using the 'http' package. It includes fetching data, decoding JSON, and handling potential errors. ```dart import 'package:http/http.dart' as http; import 'dart:convert'; Future fetchAlbum() async { final response = await http.get( Uri.parse('https://api.example.com/albums/1'), ); if (response.statusCode == 200) { return Album.fromJson(jsonDecode(response.body)); } else { throw Exception('Failed to load album'); } } ``` -------------------------------- ### Dart Test File Structure Example Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/unit-testing.md Presents a recommended file structure for organizing Dart tests within a project. It shows a typical layout where test files are placed in a `test/` directory, often mirroring the `lib/` directory structure for related source files. This organization aids in maintainability and discoverability of tests. ```text lib/ counter.dart test/ counter/ counter_test.dart counter_value_test.dart counter_operations_test.dart ``` -------------------------------- ### Testing Widget Text Content in Dart Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/widget-testing.md Provides an example of testing the text content displayed by a widget. It shows how to pump a widget with specific text arguments and then assert that the correct text is displayed using `find.text`. ```dart testWidgets('displays correct text', (tester) async { await tester.pumpWidget(const MyWidget(text: 'Hello')); expect(find.text('Hello'), findsOneWidget); expect(find.text('Goodbye'), findsNothing); }); ``` -------------------------------- ### GitHub Actions CI/CD for Plugin Tests Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/plugin-testing.md A GitHub Actions workflow to automate testing for a plugin across different platforms. It includes jobs for running Dart unit tests on Ubuntu, Android unit tests on macOS, and iOS tests on macOS. This setup ensures continuous integration and testing. ```yaml name: Plugin Tests on: [push, pull_request] jobs: dart-tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: subosito/flutter-action@v2 - run: flutter test android-tests: runs-on: macos-latest steps: - uses: actions/checkout@v2 - name: Run Android tests run: | cd example/android ./gradlew testDebugUnitTest ios-tests: runs-on: macos-latest steps: - uses: actions/checkout@v2 - name: Run iOS tests run: | cd example/ios xcodebuild test -workspace Runner.xcworkspace \ -scheme Runner -configuration Debug ``` -------------------------------- ### Mocking a Stream in Dart Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/mocking.md Provides an example of mocking a stream. It sets up a mock StreamService, controls the stream's output using a StreamController, and uses expectLater with emitsInOrder to assert the sequence of emitted values. ```dart class StreamService { Stream get counterStream => StreamController().stream; } // Test test('mocks stream', () async { final mockService = MockStreamService(); final controller = StreamController(); when(mockService.counterStream).thenAnswer((_) => controller.stream); expectLater( mockService.counterStream, emitsInOrder([1, 2, 3]), ); controller.add(1); controller.add(2); controller.add(3); await controller.close(); }); ``` -------------------------------- ### Dart Drift Database Setup Source: https://context7.com/madteacher/mad-agents-skills/llms.txt Sets up a Drift database for Dart applications, supporting type-safe queries, reactive streams, and migrations for SQLite and PostgreSQL. This example demonstrates defining tables, creating the database, and performing basic CRUD operations. ```dart // pubspec.yaml dependencies // dependencies: // drift: ^2.30.0 // sqlite3: ^3.1.3 // dev_dependencies: // drift_dev: ^2.30.0 // build_runner: ^2.10.4 import 'dart:io'; import 'package:drift/drift.dart'; import 'package:drift/native.dart'; import 'package:sqlite3/sqlite3.dart'; // Define table class TodoItems extends Table { IntColumn get id => integer().autoIncrement()(); TextColumn get title => text().withLength(min: 1, max: 100)(); BoolColumn get isCompleted => boolean().withDefault(const Constant(false))(); DateTimeColumn get createdAt => dateTime().withDefault(currentDateAndTime)(); } // Define database @DriftDatabase(tables: [TodoItems]) class AppDatabase extends _$AppDatabase { AppDatabase(QueryExecutor e) : super(e); @override int get schemaVersion => 1; } // Open SQLite connection AppDatabase openConnection() { final file = File('db.sqlite'); return AppDatabase(LazyDatabase(() async { final db = sqlite3.open(file.path); return NativeDatabase.createInBackground(db); })); } // Usage in CLI application void main(List args) async { final db = openConnection(); // Insert await db.into(db.todoItems).insert( TodoItemsCompanion.insert(title: 'New task'), ); // Query final todos = await db.select(db.todoItems).get(); print('Found ${todos.length} todos'); // Query with filter final pending = await (db.select(db.todoItems) ..where((t) => t.isCompleted.equals(false)) ).get(); await db.close(); } // Run: dart run build_runner build ``` -------------------------------- ### iOS Info.plist Configuration for Deep Links Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-navigation/references/deep-linking.md Configures iOS's `Info.plist` file for deep linking. Supports Universal Links (recommended, using associated domains) and custom schemes. Requires adding keys for associated domains or URL types. ```xml com.apple.developer.associated-domains applinks:yourapp.com ``` ```xml CFBundleURLTypes CFBundleURLName com.example.yourapp CFBundleURLSchemes myapp ``` -------------------------------- ### Apply Dependency Injection in Flutter Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-architecture/assets/examples/README.md Shows how to implement Dependency Injection in Flutter by providing dependencies through constructors. This example demonstrates injecting a TodoRepository into a TodoViewModel. ```dart class TodoViewModel extends ChangeNotifier { final TodoRepository _repository; TodoViewModel(this._repository); } // In main.dart /* final apiService = ApiService(); final databaseService = DatabaseService(); final repository = TodoRepository(apiService, databaseService); final viewModel = TodoViewModel(repository); */ ``` -------------------------------- ### Dart Test Naming Convention Example Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/unit-testing.md Provides guidance on naming conventions for Dart tests and test groups. It emphasizes using descriptive names that clearly state the purpose and expected outcome of a test, differentiating between good and less informative naming practices. This improves test readability and understanding. ```dart // Good test('value increments when increment is called', () {}); // Avoid test('increment', () {}); ``` -------------------------------- ### Android Unit Test for Flutter Plugin Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/plugin-testing.md Illustrates how to write unit tests for the native Android code of a Flutter plugin. These tests run on the JVM and verify the logic of Android-specific methods. The example uses JUnit assertions to check method outputs. ```java package com.example.my_plugin; import org.junit.Test; import static org.junit.Assert.*; public class MyPluginTest { @Test public void testNativeMethod() { MyPlugin plugin = new MyPlugin(); int result = plugin.calculate(10, 20); assertEquals(30, result); } @Test public void testStringProcessing() { MyPlugin plugin = new MyPlugin(); String result = plugin.process("hello"); assertEquals("HELLO", result); } } ``` -------------------------------- ### Flutter HTTP Basic Authentication Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-networking/references/authentication.md Provides a method to generate the Basic Authentication header required for HTTP requests in Flutter. It encodes username and password using Base64. The example also shows how to use this header in an HTTP GET request, similar to the Bearer Token example, handling success and failure responses. ```dart import 'dart:convert'; import 'package:http/http.dart' as http; import 'dart:io'; // Assuming Album class and jsonDecode are defined elsewhere // class Album { ... } String basicAuthHeader(String username, String password) { final credentials = '$username:$password'; return 'Basic ${base64Encode(utf8.encode(credentials))}'; } Future fetchAlbum(String username, String password) async { final response = await http.get( Uri.parse('https://api.example.com/albums/1'), headers: { HttpHeaders.authorizationHeader: basicAuthHeader(username, password), }, ); if (response.statusCode == 200) { return Album.fromJson(jsonDecode(response.body)); } else { throw Exception('Failed to load album'); } } ``` -------------------------------- ### Get vs Watch Comparison (Dart) Source: https://github.com/madteacher/mad-agents-skills/blob/main/dart-drift/references/streams.md Illustrates the difference between `get()` which fetches data once, and `watch()` which provides a stream for continuous updates. ```dart // Run once, get current results final todos = await select(todoItems).get(); // Watch for changes, get updates final todosStream = select(todoItems).watch(); ``` -------------------------------- ### Flutter Widget Test Example Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/SKILL.md An example of a widget test in Flutter, verifying the presence of a title and message within a custom widget. This test uses `flutter_test` to render and interact with widgets in a simulated environment. ```dart import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('MyWidget has a title and message', (tester) async { await tester.pumpWidget(const MyWidget(title: 'T', message: 'M')); final titleFinder = find.text('T'); final messageFinder = find.text('M'); expect(titleFinder, findsOneWidget); expect(messageFinder, findsOneWidget); }); } ``` -------------------------------- ### Run Integration Tests (Bash) Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/integration-testing.md Command-line instructions for running integration tests. These commands allow running tests on all connected devices, a specific device, or a particular test file, including using the `flutter drive` command. ```bash # Run on all devices flutter test integration_test/ # Run on specific device flutter test -d integration_test/ # Run specific test file flutter test integration_test/my_test.dart # Run with driver flutter drive --target=integration_test/my_test.dart ``` -------------------------------- ### Run iOS Tests via Command Line Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/plugin-testing.md This code snippet shows the bash commands to navigate to the iOS directory and execute tests using xcodebuild. It's a common way to automate iOS testing. ```bash # From ios directory cd example/ios # Run tests xcodebuild test -workspace Runner.xcworkspace -scheme Runner -configuration Debug # Or run from Xcode # Product > Test ``` -------------------------------- ### Flutter Integration Test Example Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/SKILL.md An integration test example for a Flutter application, demonstrating a user flow involving tapping a button to increment a counter. This test uses `integration_test` to run tests on a real device or emulator, simulating end-to-end functionality. ```dart import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:my_app/main.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('tap button, verify counter', (tester) async { await tester.pumpWidget(const MyApp()); expect(find.text('0'), findsOneWidget); await tester.tap(find.byKey(const ValueKey('increment'))); await tester.pumpAndSettle(); expect(find.text('1'), findsOneWidget); }); } ``` -------------------------------- ### Grouping Unit Tests in Dart Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/unit-testing.md Shows how to group related unit tests using the `group` function in Dart's `test` package. This improves organization and allows for setup (`setUp`) and teardown (`tearDown`) logic to be applied to all tests within the group. ```dart import 'package:test/test.dart'; void main() { group('Counter', () { late Counter counter; setUp(() { counter = Counter(); }); test('value starts at 0', () { expect(counter.value, 0); }); test('increment increases value', () { counter.increment(); expect(counter.value, 1); }); tearDown(() { counter.dispose(); }); }); } ``` -------------------------------- ### Open SQLite Database Connection Source: https://github.com/madteacher/mad-agents-skills/blob/main/dart-drift/references/setup.md Open a SQLite database connection using sqlite3 and NativeDatabase.createInBackground for background execution. Ensure the database file path is correctly specified. ```dart import 'package:drift/drift.dart'; import 'package:sqlite3/sqlite3.dart'; import 'package:path/path.dart'; AppDatabase openConnection() { final file = File('db.sqlite'); return AppDatabase(LazyDatabase(() async { final db = sqlite3.open(file.path); return NativeDatabase.createInBackground(db); }); } ``` -------------------------------- ### Debug a Specific Flutter Test Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/SKILL.md Command to debug a specific test file. The `--no-sound-null-safety` flag is included as an example for older projects or specific debugging needs. ```bash flutter test --no-sound-null-safety test/my_test.dart ``` -------------------------------- ### Dart Testing Pitfall: Fragile Tests Example Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/unit-testing.md Illustrates the concept of fragile tests that are overly sensitive to external factors like timing. The example shows a 'bad' test that checks execution time, which can be unreliable, versus a 'good' test that focuses on the successful completion of an operation, leading to more stable tests. ```dart // Bad - depends on exact timing test('completes within 100ms', () async { final stopwatch = Stopwatch()..start(); await operation(); expect(stopwatch.elapsedMilliseconds, lessThan(100)); }); // Good - tests completion test('completes successfully', () async { await operation(); // operation completed without error }); ``` -------------------------------- ### Flutter Web Default Hash URL Strategy Setup Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-navigation/references/web-navigation.md Demonstrates the default setup for Flutter web applications using the Hash URL strategy. No specific code is required as it's the default behavior, making it simple to implement. ```dart void main() { runApp(MyApp()); } ``` -------------------------------- ### Open PostgreSQL Database Connection Source: https://github.com/madteacher/mad-agents-skills/blob/main/dart-drift/references/setup.md Open a PostgreSQL database connection using PgDatabase. Configure the HostEndpoint with your database credentials and connection details. ```dart import 'package:drift/drift.dart'; import 'package:drift_postgres/drift_postgres.dart'; import 'package:postgres/postgres.dart'; AppDatabase openPostgresConnection() { final endpoint = HostEndpoint( host: 'localhost', port: 5432, database: 'mydb', username: 'user', password: 'password', ); return AppDatabase( PgDatabase( endpoint: endpoint, ), ); } ``` -------------------------------- ### Provider Setup for Drift Database Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-drift/SKILL.md Configures a Provider for the AppDatabase instance, making it accessible throughout the Flutter widget tree. It also ensures the database is closed when the provider is disposed. ```dart final databaseProvider = Provider((ref) { final database = AppDatabase(); ref.onDispose(database.close); return database; }); ``` -------------------------------- ### Setup Dependency Injection with Provider in Dart Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-architecture/references/design-patterns.md Demonstrates how to set up dependency injection using the `provider` package in a Flutter application. It shows the creation of services and repositories, and how to provide them to the widget tree using `MultiProvider` and `ChangeNotifierProvider`. ```dart void main() { final apiService = ApiService(); final databaseService = DatabaseService(); final repository = TodoRepository(apiService, databaseService); final viewModel = TodoViewModel(repository); runApp( MultiProvider( providers: [ Provider.value(value: repository), ChangeNotifierProvider.value(value: viewModel), ], child: MyApp(), ), ); } ``` -------------------------------- ### Testing Widgets with Arguments in Dart Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/widget-testing.md Demonstrates how to test widgets that receive arguments, including simple data types like strings and callback functions. It shows how to pass these arguments during widget creation and verify their correct usage. ```dart testWidgets('receives and displays title', (tester) async { const title = 'My Title'; await tester.pumpWidget( MaterialApp( home: MyWidget(title: title), ), ); expect(find.text(title), findsOneWidget); }); testWidgets('receives and uses callback', (tester) async { bool callbackCalled = false; await tester.pumpWidget( MaterialApp( home: MyWidget( onPressed: () => callbackCalled = true, ), ), ); await tester.tap(find.byType(ElevatedButton)); expect(callbackCalled, true); }); ``` -------------------------------- ### Built-in Explicit Transitions in Dart Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-animations/SKILL.md Lists and provides an example of Flutter's built-in explicit transition widgets, such as FadeTransition, ScaleTransition, and SlideTransition. These widgets simplify the implementation of common animation effects. ```dart FadeTransition( opacity: _animation, child: const FlutterLogo(), ) ``` -------------------------------- ### Add Flutter Internationalization Dependencies Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-internationalization/SKILL.md This snippet shows how to add the necessary dependencies for Flutter internationalization to your `pubspec.yaml` file and install them using `flutter pub add`. It includes `flutter_localizations` and the `intl` package. ```yaml dependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter intl: any ``` ```bash flutter pub add flutter_localizations --sdk=flutter flutter pub add intl:any ``` -------------------------------- ### Flutter Drift Database Setup and Configuration Source: https://context7.com/madteacher/mad-agents-skills/llms.txt Demonstrates setting up a Flutter Drift database with cross-platform support for mobile, web, and desktop. It includes database definition, schema versioning, and migration strategies. Dependencies for drift, drift_flutter, path_provider, and provider are also listed. ```dart // pubspec.yaml dependencies // dependencies: // drift: ^2.30.0 // drift_flutter: ^0.2.8 // path_provider: ^2.1.5 // provider: ^6.0.0 import 'package:flutter/material.dart'; import 'package:drift/drift.dart'; import 'package:drift_flutter/drift_flutter.dart'; import 'package:path_provider/path_provider.dart'; import 'package:provider/provider.dart'; // Database definition with cross-platform support @DriftDatabase(tables: [TodoItems]) class AppDatabase extends _$AppDatabase { AppDatabase([QueryExecutor? e]) : super( e ?? driftDatabase( name: 'app_db', native: const DriftNativeOptions( databaseDirectory: getApplicationSupportDirectory, ), web: DriftWebOptions( sqlite3Wasm: Uri.parse('sqlite3.wasm'), driftWorker: Uri.parse('drift_worker.js'), ), ), ); @override int get schemaVersion => 1; // Migration strategy @override MigrationStrategy get migration { return MigrationStrategy( onUpgrade: stepByStep( from1To2: (m, schema) async { await m.addColumn(schema.todoItems, schema.todoItems.dueDate); }, ), ); } } // In-memory database for testing AppDatabase createTestDatabase() { return AppDatabase(NativeDatabase.memory()); } ``` -------------------------------- ### Test Navigation Between Screens in Flutter Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/widget-testing.md Provides an example of testing navigation between different screens in a Flutter application. This test simulates user interaction (tapping a button) and verifies that the correct screen is displayed using `pumpAndSettle`. ```dart testWidgets('navigates to detail screen', (tester) async { await tester.pumpWidget( MaterialApp( initialRoute: '/', routes: { '/': (context) => const HomeScreen(), '/detail': (context) => const DetailScreen(), }, ), ); // Tap navigation button await tester.tap(find.text('Go to Detail')); await tester.pumpAndSettle(); // Verify navigation expect(find.text('Detail Screen'), findsOneWidget); expect(find.text('Home Screen'), findsNothing); }); ``` -------------------------------- ### Flutter GoRouter Preload Routes Example Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-navigation/references/web-navigation.md Shows how to preload routes in a Flutter application using `GoRouter`. This can enhance user experience by making subsequent navigations faster, especially for routes with heavy initial loading. ```dart // Preload in background WidgetsBinding.instance.addPostFrameCallback((_) { GoRouter.of(context).preloadRoutes(); }); ``` -------------------------------- ### Testing Conditional Widget Rendering in Dart Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/widget-testing.md Shows how to test conditional rendering based on widget properties. Examples include testing the display of a loading indicator when a loading flag is true, and a button when it's false. ```dart testWidgets('shows loading indicator when loading', (tester) async { await tester.pumpWidget(MyWidget(isLoading: true)); expect(find.byType(CircularProgressIndicator), findsOneWidget); expect(find.byType(ElevatedButton), findsNothing); }); testWidgets('shows button when not loading', (tester) async { await tester.pumpWidget(MyWidget(isLoading: false)); expect(find.byType(CircularProgressIndicator), findsNothing); expect(find.byType(ElevatedButton), findsOneWidget); }); ``` -------------------------------- ### Flutter Internationalization Setup and Usage (Dart) Source: https://context7.com/madteacher/mad-agents-skills/llms.txt Demonstrates the complete setup for Flutter internationalization, including `pubspec.yaml` configuration, ARB file structure for defining translations and placeholders, running the `gen-l10n` command, and utilizing the generated localizations within `MaterialApp` and individual widgets. It also shows how to override locales for specific widgets. ```dart // 1. Add dependencies to pubspec.yaml // dependencies: // flutter_localizations: // sdk: flutter // intl: any // 2. Enable generation in pubspec.yaml // flutter: // generate: true // 3. Create l10n.yaml in project root // arb-dir: lib/l10n // template-arb-file: app_en.arb // output-localization-file: app_localizations.dart // 4. Create lib/l10n/app_en.arb (template) // { // "helloWorld": "Hello World!", // "@helloWorld": { // "description": "Greeting message" // }, // "greeting": "Hello {userName}!", // "@greeting": { // "placeholders": { // "userName": {"type": "String"} // } // }, // "itemCount": "{count, plural, =0{No items} =1{1 item} other{{count} items}}", // "@itemCount": { // "placeholders": { // "count": {"type": "int"} // } // }, // "price": "Price: {value}", // "@price": { // "placeholders": { // "value": {"type": "int", "format": "simpleCurrency"} // } // } // } // 5. Create lib/l10n/app_es.arb (translation) // { // "helloWorld": "¡Hola Mundo!", // "greeting": "¡Hola {userName}!", // "itemCount": "{count, plural, =0{Sin artículos} =1{1 artículo} other{{count} artículos}}" // } // 6. Run: flutter gen-l10n // 7. Configure MaterialApp import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( localizationsDelegates: const [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: const [ Locale('en'), Locale('es'), ], home: const HomePage(), ); } } // 8. Use localizations in widgets class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { final l10n = AppLocalizations.of(context)!; return Scaffold( appBar: AppBar(title: Text(l10n.helloWorld)), body: Column( children: [ Text(l10n.greeting('Alice')), Text(l10n.itemCount(5)), Text(l10n.price(99)), ], ), ); } } // Override locale for specific widgets Widget buildSpanishCalendar(BuildContext context) { return Localizations.override( context: context, locale: const Locale('es'), child: CalendarDatePicker( initialDate: DateTime.now(), firstDate: DateTime(2020), lastDate: DateTime(2030), onDateChanged: (date) {}, ), ); } ``` -------------------------------- ### JSON Localization Configuration Example Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-internationalization/references/arb-format.md This JSON object defines localization strings for an application. It includes examples of simple text, personalized greetings with placeholders, pluralization for item counts, gender-based pronoun selection, and date formatting. The '@' prefixed keys provide metadata like descriptions and placeholder types for translators and developers. ```json { "appTitle": "My App", "@appTitle": { "description": "Application title" }, "greeting": "Hello {userName}!", "@greeting": { "description": "Personalized greeting message", "placeholders": { "userName": { "type": "String", "example": "John" } } }, "itemCount": "{count, plural, =0{No items} =1{1 item} other{{count} items}}", "@itemCount": { "description": "Number of items in cart", "placeholders": { "count": { "type": "int" } } }, "pronoun": "{gender, select, male{he} female{she} other{they}}", "@pronoun": { "description": "Gender-based pronoun", "placeholders": { "gender": { "type": "String" } } }, "orderDate": "Ordered on {date}", "@orderDate": { "description": "Order confirmation with date", "placeholders": { "date": { "type": "DateTime", "format": "yMMMd" } } } } ``` -------------------------------- ### Mocking a Class Method in Dart Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/mocking.md Shows how to mock a method of a concrete class. This example defines a simple DataService class and then mocks its fetchData method to return a predefined string value during testing. ```dart class DataService { Future fetchData() async => 'real data'; } // Test test('mocks class method', () async { final mockService = MockDataService(); when(mockService.fetchData()) .thenAnswer((_) async => 'mocked data'); final result = await mockService.fetchData(); expect(result, 'mocked data'); }); ``` -------------------------------- ### Running Dart Tests with Flutter CLI Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/unit-testing.md Provides common command-line interface (CLI) commands for running Dart tests using the Flutter tool. It covers executing all tests, specific files, generating coverage reports, enabling verbose output, and filtering tests by name. These commands are essential for test execution and analysis. ```bash # Run all tests flutter test # Run specific file flutter test test/counter/counter_test.dart # Run with coverage flutter test --coverage # Run verbose flutter test --verbose # Run specific test flutter test --name "value increments" ``` -------------------------------- ### iOS Deep Link Testing Command Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-navigation/references/deep-linking.md Tests deep links on an iOS simulator using the `xcrun simctl` command. This command opens a specified URL in the simulator, verifying the deep link functionality. ```bash xcrun simctl openurl booted "https://yourapp.com/path" ``` -------------------------------- ### Flutter Navigator Configuration for Deep Links Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-navigation/references/deep-linking.md Sets up deep link routing in Flutter using the standard `Navigator` and `MaterialApp` routes. This approach is less recommended due to limitations in route management and customization. ```dart MaterialApp( initialRoute: '/', routes: { '/': (context) => HomeScreen(), '/details/:id': (context) { final id = ModalRoute.of(context)!.settings.arguments as String; return DetailsScreen(id: id); }, }, ); ``` -------------------------------- ### Objective-C Unit Tests for iOS Plugin Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/plugin-testing.md This snippet demonstrates how to set up and run unit tests for an iOS plugin using XCTest. It includes tests for a native method calculation and string processing. ```objectivec #import #import "MyPlugin.h" @interface MyPluginTest : XCTestCase @end @implementation MyPluginTest - (void)setUp { [super setUp]; // Setup code } - (void)testNativeMethod { MyPlugin *plugin = [[MyPlugin alloc] init]; NSInteger result = [plugin calculateWithA:10 b:20]; XCTAssertEqual(result, 30); } - (void)testStringProcessing { MyPlugin *plugin = [[MyPlugin alloc] init]; NSString *result = [plugin processString:@"hello"]; XCTAssertEqualObjects(result, @"HELLO"); } @end ``` -------------------------------- ### iOS Universal Links Verification File Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-navigation/references/deep-linking.md Defines the `apple-app-site-association` JSON file required for verifying Universal Links on iOS. This file specifies which app IDs are associated with specific URL paths on your domain. ```json { "applinks": { "apps": [], "details": [ { "appIDs": ["TEAMID.com.example.yourapp"], "components": [ { "/": "/path/to/*", "comment": "Matches anything under /path/to/" } ] } ] } } ``` -------------------------------- ### Declarative Navigation with go_router Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-navigation/references/go_router-guide.md go_router provides declarative methods for navigation. Use `context.go()` to replace the current route with a new one, and `context.push()` to add a new route to the navigation stack. `context.pop()` is used to go back, optionally returning data. ```dart // Go to screen (replace current) context.go('/details'); // Push screen (add to stack) context.push('/details'); // Pop screen (go back) context.pop(); // OR return data context.pop('result_value'); ``` -------------------------------- ### Android App Links Verification File Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-navigation/references/deep-linking.md Defines the `assetlinks.json` file required for verifying App Links on Android. This JSON structure links your app to your website domain, enabling secure deep linking. ```json [ { "relation": ["delegate_permission/common.handle_all_urls"], "target": { "namespace": "android_app", "package_name": "com.example.yourapp", "sha256_cert_fingerprints": ["YOUR_SHA256_FINGERPRINT"] } }] ``` -------------------------------- ### Database Migration Schema Update (Dart) Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-drift/SKILL.md Defines a database migration strategy to update the schema from version 1 to 2 by adding a 'dueDate' column to the 'todoItems' table. This is part of the drift_flutter database setup. ```dart @override MigrationStrategy get migration { return MigrationStrategy( onUpgrade: stepByStep( from1To2: (m, schema) async { await m.addColumn(schema.todoItems, schema.todoItems.dueDate); }, ), ); } ``` -------------------------------- ### Testing Streams in Dart Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/unit-testing.md Illustrates how to test streams in Dart using `expectLater` and matchers like `emitsInOrder`. This is useful for verifying the sequence and content of data emitted by a stream over time. ```dart import 'dart:async'; class CounterStream { final _controller = StreamController(); Stream get stream => _controller.stream; void increment() => _controller.sink.add(1); void dispose() => _controller.close(); } // Test test('stream emits values', () async { final counter = CounterStream(); expectLater( counter.stream, emitsInOrder([1, 1, 1]), ); counter.increment(); counter.increment(); counter.increment(); await Future.delayed(const Duration(milliseconds: 100)); counter.dispose(); }); ``` -------------------------------- ### Dart: Interval-Based Animation Timing Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-animations/SKILL.md Demonstrates how to define an animation's timing using an Interval within a CurvedAnimation. This snippet shows how to control when an animation starts and ends relative to the parent controller's duration. ```dart animation = Tween(begin: 0, end: 300).animate( CurvedAnimation( parent: controller, curve: const Interval( 0.25, // Start at 25% of controller duration 0.50, // End at 50% of controller duration curve: Curves.ease, ), ), ); ``` -------------------------------- ### Mocking API Client with Mockito in Dart Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-testing/references/unit-testing.md Demonstrates how to use the Mockito package to create mock objects for API clients in Dart unit tests. It sets up a mock API client and uses it to test a UserService, verifying interactions and return values. Requires the 'mockito' and 'build_runner' packages. ```dart import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; // Generate mocks with: flutter pub run build_runner build class MockApiClient extends Mock implements ApiClient {} @GenerateMocks([ApiClient]) void main() { group('UserService', () { late MockApiClient mockApiClient; late UserService userService; setUp(() { mockApiClient = MockApiClient(); userService = UserService(mockApiClient); }); test('fetches user data', () async { when(mockApiClient.getUser('123')) .thenAnswer((_) async => User(id: '123', name: 'John')); final user = await userService.getUser('123'); expect(user.name, 'John'); verify(mockApiClient.getUser('123')).called(1); }); }); } ``` -------------------------------- ### AnimatedWidget Pattern Flutter Explicit Animation Source: https://github.com/madteacher/mad-agents-skills/blob/main/flutter-animations/SKILL.md A base class for widgets that rebuild whenever their listenable (typically an Animation) changes. It simplifies creating reusable animated widgets by abstracting the listener setup and rebuild logic. ```dart class AnimatedLogo extends AnimatedWidget { const AnimatedLogo({super.key, required Animation animation}) : super(listenable: animation); @override Widget build(BuildContext context) { final animation = listenable as Animation; return Center( child: Container( height: animation.value, width: animation.value, child: const FlutterLogo(), ), ); } } ``` -------------------------------- ### Open Pooled PostgreSQL Connection Source: https://github.com/madteacher/mad-agents-skills/blob/main/dart-drift/references/setup.md Open a PostgreSQL connection with connection pooling and custom settings for improved performance. Configure connectTimeout and queryTimeout in ConnectionSettings. ```dart AppDatabase openPooledPostgresConnection() { final endpoint = HostEndpoint( host: 'localhost', port: 5432, database: 'mydb', username: 'user', password: 'password', ); return AppDatabase( PgDatabase( endpoint: endpoint, settings: ConnectionSettings( connectTimeout: Duration(seconds: 10), queryTimeout: Duration(seconds: 30), ), ), ); } ``` -------------------------------- ### Configure PostgreSQL Connection Pool Settings Source: https://github.com/madteacher/mad-agents-skills/blob/main/dart-drift/SKILL.md Example of configuring `PoolSettings` for a PostgreSQL connection in Dart. This allows adjustment of `maxSize` and `maxLifetime` to manage connection resources efficiently and prevent pool exhaustion. ```dart PoolSettings( maxSize: 20, maxLifetime: Duration(minutes: 5), ) ```