### Run Flutter Fixtures Example App Source: https://github.com/brotoo25/flutter_fixtures/blob/main/CONTRIBUTING.md Commands to navigate to the example directory and run the demonstration application. Useful for verifying setup and understanding usage. ```bash cd example flutter run ``` -------------------------------- ### Run Flutter Example App Source: https://github.com/brotoo25/flutter_fixtures/blob/main/example/README.md Command to run the Flutter Fixtures example application. This is the primary method to interact with the demonstration. ```shell flutter run ``` -------------------------------- ### Complete Flutter API Service Example with Dio and Fixtures Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_dio/README.md A comprehensive example demonstrating the setup of an `ApiService` class using Dio and `flutter_fixtures_dio`. It includes initializing Dio with a base URL, adding the `FixturesInterceptor` with default value selection, and defining methods for fetching and creating users. ```dart import 'package:flutter/material.dart'; import 'package:dio/dio.dart'; import 'package:flutter_fixtures_dio/flutter_fixtures_dio.dart'; class ApiService { late final Dio _dio; ApiService() { _dio = Dio(BaseOptions(baseUrl: 'https://api.example.com')); // Add fixtures interceptor for development/testing _dio.interceptors.add( FixturesInterceptor( dataQuery: DioDataQuery(), dataSelector: DataSelectorType.defaultValue(), ), ); } Future> getUsers() async { final response = await _dio.get('/users'); return (response.data['users'] as List) .map((json) => User.fromJson(json)) .toList(); } Future createUser(User user) async { final response = await _dio.post('/users', data: user.toJson()); return User.fromJson(response.data); } } // Assuming User model with fromJson and toJson methods exists elsewhere. ``` -------------------------------- ### Dart Code Documentation Example Source: https://github.com/brotoo25/flutter_fixtures/blob/main/CONTRIBUTING.md An example of documenting a Dart class using dartdoc comments, including explanations of parameters, usage examples, and purpose. Essential for maintaining maintainable code. ```dart /// Creates a fixture interceptor for Dio HTTP client. /// /// The [dataQuery] is used to load and parse fixture files. /// The [dataSelector] determines how fixtures are selected. /// /// Example: /// ```dart /// final interceptor = FixturesInterceptor( /// dataQuery: DioDataQuery(), /// dataSelector: DataSelectorType.random(), /// ); /// ``` class FixturesInterceptor { // Implementation } ``` -------------------------------- ### Example API Service Implementation Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_dio/README.md A complete example demonstrating how to set up an `ApiService` class using Dio and the `FixturesInterceptor` for mocking GET and POST requests. ```APIDOC ## Example API Service Implementation ### Description This example shows a complete `ApiService` class that utilizes `Dio` with the `FixturesInterceptor` to mock network requests for fetching and creating users. ### Method API Service Setup and Usage ### Endpoint N/A (Illustrative API endpoints: GET /users, POST /users) ### Request Example ```dart import 'package:flutter/material.dart'; import 'package:dio/dio.dart'; import 'package:flutter_fixtures_dio/flutter_fixtures_dio.dart'; // Assume User model with fromJson and toJson methods exists class User { String? id; String? name; static User fromJson(Map json) => User() ..id = json['id'] ..name = json['name']; Map toJson() => {'id': id, 'name': name}; } class ApiService { late final Dio _dio; ApiService() { _dio = Dio(BaseOptions(baseUrl: 'https://api.example.com')); // Add fixtures interceptor for development/testing _dio.interceptors.add( FixturesInterceptor( dataQuery: DioDataQuery(), dataSelector: DataSelectorType.defaultValue(), // Use default fixture ), ); } Future> getUsers() async { try { final response = await _dio.get('/users'); // Ensure response.data is not null and is a Map before accessing 'users' if (response.data != null && response.data is Map) { final usersData = response.data['users']; if (usersData is List) { return usersData.map((json) => User.fromJson(json)).toList(); } } return []; // Return empty list if data format is unexpected } catch (e) { print('Error fetching users: $e'); return []; // Handle error appropriately } } Future createUser(User user) async { try { final response = await _dio.post('/users', data: user.toJson()); // Ensure response.data is not null and is a Map before calling fromJson if (response.data != null && response.data is Map) { return User.fromJson(response.data); } else { // Handle cases where response.data is not a Map or is null throw Exception('Invalid response data format'); } } catch (e) { print('Error creating user: $e'); rethrow; // Re-throw the exception for higher-level handling } } } ``` ### Response Example N/A (This section illustrates service implementation, not direct responses) ``` -------------------------------- ### Modular Installation of Flutter Fixtures Packages Source: https://github.com/brotoo25/flutter_fixtures/blob/main/README.md This snippet illustrates how to install individual packages of flutter_fixtures, such as `flutter_fixtures_core` and `flutter_fixtures_dio`, based on your project's needs. ```yaml dependencies: # Core interfaces and models (required) flutter_fixtures_core: ^0.1.0 # Only if you need Dio support flutter_fixtures_dio: ^0.1.0 # Only if you need UI components flutter_fixtures_ui: ^0.1.0 ``` -------------------------------- ### Setup Flutter Fixtures Project Source: https://github.com/brotoo25/flutter_fixtures/blob/main/CONTRIBUTING.md Commands to clone the repository and set up project dependencies. Ensures the development environment is correctly configured. ```bash git clone https://github.com/brotoo25/flutter_fixtures.git cd flutter_fixtures flutter pub get ``` -------------------------------- ### Install Flutter Fixtures using Flutter CLI Source: https://github.com/brotoo25/flutter_fixtures/blob/main/README.md This snippet demonstrates the command-line instruction to add the flutter_fixtures package to your project. ```bash flutter pub add flutter_fixtures ``` -------------------------------- ### Example Fixture JSON File Structure Source: https://github.com/brotoo25/flutter_fixtures/blob/main/README.md This JSON snippet provides an example of a fixture file structure for mocking HTTP responses. It includes a description, multiple values with identifiers, descriptions, default flags, and the actual data. ```json { "description": "Users List", "values": [ { "identifier": "Success", "description": "200", "default": true, "data": {"users": [{"id": 1, "name": "John"}]} }, { "identifier": "Empty", "description": "200", "data": {"users": []} }, { "identifier": "Error", "description": "500", "data": {"error": "Internal Server Error"} } ] } ``` -------------------------------- ### CMake Installation Rules Source: https://github.com/brotoo25/flutter_fixtures/blob/main/example/windows/CMakeLists.txt Configures installation rules for the application executable, support files, and assets. It ensures files are copied next to the executable for in-place execution and handles different build environments like Visual Studio. ```cmake # === Installation === set(BUILD_BUNDLE_DIR "$") set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() # Copy the native assets provided by the build.dart from all packages. set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) # Install the AOT library on non-Debug builds only. install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### Fixture File Structure Example Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_dio/README.md Provides an example JSON structure for fixture files, demonstrating how to define multiple response options with identifiers, descriptions, and data payloads. Includes a 'default' flag for automatic selection. ```json { "description": "User API responses", "values": [ { "identifier": "success", "description": "200 Success", "default": true, "data": { "users": [ {"id": 1, "name": "Alice Johnson", "email": "alice@example.com"}, {"id": 2, "name": "Bob Smith", "email": "bob@example.com"} ] } }, { "identifier": "empty", "description": "200 Empty List", "data": { "users": [] } }, { "identifier": "server_error", "description": "500 Server Error", "data": { "error": "Internal server error", "message": "Something went wrong" } } ] } ``` -------------------------------- ### Complete Flutter Fixtures Example with DataService Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures/README.md This Dart example demonstrates integrating Flutter Fixtures with multiple data sources including HTTP (Dio), databases, and file systems. It sets up a DataService class to handle fetching users via HTTP and from a database, and listing files from the file system, all while utilizing Flutter Fixtures for mocking responses. ```dart import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart'; import 'package:dio/dio.dart'; import 'package:flutter_fixtures/flutter_fixtures.dart'; class DataService { late final Dio _dio; late final DatabaseDataQuery _dbQuery; late final FileSystemDataQuery _fsQuery; DataService() { // HTTP Client with fixtures _dio = Dio(BaseOptions(baseUrl: 'https://api.example.com')); if (kDebugMode) { _dio.interceptors.add( FixturesInterceptor( dataQuery: DioDataQuery(), dataSelector: DataSelectorType.defaultValue(), ), ); } // Database queries with fixtures _dbQuery = DatabaseDataQuery(); // File system operations with fixtures _fsQuery = FileSystemDataQuery(); } // HTTP API calls Future> getUsers() async { final response = await _dio.get('/users'); return (response.data['users'] as List) .map((json) => User.fromJson(json)) .toList(); } // Database queries Future> getUsersFromDatabase() async { final fixture = await _dbQuery.find('SELECT * FROM users'); if (fixture != null) { final collection = await _dbQuery.parse(fixture); if (collection != null) { final document = await _dbQuery.select( collection, null, DataSelectorType.defaultValue() ); if (document != null) { final data = await _dbQuery.data(document); if (data != null) { return (data['users'] as List) .map((json) => User.fromJson(json)) .toList(); } } } } return []; } // File system operations Future> listFiles(String path) async { final fixture = await _fsQuery.find(path); if (fixture != null) { final collection = await _fsQuery.parse(fixture); if (collection != null) { final document = await _fsQuery.select( collection, null, DataSelectorType.defaultValue() ); if (document != null) { final data = await _fsQuery.data(document); if (data != null && data['files'] != null) { return (data['files'] as List) .map((f) => FileInfo.fromJson(f)) .toList(); } } } } return []; } } class User { final int id; final String name; final String email; User({required this.id, required this.name, required this.email}); factory User.fromJson(Map json) => User( id: json['id'], name: json['name'], email: json['email'], ); Map toJson() => { 'id': id, 'name': name, 'email': email, }; } class FileInfo { final String name; final String type; final int size; FileInfo({required this.name, required this.type, required this.size}); factory FileInfo.fromJson(Map json) => FileInfo( name: json['name'], type: json['type'], size: json['size'], ); } ``` -------------------------------- ### Basic Dio Setup with Fixtures Interceptor Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_dio/README.md Demonstrates a basic setup for the Dio HTTP client, including setting a base URL and adding the FixturesInterceptor. This configuration allows mock data to be returned for API requests. ```dart import 'package:dio/dio.dart'; import 'package:flutter_fixtures_dio/flutter_fixtures_dio.dart'; final dio = Dio(BaseOptions(baseUrl: 'https://api.example.com')); // Add the fixtures interceptor dio.interceptors.add( FixturesInterceptor( dataQuery: DioDataQuery(), dataSelector: DataSelectorType.random(), // Randomly select fixtures ), ); // Use Dio as normal - requests will return mock data final response = await dio.get('/users'); print(response.data); // Mock data from fixture file ``` -------------------------------- ### Pull Request Template Structure Source: https://github.com/brotoo25/flutter_fixtures/blob/main/CONTRIBUTING.md A markdown template to guide contributors in providing necessary information for pull requests. It includes sections for description, type of change, testing, and a comprehensive checklist. ```markdown ## Description Brief description of changes ## Type of Change - [ ] Bug fix - [ ] New feature - [ ] Documentation update - [ ] Refactoring - [ ] Other (please describe) ## Testing - [ ] Unit tests added/updated - [ ] Integration tests added/updated - [ ] Manual testing completed ## Checklist - [ ] Code follows project style guidelines - [ ] Self-review completed - [ ] Documentation updated - [ ] Tests pass - [ ] No breaking changes (or clearly documented) ``` -------------------------------- ### CMake Project Setup and Configuration Source: https://github.com/brotoo25/flutter_fixtures/blob/main/example/windows/CMakeLists.txt Initializes the CMake project, sets the minimum version, project name, executable name, and defines build policies. It also handles multi-configuration generators and sets default build types. ```cmake cmake_minimum_required(VERSION 3.14) project(example LANGUAGES CXX) set(BINARY_NAME "example") cmake_policy(VERSION 3.14...3.25) get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) if(IS_MULTICONFIG) set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" CACHE STRING "" FORCE) else() if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() endif() ``` -------------------------------- ### Dart Test Structure for Flutter Fixtures Source: https://github.com/brotoo25/flutter_fixtures/blob/main/CONTRIBUTING.md A standard template for writing unit and integration tests in Dart for the Flutter Fixtures project. Includes setup, grouping, and assertion patterns. ```dart void main() { group('ClassName', () { late ClassName instance; setUp(() { instance = ClassName(); }); group('methodName', () { test('should do something when condition', () { // Arrange // Act // Assert }); }); }); } ``` -------------------------------- ### Fixture Selection Strategies (Dart) Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures/README.md These Dart examples illustrate different strategies for selecting mock data fixtures. You can choose to always use the default fixture, randomly select one, or enable an interactive dialog for user selection. ```dart // Always use the default fixture (marked with "default": true) dataSelector: DataSelectorType.defaultValue() // Randomly select from available fixtures dataSelector: DataSelectorType.random() // Show UI dialog to let users choose dataSelector: DataSelectorType.pick() ``` -------------------------------- ### Example JSON for External Data Files Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_dio/README.md Demonstrates how to structure a JSON fixture file when using external data files for responses. It specifies a description, a list of values, and importantly, the `dataPath` pointing to the actual response data. ```json { "description": "Large user dataset", "values": [ { "identifier": "large_dataset", "description": "200 Success", "default": true, "dataPath": "data/users_large.json" } ] } ``` -------------------------------- ### Utilize FixtureSelector Mixin in Dart Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_core/README.md This example shows how to incorporate the `FixtureSelector` mixin into a class that also implements `DataQuery`. The mixin provides the implementation for the `select` method, simplifying the process of fixture selection logic within the custom data provider. ```dart import 'package:flutter_fixtures_core/flutter_fixtures_core.dart'; class MyDataProvider with FixtureSelector implements DataQuery> { @override Future?> find(String input) async { // Your find implementation return Future.value({}); // Placeholder } @override Future parse(Map source) async { // Your parse implementation return Future.value(null); // Placeholder } @override Future?> data(FixtureDocument document) async { // Your data implementation return Future.value(document.data); // Placeholder } // select() method is provided by the FixtureSelector mixin } ``` -------------------------------- ### Implement Custom Fixtures Dialog Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_ui/README.md Shows how to create a custom dialog by extending FixturesDialogView and overriding the pick method. This example uses AlertDialog to display fixture options with custom styling and selection logic. ```dart class CustomFixturesDialog extends FixturesDialogView { CustomFixturesDialog({required BuildContext context}) : super(context: context); @override Future pick(FixtureCollection fixture) async { return showDialog( context: context, builder: (context) => AlertDialog( title: Text(fixture.description), content: Column( mainAxisSize: MainAxisSize.min, children: fixture.items.map((item) => Card( child: ListTile( leading: Icon(item.defaultOption ? Icons.star : Icons.circle_outlined), title: Text(item.identifier), subtitle: Text(item.description), onTap: () => Navigator.of(context).pop(item), ), ) ).toList(), ), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: Text('Cancel'), ), ], ), ); } } ``` -------------------------------- ### Retrieve Fixture Path from Response Headers in Dart Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures/README.md Retrieves the fixture file path from the 'x-fixture-file-path' response header after making a GET request using Dio. This helps in identifying which fixture was used for a particular API call during debugging. ```dart final response = await dio.get('/users'); final fixturePath = response.headers.value('x-fixture-file-path'); print('Using fixture: $fixturePath'); ``` -------------------------------- ### Configure Flutter Library and Wrappers Source: https://github.com/brotoo25/flutter_fixtures/blob/main/example/windows/flutter/CMakeLists.txt This snippet sets up the Flutter library, including its headers and DLL, and defines static libraries for C++ wrappers used by plugins and the application runner. It links against the main Flutter library and sets include directories and dependencies. ```cmake cmake_minimum_required(VERSION 3.14) set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") # Configuration provided via flutter tool. include(${EPHEMERAL_DIR}/generated_config.cmake) # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") # Set fallback configurations for older versions of the flutter tool. if (NOT DEFINED FLUTTER_TARGET_PLATFORM) set(FLUTTER_TARGET_PLATFORM "windows-x64") endif() # === Flutter Library === set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "flutter_export.h" "flutter_windows.h" "flutter_messenger.h" "flutter_plugin_registrar.h" "flutter_texture_registrar.h" ) list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/') add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") add_dependencies(flutter flutter_assemble) # === Wrapper === list(APPEND CPP_WRAPPER_SOURCES_CORE "core_implementations.cc" "standard_codec.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/') list(APPEND CPP_WRAPPER_SOURCES_PLUGIN "plugin_registrar.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/') list(APPEND CPP_WRAPPER_SOURCES_APP "flutter_engine.cc" "flutter_view_controller.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/') # Wrapper sources needed for a plugin. add_library(flutter_wrapper_plugin STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ) apply_standard_settings(flutter_wrapper_plugin) set_target_properties(flutter_wrapper_plugin PROPERTIES POSITION_INDEPENDENT_CODE ON) set_target_properties(flutter_wrapper_plugin PROPERTIES CXX_VISIBILITY_PRESET hidden) target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) target_include_directories(flutter_wrapper_plugin PUBLIC "${WRAPPER_ROOT}/include" ) add_dependencies(flutter_wrapper_plugin flutter_assemble) # Wrapper sources needed for the runner. add_library(flutter_wrapper_app STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_APP} ) apply_standard_settings(flutter_wrapper_app) target_link_libraries(flutter_wrapper_app PUBLIC flutter) target_include_directories(flutter_wrapper_app PUBLIC "${WRAPPER_ROOT}/include" ) add_dependencies(flutter_wrapper_app flutter_assemble) ``` -------------------------------- ### Implement DataQuery for Custom Data Providers in Dart Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_core/README.md This code demonstrates how to implement the `DataQuery` interface to create a custom data provider, specifically for a database. It shows how to define methods for finding data, parsing it into fixture collections, extracting raw data from a document, and selecting a fixture based on a strategy. Dependencies include the `flutter_fixtures_core` package. ```dart import 'package:flutter_fixtures_core/flutter_fixtures_core.dart'; import 'dart:math'; // Assume Database and DatabaseResult are defined elsewhere class Database {} class DatabaseResult {} class DatabaseDataQuery implements DataQuery> { final Database database; DatabaseDataQuery(this.database); @override Future?> find(String query) async { // Query your database // final result = await database.query('fixtures', where: 'query = ?', whereArgs: [query]); // return result.isNotEmpty ? result.first : null; return Future.value({}); // Placeholder } @override Future parse(Map source) async { // Parse database result into fixture collection return Future.value(FixtureCollection( description: source['description'], items: (source['options'] as List).map((item) => FixtureDocument( identifier: item['id'], description: item['description'], defaultOption: item['is_default'] ?? false, data: item['response_data'], ) ).toList(), )); } @override Future?> data(FixtureDocument document) async { // Return the response data return Future.value(document.data); } @override Future select( FixtureCollection fixture, DataSelectorView? view, DataSelectorType selector, ) async { // Use the FixtureSelector mixin for standard selection logic return switch (selector) { Pick() => view?.pick(fixture), // Assuming view is not null for Pick Default() => fixture.items.firstWhere((item) => item.defaultOption ?? false), Random() => fixture.items[Random().nextInt(fixture.items.length)], }; } } // Mock implementations for compilation class DataSelectorView {} class DataSelectorType { static Pick() => Pick(); static Default() => Default(); static Random() => Random(); } class Pick {} class Default {} class Random {} ``` -------------------------------- ### Manage Flutter Fixtures Development Branches Source: https://github.com/brotoo25/flutter_fixtures/blob/main/CONTRIBUTING.md Commands for creating a new feature branch for development. Essential for organizing changes and contributing to the project. ```bash git checkout -b feature/your-feature-name ``` -------------------------------- ### Run Flutter Tests with Bash Source: https://github.com/brotoo25/flutter_fixtures/blob/main/README.md Provides bash commands to execute tests within a Flutter project. It includes commands for running all tests in the workspace and for running tests in a specific package. ```bash flutter test ``` ```bash flutter test packages/flutter_fixtures_core ``` -------------------------------- ### Run Flutter Fixtures Tests Source: https://github.com/brotoo25/flutter_fixtures/blob/main/CONTRIBUTING.md Commands to execute tests within the Flutter Fixtures project, including running all tests, tests for a specific package, and tests with code coverage. ```bash # All tests flutter test # Specific package flutter test packages/flutter_fixtures_core # With coverage flutter test --coverage ``` -------------------------------- ### Test and Analyze Flutter Fixtures Code Source: https://github.com/brotoo25/flutter_fixtures/blob/main/CONTRIBUTING.md Commands to run all tests and perform code analysis within the Flutter Fixtures project. Crucial for maintaining code quality and identifying potential issues. ```bash flutter test flutter analyze ``` -------------------------------- ### Dart: FixturesDialogView Constructor and Pick Method Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_ui/README.md Demonstrates the constructor for FixturesDialogView, which requires a BuildContext, and the 'pick' method. The 'pick' method displays a dialog with fixture options and returns the user's selection or null if cancelled. Dependencies include flutter_fixtures_core, flutter_fixtures_dio, and flutter_fixtures. ```dart class FixturesDialogView { FixturesDialogView({required BuildContext context}); Future pick(FixtureCollection fixture) { // Implementation to show dialog and return selected fixture } } ``` -------------------------------- ### Instantiate DataSelectorType Strategies in Dart Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_core/README.md Shows how to create instances of different `DataSelectorType` strategies for selecting fixtures. This includes `default()`, `random()`, and `pick()`, which correspond to using the default fixture, selecting randomly, or allowing user selection via a UI respectively. The `pick()` strategy requires a `DataSelectorView` implementation. ```dart // Always use default fixture final defaultSelector = DataSelectorType.defaultValue(); // Randomly select fixture final randomSelector = DataSelectorType.random(); // Let user choose via UI (requires DataSelectorView implementation) final pickSelector = DataSelectorType.pick(); ``` -------------------------------- ### CMake Configuration for Flutter Application Source: https://github.com/brotoo25/flutter_fixtures/blob/main/example/windows/runner/CMakeLists.txt This snippet configures the CMake build system for a Flutter application. It defines the main executable target, lists source files, sets preprocessor definitions for version information, and links necessary libraries and include directories. It also ensures the Flutter build artifacts are included. ```cmake cmake_minimum_required(VERSION 3.14) project(runner LANGUAGES CXX) # Define the application target. To change its name, change BINARY_NAME in the # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer # work. # # Any new source files that you add to the application should be added here. add_executable(${BINARY_NAME} WIN32 "flutter_window.cpp" "main.cpp" "utils.cpp" "win32_window.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" "runner.exe.manifest" ) # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) # Add preprocessor definitions for the build version. target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") # Disable Windows macros that collide with C++ standard library functions. target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") # Add dependency libraries and include directories. Add any application-specific # dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") # Run the Flutter tool portions of the build. This must not be removed. add_dependencies(${BINARY_NAME} flutter_assemble) ``` -------------------------------- ### Flutter Workspace Configuration with YAML Source: https://github.com/brotoo25/flutter_fixtures/blob/main/README.md Shows the YAML configuration for a Flutter workspace, defining the directories that constitute the multi-package project. This is typically found in the root pubspec.yaml file. ```yaml workspace: - packages/flutter_fixtures_core - packages/flutter_fixtures_dio - packages/flutter_fixtures_ui - packages/flutter_fixtures ``` -------------------------------- ### Basic Usage of Flutter Fixtures with Dio Source: https://github.com/brotoo25/flutter_fixtures/blob/main/README.md This Dart snippet shows how to integrate Flutter Fixtures with the Dio HTTP client. It involves creating a Dio instance, adding the `FixturesInterceptor`, and making requests. ```dart import 'package:dio/dio.dart'; import 'package:flutter_fixtures/flutter_fixtures.dart'; // Create a Dio instance final dio = Dio(BaseOptions(baseUrl: 'https://example.com')); // Add the FixturesInterceptor dio.interceptors.add( FixturesInterceptor( dataQuery: DioDataQuery(), dataSelectorView: FixturesDialogView( context: navigatorKey.currentContext!, ), dataSelector: DataSelectorType.random(), ), ); // Make requests as usual final response = await dio.get('/users'); ``` -------------------------------- ### Create FixtureCollection Object in Dart Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_core/README.md Demonstrates the creation of a `FixtureCollection` object, which serves as a container for multiple fixture response options. It includes a description for the collection and a list of `FixtureDocument` objects, each representing a potential fixture response with its identifier, description, and data. ```dart final collection = FixtureCollection( description: 'User API responses', items: [ FixtureDocument( identifier: 'success', description: '200 Success', defaultOption: true, data: {'users': [...]}, ), // ... more fixtures ], ); ``` -------------------------------- ### Flutter Fixtures Pick Selection Mode Source: https://github.com/brotoo25/flutter_fixtures/blob/main/README.md This Dart snippet illustrates how to configure the `FixturesInterceptor` to display a dialog for the user to pick the desired fixture response. ```dart dataSelector: DataSelectorType.pick() ``` -------------------------------- ### Fixture File Structure and Usage Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_dio/README.md Explains the structure of fixture files, including field descriptions and how to use external data files for large responses. Also covers response headers and error handling. ```APIDOC ## Fixture File Structure and Usage ### Description Fixture files define the mock responses for your API endpoints. They consist of a description and an array of possible response values, each with an identifier, description, and the actual data. ### Field Descriptions - **`description`** (String): Human-readable description of the fixture collection. - **`values`** (Array of Objects): Contains different response options for a fixture. - **`identifier`** (String): Unique identifier for a specific response option. - **`description`** (String): Description of the response. The first 3 characters are used as the HTTP status code (e.g., "200 OK"). - **`default`** (Boolean): Indicates if this is the default response option. - **`data`** (Object): The actual response data to be returned. - **`dataPath`** (String, Optional): Path to an external JSON file containing the response data. This path is relative to your fixture folder. ### External Data Files For large response payloads, you can store the data in separate JSON files referenced by `dataPath`. **Example `dataPath` Usage:** ```json { "description": "Large user dataset", "values": [ { "identifier": "large_dataset", "description": "200 Success", "default": true, "dataPath": "data/users_large.json" } ] } ``` **Location:** The file specified in `dataPath` (e.g., `data/users_large.json`) should be located relative to your fixture folder (e.g., `assets/fixtures/data/users_large.json`). ### Response Headers The interceptor automatically adds the `x-fixture-file-path` header to responses when `dataPath` is used, indicating the path to the fixture file. **Example Header Usage:** ```dart final response = await dio.get('/users'); final fixturePath = response.headers.value('x-fixture-file-path'); print('Response from: $fixturePath'); ``` ### Error Handling The interceptor provides specific `DioException` messages for common error scenarios: - **No fixture found**: "No fixture found for request" - **Empty fixture collection**: "No fixture options found for request" - **No fixture selected**: "No fixture selected for request" - **Processing errors**: Detailed error information from fixture processing. ### Integration with UI Components Combine with `flutter_fixtures_ui` for interactive fixture selection. **Example Integration:** ```dart import 'package:flutter_fixtures_ui/flutter_fixtures_ui.dart'; dio.interceptors.add( FixturesInterceptor( dataQuery: DioDataQuery(), dataSelectorView: FixturesDialogView(context: context), dataSelector: DataSelectorType.pick(), // Enables UI selection ), ); ``` ``` -------------------------------- ### Implement Custom DataQuery Interface in Dart Source: https://github.com/brotoo25/flutter_fixtures/blob/main/README.md This Dart snippet shows the structure for creating a custom data provider by implementing the `DataQuery` interface from the `flutter_fixtures_core` package. ```dart class MyCustomDataQuery implements DataQuery { @override Future find(MyInput input) async { // Your implementation } @override Future parse(MyOutput source) async { // Your implementation } @override Future data(FixtureDocument document) async { // Your implementation } @override Future select( FixtureCollection fixture, DataSelectorView? view, DataSelectorType selector, ) async { // You can use the FixtureSelector mixin or implement your own logic } } ``` -------------------------------- ### Flutter Tool Backend Custom Command Source: https://github.com/brotoo25/flutter_fixtures/blob/main/example/windows/flutter/CMakeLists.txt This snippet defines a custom CMake command to invoke the Flutter tool's backend script. It uses a phony output file to ensure the command runs on every build, as it's difficult to determine all inputs and outputs dynamically. This command generates necessary Flutter libraries and headers. ```cmake # === Flutter tool backend === # _phony_ is a non-existent file to force this command to run every time, # since currently there's no way to get a full input/output list from the # flutter tool. set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ${PHONY_OUTPUT} COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" ${FLUTTER_TARGET_PLATFORM} $ VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ) ``` -------------------------------- ### Create Custom UI Component with Dart Source: https://github.com/brotoo25/flutter_fixtures/blob/main/README.md Demonstrates how to implement a custom UI component for fixture selection by extending the DataSelectorView interface in Dart. This allows for custom user interfaces for picking fixtures. ```dart class MyCustomSelectorView implements DataSelectorView { @override Future pick(FixtureCollection fixture) async { // Your custom UI implementation } } ``` -------------------------------- ### CMake Subdirectory and Plugin Integration Source: https://github.com/brotoo25/flutter_fixtures/blob/main/example/windows/CMakeLists.txt Includes subdirectories for Flutter libraries and application runners, and includes generated CMake scripts for managing plugin builds. ```cmake # Flutter library and tool build rules. set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") add_subdirectory(${FLUTTER_MANAGED_DIR}) # Application build; see runner/CMakeLists.txt. add_subdirectory("runner") # Generated plugin build rules, which manage building the plugins and adding # them to the application. include(flutter/generated_plugins.cmake) ``` -------------------------------- ### Commit Changes in Flutter Fixtures Source: https://github.com/brotoo25/flutter_fixtures/blob/main/CONTRIBUTING.md Standard commands for staging all changes and committing them with a descriptive message following Conventional Commits. Ensures consistent commit history. ```bash git add . git commit -m "feat: add your feature description" ``` -------------------------------- ### Add Dependencies to pubspec.yaml Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_ui/README.md Specifies the necessary dependencies for using flutter_fixtures_ui in your Flutter project. Ensure these versions are compatible with your project. ```yaml dependencies: flutter_fixtures_ui: ^0.1.0 flutter_fixtures_dio: ^0.1.0 flutter_fixtures_core: ^0.1.0 ``` -------------------------------- ### Customizing Asset Directory for Fixtures Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_dio/README.md Shows how to configure the DioDataQuery to load fixture files from a custom directory other than the default 'assets/fixtures/'. This provides flexibility in organizing mock data. ```dart dio.interceptors.add( FixturesInterceptor( dataQuery: DioDataQuery(mockFolder: 'assets/my_mocks'), dataSelector: DataSelectorType.random(), ), ); ``` -------------------------------- ### Set Up Dio Interceptor with Fixtures Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_dio/README.md Configure the Dio HTTP client by adding the FixturesInterceptor and specifying a DioDataQuery and a data selection strategy (e.g., random). This enables mock responses for Dio requests. ```dart import 'package:dio/dio.dart'; import 'package:flutter_fixtures_dio/flutter_fixtures_dio.dart'; final dio = Dio(); dio.interceptors.add( FixturesInterceptor( dataQuery: DioDataQuery(), dataSelector: DataSelectorType.random(), ), ); ``` -------------------------------- ### Add Flutter Fixtures Dependency to pubspec.yaml Source: https://github.com/brotoo25/flutter_fixtures/blob/main/README.md This snippet shows how to add the complete flutter_fixtures package as a dependency in your Flutter project's `pubspec.yaml` file. ```yaml dependencies: flutter_fixtures: ^0.1.0 ``` -------------------------------- ### Configure Assets for Fixture Files in pubspec.yaml Source: https://github.com/brotoo25/flutter_fixtures/blob/main/README.md This YAML snippet shows how to declare the `assets/fixtures` directory in your `pubspec.yaml` file so that fixture files can be loaded by the application. ```yaml flutter: assets: - assets/fixtures/ - assets/fixtures/data/ ``` -------------------------------- ### Define User Data Fixture (JSON) Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures/README.md This JSON structure defines mock data scenarios for user data. It includes a 'success' scenario with user lists, an 'empty' scenario with an empty user list, and an 'error' scenario simulating a server error. Each scenario has an identifier, description, and the actual data payload. ```json { "description": "User Data Scenarios", "values": [ { "identifier": "success", "description": "200 Success", "default": true, "data": { "users": [ {"id": 1, "name": "Alice Johnson", "email": "alice@example.com"}, {"id": 2, "name": "Bob Smith", "email": "bob@example.com"} ] } }, { "identifier": "empty", "description": "200 Empty", "data": {"users": []} }, { "identifier": "error", "description": "500 Server Error", "data": {"error": "Internal server error"} } ] } ``` -------------------------------- ### Custom File System Data Provider in Dart Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures/README.md Implements the DataQuery interface for file system operations. It loads fixtures based on file paths, replacing slashes with underscores for naming. The parse method structures file system data into FixtureCollection, and the data method returns file listing information. ```dart class FileSystemDataQuery with FixtureSelector implements DataQuery> { @override Future?> find(String path) async { // Load fixture based on file path return await _loadFixtureFile('filesystem/${path.replaceAll('/', '_')}.json'); } @override Future parse(Map source) async { // Parse file system fixture format return FixtureCollection( description: source['description'], items: (source['values'] as List) .map((option) => FixtureDocument( identifier: option['identifier'] as String, description: option['description'] as String, defaultOption: option['default'] as bool? ?? false, data: option['data'], dataPath: option['dataPath'], )) .toList(), ); } // select() method is provided by the FixtureSelector mixin @override Future?> data(FixtureDocument document) async { // Return file listing data return document.data; } } ``` -------------------------------- ### FixturesInterceptor Configuration Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_dio/README.md Demonstrates how to add the `FixturesInterceptor` to a Dio instance for development and testing purposes. This allows for mocking API responses using local fixture files. ```APIDOC ## FixturesInterceptor Configuration ### Description Add the `FixturesInterceptor` to your Dio instance to enable mocking API responses with local fixture files. This is particularly useful during development and testing. ### Method Interceptor Addition ### Endpoint N/A (Interceptor) ### Parameters #### Constructor Parameters (FixturesInterceptor) - **`dataQuery`** (required, `DataQuery` implementation) - Used for loading and parsing fixture data. - **`dataSelector`** (required, `DataSelector` implementation) - Determines which fixture response to use. - **`dataSelectorView`** (optional, `DataSelectorView`) - UI component for interactive fixture selection. #### Constructor Parameters (DioDataQuery) - **`mockFolder`** (optional, `String`) - The directory within your app assets where fixture files are located. Defaults to `'assets/fixtures'`. ### Request Example ```dart import 'package:dio/dio.dart'; import 'package:flutter_fixtures_dio/flutter_fixtures_dio.dart'; final dio = Dio(); dio.interceptors.add( FixturesInterceptor( dataQuery: DioDataQuery(), dataSelector: DataSelectorType.defaultValue(), // Or DataSelectorType.pick() ), ); ``` ### Response Example N/A (Interceptor modifies responses based on fixtures) ``` -------------------------------- ### Dio Fixture Data Selection Strategies Source: https://github.com/brotoo25/flutter_fixtures/blob/main/packages/flutter_fixtures_dio/README.md Illustrates different strategies for selecting mock data from fixture files using the dataSelector property of FixturesInterceptor. Options include default, random, and user-picked selections. ```dart // Always use the default fixture (marked with "default": true) dataSelector: DataSelectorType.defaultValue() // Randomly select from available fixtures dataSelector: DataSelectorType.random() // Let user pick through UI (requires flutter_fixtures_ui package) dataSelector: DataSelectorType.pick() ```