### Install Flutter Library Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt Installs the main Flutter library file to the root installation directory. ```cmake install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Install Application Executable Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt Installs the main application executable to the specified runtime destination. ```cmake install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) ``` -------------------------------- ### Create .env File Example Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Example of a .env file in the project root containing API URL, max retries, and debug flag. ```sh API_URL=https://api.example.com MAX_RETRIES=3 DEBUG=true ``` -------------------------------- ### Install Bundled Plugin Libraries Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt Installs any bundled native libraries provided by plugins to the installation's library directory. ```cmake if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Install Application Bundle Source: https://github.com/java-james/flutter_dotenv/blob/master/example/linux/CMakeLists.txt Configures the installation process to create a relocatable bundle in the build directory. This ensures correct runtime behavior by placing resources in relative locations. ```cmake set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") 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) foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Install Native Assets Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt Copies native assets provided by build.dart from all packages to the installation's library directory. ```cmake set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Environment File Syntax Examples Source: https://context7.com/java-james/flutter_dotenv/llms.txt Illustrates the supported syntax for `.env` files, including comments, quoted values with interpolation and escape sequences, literal values, trimming, and the `export` keyword. ```bash # .env file syntax examples # Comments start with # API_URL=https://api.example.com # Double-quoted values support interpolation and escape sequences BASE_URL=https://api.example.com FULL_URL="$BASE_URL/v1" # => "https://api.example.com/v1" ALT_URL="${BASE_URL}/v2" # => "https://api.example.com/v2" MULTILINE="line1\nline2" # => "line1" + newline + "line2" ESCAPED_QUOTE="He said \"hello\"" # => He said "hello" # Single-quoted values are literal (no interpolation) PRICE='$9.99' # => "$9.99" (literal dollar sign) LITERAL='$BASE_URL/path' # => "$BASE_URL/path" (no substitution) ESCAPED_SINGLE='\'' # => "'" # Unquoted values are trimmed TRIMMED= some value # => "some value" WITH_EQUALS=foo=bar=baz # => "foo=bar=baz" # Escape literal dollar signs in unquoted/double-quoted DOLLARS=\$100 # => "$100" # Export keyword is stripped export EXPORTED_VAR=hello # => key is "EXPORTED_VAR" # Empty values EMPTY= # => "" # JSON values work inside quotes JSON_CONFIG='{"key": "value"}' # => {"key": "value"} ``` -------------------------------- ### Set Installation Prefix for Bundled Files Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt Configures the installation prefix to be next to the executable, supporting in-place execution. This is crucial for Visual Studio builds. ```cmake 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 AOT Library for Release Builds Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt Installs the Ahead-Of-Time (AOT) compilation library, but only for non-Debug builds (Profile and Release configurations). ```cmake install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### Install ICU Data File Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt Installs the ICU data file, which is required for internationalization, to the data directory. ```cmake install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Load Environment Variables in main() Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Load environment variables at the start of your application's main function. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; Future main() async { await dotenv.load(); runApp(const MyApp()); } ``` -------------------------------- ### Add flutter_dotenv Dependency Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Install the flutter_dotenv package using the flutter pub add command. ```sh flutter pub add flutter_dotenv ``` -------------------------------- ### Get String Values from Environment Variables Source: https://context7.com/java-james/flutter_dotenv/llms.txt Retrieve string values from loaded environment variables using `get()` for required values, `maybeGet()` for optional values, or direct map access via `env[]`. Direct map access returns null if the key is missing. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; void fetchConfig() { // Direct map access - returns null if missing String? apiUrl = dotenv.env['API_URL']; // => "https://api.example.com" or null // Required value - throws AssertionError if missing String baseUrl = dotenv.get('BASE_URL'); // Required value with fallback - returns fallback if missing String timeout = dotenv.get('TIMEOUT', fallback: '30'); // Optional value - returns null if missing String? optionalKey = dotenv.maybeGet('OPTIONAL_KEY'); // Optional value with fallback - returns fallback if missing String feature = dotenv.maybeGet('FEATURE_FLAG', fallback: 'disabled') ?? 'disabled'; } ``` -------------------------------- ### Install AOT Library Conditionally with CMake Source: https://github.com/java-james/flutter_dotenv/blob/master/example/linux/CMakeLists.txt Installs the AOT library to the bundle's library directory, but only for non-Debug builds. Ensure the AOT_LIBRARY variable is correctly set before this command. ```cmake if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Get Typed Values (Int, Double, Bool) from Environment Variables Source: https://context7.com/java-james/flutter_dotenv/llms.txt Parse environment variables directly as `int`, `double`, or `bool` types with built-in validation and fallback support. Boolean parsing accepts 'true', 'false', '1', '0' case-insensitively. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; void loadTypedConfig() { // .env file contains: // MAX_RETRIES=5 // RATE_LIMIT=0.75 // DEBUG=true // FEATURE_ENABLED=1 // Integer values - throws AssertionError if missing, FormatException if not parseable int maxRetries = dotenv.getInt('MAX_RETRIES'); // => 5 int timeout = dotenv.getInt('TIMEOUT', fallback: 30); // => 30 (fallback) int negative = dotenv.getInt('NEGATIVE_VAL'); // supports "-42" // Double values double rateLimit = dotenv.getDouble('RATE_LIMIT'); // => 0.75 double defaultRate = dotenv.getDouble('MISSING', fallback: 1.0); // => 1.0 // Boolean values - accepts "true", "false", "1", "0" (case-insensitive) bool debug = dotenv.getBool('DEBUG'); // => true bool featureEnabled = dotenv.getBool('FEATURE_ENABLED'); // => true (from "1") bool safeMode = dotenv.getBool('SAFE_MODE', fallback: false); // => false } ``` -------------------------------- ### Basic .env File Syntax Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Demonstrates the basic syntax for `.env` files, including comments, key-value pairs, quoted values, and variable interpolation. ```sh # Comments start with # KEY=value QUOTED="double quoted value" SINGLE='single quoted value' # Variable interpolation BASE_URL=https://api.example.com FULL_URL=$BASE_URL/v1 ALT_URL=${BASE_URL}/v1 # Prevent interpolation with single quotes PRICE='$9.99' # Newlines in double quotes MULTI="line1\nline2" # The export keyword is stripped automatically export EXPORTED=hello ``` -------------------------------- ### Value Precedence and State Management Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Explains the order in which environment variables are loaded and how to manage the dotenv state. ```APIDOC ## Value Precedence and State Management ### Description Details the order of precedence for environment variables loaded via `load()` and `loadFromString()`, and how to manage the dotenv instance's state. ### Value Precedence Order 1. **mergeWith**: Highest precedence. Programmatic key-value pairs. 2. **Override files / strings**: Values from override files or strings. 3. **Base file / string**: Lowest precedence. Values from the primary .env file or string. ### State Management - **`dotenv.isInitialized`** (bool): `true` after `load()` or `loadFromString()` completes. `false` otherwise. - **`dotenv.clean()`**: Clears all loaded variables and resets `isInitialized` to `false`. Accessing values after `clean()` without a subsequent load will throw `NotInitializedError`. ### Errors - **`NotInitializedError`**: Thrown when accessing values before calling `load()` or `loadFromString()`. - **`FileNotFoundError`**: Thrown when the env file is not found in the asset bundle (only for `load()`). - **`EmptyEnvFileError`**: Thrown when the env file or string is empty. - **`AssertionError`**: Thrown when a required variable is missing and no fallback is provided. - **`FormatException`**: Thrown when a typed getter cannot parse the value. ``` -------------------------------- ### Loading Multiple Environments Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Shows how to layer environment-specific values using override files. ```APIDOC ## POST /load with overrideFiles ### Description Loads environment variables from a base file and optionally overrides them with values from specified override files. ### Method POST ### Endpoint N/A (This is a method call, not a REST endpoint) ### Parameters #### Request Body - **overrideWithFiles** (List) - Required - A list of filenames to use as override files. These files take precedence over the base file. ### Request Example ```dart await dotenv.load(overrideWithFiles: ['.env.staging']); ``` ### Response #### Success Response (200) Environment variables are loaded, with values from `overrideWithFiles` taking precedence. #### Response Example ```dart dotenv.get('API_URL'); // Example: "https://staging.api.example.com" dotenv.get('LOG_LEVEL'); // Example: "debug" ``` ``` -------------------------------- ### Loading Environment Variables from a String Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Demonstrates how to load environment variables directly from a string, which is useful for testing or in-memory configurations. ```APIDOC ## POST /loadFromString ### Description Loads environment variables from a given string. ### Method POST ### Endpoint N/A (This is a method call, not a REST endpoint) ### Parameters #### Request Body - **envString** (String) - Required - The env-formatted string to parse. - **overrideWith** (List) - Optional - Additional env strings that override the base string. - **mergeWith** (Map) - Optional - Programmatic key-value pairs (highest precedence). - **isOptional** (bool) - Optional - When true, an empty string doesn't throw an `EmptyEnvFileError`. - **parser** (Parser) - Optional - Custom parser instance. ### Request Example ```json { "envString": "FOO=bar\nBAZ=qux", "overrideWith": ["OVERRIDE_VAR=override_value"], "mergeWith": {"MERGED_VAR": "merged_value"}, "isOptional": false, "parser": "Parser()" } ``` ### Response #### Success Response (200) No specific response body is detailed, but the environment variables are loaded into the dotenv instance. #### Response Example N/A ``` -------------------------------- ### .env File Syntax Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Describes the syntax rules for creating .env files, including comments, variable interpolation, and quoting. ```APIDOC ## .env File Syntax ### Description Defines the rules and examples for writing environment variables in `.env` files. ### Syntax Rules - Lines starting with `#` are comments, unless inside quoted values. - Lines without an `=` are ignored. - `KEY=value` format is used for defining variables. - Double quotes (`"`) allow for unescaping `\"`, newlines (`\n`), and variable interpolation (`$VAR` or `${VAR}`). - Single quotes (`'`) prevent variable interpolation and unescape `\'`. Escaped single quotes (`\'`) are unescaped. - Use `\$` to represent a literal dollar sign. - Undefined variables interpolate to an empty string. - Unquoted values are trimmed of surrounding whitespace. - The first occurrence of a key wins if it appears multiple times. - The `export` keyword is automatically stripped. - Complex shell expressions are not supported. ### Examples ```sh # This is a comment KEY=value QUOTED="double quoted value with \"escaped quotes\" and \n newlines" SINGLE='single quoted value with \'escaped single quotes\' # Variable interpolation BASE_URL=https://api.example.com FULL_URL=$BASE_URL/v1 ALT_URL=${BASE_URL}/v1 # Prevent interpolation PRICE='$9.99' # Newlines in double quotes MULTI="line1\nline2" # Export keyword export EXPORTED=hello ``` ``` -------------------------------- ### Remote Configuration Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Illustrates how to load environment configurations remotely using a config ID and optionally falling back to cached values. ```APIDOC ## POST /loadRemote ### Description Loads environment variables from a remote configuration source using a provided config ID. Supports using cached data on failure. ### Method POST ### Endpoint N/A (This is a method call, not a REST endpoint) ### Parameters #### Request Body - **configId** (String) - Required - The unique identifier for the remote configuration. - **useCacheOnFailure** (bool) - Optional - If true, uses the last successful configuration as a fallback when remote loading fails. ### Request Example ```dart await dotenv.loadRemote(configId: 'your-config-id', useCacheOnFailure: true); ``` ### Response #### Success Response (200) Environment variables are loaded from the remote source. #### Response Example N/A ``` -------------------------------- ### Multiple Instances Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Explains how to create and manage multiple independent instances of DotEnv for different configurations. ```APIDOC ## Multiple DotEnv Instances ### Description Demonstrates how to create separate `DotEnv` instances to manage distinct sets of environment variables independently. ### Usage Instantiate `DotEnv` for each configuration needed. The package provides a default singleton instance named `dotenv`. ### Example ```dart // Create separate instances final publicConfig = DotEnv(); final featureFlags = DotEnv(); // Load configurations into respective instances await publicConfig.load(fileName: '.env'); await featureFlags.load(fileName: '.env.features'); // Access variables from specific instances String apiUrl = publicConfig.get('API_URL'); bool beta = featureFlags.getBool('BETA_ENABLED', fallback: false); ``` ### Response #### Success Response (200) Each `DotEnv` instance maintains its own state, allowing for isolated management of environment variables. ``` -------------------------------- ### Activate dartdoc Documentation Generator Source: https://github.com/java-james/flutter_dotenv/blob/master/tool/README.md Activates the dartdoc package globally for generating documentation. Ensure ~/.pub_cache/bin is in your PATH. ```sh $ pub global activate dartdoc ``` -------------------------------- ### Create and Load Multiple Dotenv Instances Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Instantiate multiple `DotEnv` objects to manage independent configurations. Each instance maintains its own state, allowing for distinct sets of environment variables. ```dart final publicConfig = DotEnv(); final featureFlags = DotEnv(); await publicConfig.load(fileName: '.env'); await featureFlags.load(fileName: '.env.features'); String apiUrl = publicConfig.get('API_URL'); bool beta = featureFlags.getBool('BETA_ENABLED', fallback: false); ``` -------------------------------- ### Create and Manage Multiple DotEnv Instances Source: https://context7.com/java-james/flutter_dotenv/llms.txt Instantiate multiple `DotEnv` objects to manage separate configurations independently. Each instance maintains its own state, allowing for distinct loading and cleaning operations without affecting others. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; Future main() async { // Create separate instances for different configs final publicConfig = DotEnv(); final featureFlags = DotEnv(); final apiConfig = DotEnv(); // Load different env files into each instance await publicConfig.load(fileName: '.env'); await featureFlags.load(fileName: '.env.features'); await apiConfig.load(fileName: '.env.api'); // Each instance maintains independent state String apiUrl = publicConfig.get('API_URL'); bool betaEnabled = featureFlags.getBool('BETA_ENABLED', fallback: false); int rateLimit = apiConfig.getInt('RATE_LIMIT', fallback: 100); // Clean one instance without affecting others featureFlags.clean(); print(publicConfig.isInitialized); // => true (unaffected) print(featureFlags.isInitialized); // => false } ``` -------------------------------- ### Find and Check GTK, GLIB, and GIO Modules in CMake Source: https://github.com/java-james/flutter_dotenv/blob/master/example/linux/flutter/CMakeLists.txt Uses PkgConfig to find and check for required GTK, GLIB, and GIO modules. This ensures the necessary libraries are available for the build. ```cmake find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) ``` -------------------------------- ### Apply Standard Build Settings Source: https://github.com/java-james/flutter_dotenv/blob/master/example/linux/CMakeLists.txt Applies standard compilation features and options to a target. Use with caution as plugins use this by default; add new options to specific targets when possible. ```cmake function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_14) target_compile_options(${TARGET} PRIVATE -Wall -Werror) target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") endfunction() ``` -------------------------------- ### Link Libraries and Include Directories Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/runner/CMakeLists.txt Links necessary libraries (flutter, flutter_wrapper_app, dwmapi.lib) and sets include directories for the application target. Add any other application-specific dependencies here. ```cmake # 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}") ``` -------------------------------- ### Apply Standard Build Settings Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/runner/CMakeLists.txt Applies a standard set of build settings to the application target. This can be removed or modified if custom build settings are required. ```cmake # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) ``` -------------------------------- ### Enable Unicode Support Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt Adds definitions to enable Unicode support for all projects. Use this for cross-platform compatibility. ```cmake add_definitions(-DUNICODE -D_UNICODE) ``` -------------------------------- ### Link Dependencies Source: https://github.com/java-james/flutter_dotenv/blob/master/example/linux/CMakeLists.txt Links necessary libraries to the application target. Add any application-specific dependencies here. ```cmake target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) ``` -------------------------------- ### Configure Build Configurations Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt Sets the available build configurations (Debug, Profile, Release) based on whether the generator supports multi-configuration builds. ```cmake 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() ``` -------------------------------- ### Activate dart_style Formatter Source: https://github.com/java-james/flutter_dotenv/blob/master/tool/README.md Activates the dart_style package globally for code formatting. Ensure ~/.pub_cache/bin is in your PATH. ```sh $ pub global activate dart_style ``` -------------------------------- ### Opt-in to Modern CMake Behaviors Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt Explicitly enables modern CMake behaviors to avoid warnings with recent CMake versions. Recommended for compatibility. ```cmake cmake_policy(VERSION 3.14...3.25) ``` -------------------------------- ### Load Environment Variables with Options Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Load variables from a specified asset file, override with additional files, merge programmatically, and optionally ignore file not found errors. ```dart await dotenv.load( fileName: '.env', overrideWithFiles: ['.env.staging'], mergeWith: {'BUILD': 'ci'}, isOptional: false, ); ``` -------------------------------- ### Handle EmptyEnvFileError Source: https://context7.com/java-james/flutter_dotenv/llms.txt Catch EmptyEnvFileError when attempting to load an empty environment file or string. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; Future main() async { // EmptyEnvFileError - empty file or string try { dotenv.loadFromString(envString: ''); } on EmptyEnvFileError catch (e) { print('Empty env: $e'); } // ... rest of main } ``` -------------------------------- ### Register .env as Asset in pubspec.yaml Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Register the .env file as an asset in your pubspec.yaml file. ```yaml flutter: assets: - .env ``` -------------------------------- ### Configure C++ Wrapper for Plugins Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/flutter/CMakeLists.txt Builds a static C++ wrapper library for Flutter plugins, including core and plugin-specific sources. Ensures position-independent code and hidden visibility. ```cmake 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}/") # 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) ``` -------------------------------- ### Load Environment Variables with Overrides Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Load environment variables from multiple files, where later files in the list override earlier ones. Ensure all env files are registered as assets in `pubspec.yaml`. ```dart await dotenv.load(overrideWithFiles: ['.env.staging']); dotenv.get('API_URL'); // => "https://staging.api.example.com" dotenv.get('LOG_LEVEL'); // => "debug" ``` -------------------------------- ### Flutter Tool Backend Custom Command Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/flutter/CMakeLists.txt Defines a custom command to execute the Flutter tool backend script for assembling build artifacts. Uses a phony target to ensure execution on every build. ```cmake # _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} ) ``` -------------------------------- ### Validate Required Environment Variables Source: https://context7.com/java-james/flutter_dotenv/llms.txt Ensure all necessary environment variables are defined and have non-empty values before application startup. This prevents runtime errors due to missing configurations. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; Future main() async { await dotenv.load(); // Define required variables for your application const requiredVars = ['API_URL', 'API_KEY', 'MAX_RETRIES']; // Check if all required variables are defined with non-empty values if (!dotenv.isEveryDefined(requiredVars)) { throw Exception('Missing required environment variables. ' 'Ensure all of $requiredVars are defined in your .env file.'); } // Safe to proceed - all required vars are present final apiUrl = dotenv.get('API_URL'); final apiKey = dotenv.get('API_KEY'); final retries = dotenv.getInt('MAX_RETRIES'); runApp(MyApp(apiUrl: apiUrl, apiKey: apiKey, retries: retries)); } ``` -------------------------------- ### Configure C++ Wrapper for Runner Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/flutter/CMakeLists.txt Builds a static C++ wrapper library for the Flutter runner application, including core and application-specific sources. Links against the Flutter library. ```cmake 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_APP "flutter_engine.cc" "flutter_view_controller.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") # 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) ``` -------------------------------- ### Check and Manage DotEnv Initialization State Source: https://context7.com/java-james/flutter_dotenv/llms.txt Verify if the dotenv instance has been initialized and use `clean()` to reset its state, allowing for reloading configurations. Accessing environment variables before initialization will throw a `NotInitializedError`. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; void manageState() { // Check if dotenv has been loaded print(dotenv.isInitialized); // => false (before load) dotenv.loadFromString(envString: 'FOO=bar'); print(dotenv.isInitialized); // => true print(dotenv.env['FOO']); // => "bar" // Clear all loaded variables and reset state dotenv.clean(); print(dotenv.isInitialized); // => false // Accessing env after clean() throws NotInitializedError try { var value = dotenv.env['FOO']; } on NotInitializedError catch (e) { print(e); // => "NotInitializedError: DotEnv has not been initialized..." } // Reload with new configuration dotenv.loadFromString(envString: 'BAZ=qux'); print(dotenv.env['BAZ']); // => "qux" print(dotenv.env['FOO']); // => null (previous state cleared) } ``` -------------------------------- ### Define Executable Name Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt Sets the name of the application's executable. This name will be used on disk. ```cmake set(BINARY_NAME "example") ``` -------------------------------- ### Set Project and Minimum CMake Version Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt Specifies the minimum required CMake version and the project name. Ensure your CMake version meets this requirement. ```cmake cmake_minimum_required(VERSION 3.14) project(example LANGUAGES CXX) ``` -------------------------------- ### Load Environment Variables from String Source: https://context7.com/java-james/flutter_dotenv/llms.txt Load environment variables directly from a string, useful for testing or in-memory configuration. Supports overrides and merged values. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; void main() { // Basic string loading dotenv.loadFromString(envString: 'API_URL=https://api.example.com\nDEBUG=true'); // With overrides and merged values dotenv.loadFromString( envString: 'API_URL=https://api.example.com\nLOG_LEVEL=warning', overrideWith: ['API_URL=https://staging.api.example.com\nLOG_LEVEL=debug'], mergeWith: {'VERSION': '1.0.0'}, isOptional: false, ); print(dotenv.env['API_URL']); // => "https://staging.api.example.com" print(dotenv.env['LOG_LEVEL']); // => "debug" print(dotenv.env['VERSION']); // => "1.0.0" } ``` -------------------------------- ### Load Environment Variables from String Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Use `loadFromString` to load environment variables directly from a string. This is particularly useful for testing or in-memory configurations. ```dart dotenv.loadFromString(envString: 'FOO=bar BAZ=qux'); ``` -------------------------------- ### Define Application Target Source: https://github.com/java-james/flutter_dotenv/blob/master/example/linux/CMakeLists.txt Defines the main executable target for the application. Ensure BINARY_NAME matches the executable name for `flutter run` to function correctly. Add any new source files here. ```cmake add_executable(${BINARY_NAME} "main.cc" "my_application.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) ``` -------------------------------- ### Load Remote Configuration Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Load environment configurations remotely using a config ID. Supports using the last successful config as a local fallback if remote loading fails. ```dart await dotenv.loadRemote( configId: 'your-config-id', useCacheOnFailure: true, ); ``` -------------------------------- ### Release Script Source: https://github.com/java-james/flutter_dotenv/blob/master/tool/README.md A script for managing project releases, typically involving git tagging and publishing to pub. ```sh `git tag` and `pub publish`. ``` -------------------------------- ### Define Profile Build Mode Settings Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt Sets linker and compiler flags for the Profile build mode, typically inheriting from Release settings. ```cmake set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") ``` -------------------------------- ### Custom Command for Flutter Tool Backend in CMake Source: https://github.com/java-james/flutter_dotenv/blob/master/example/linux/flutter/CMakeLists.txt A custom CMake command to execute the Flutter tool backend script. It's configured to run every time by using a phony output target, as a full input/output list is not available. ```cmake add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/_phony_ COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} VERBATIM ) ``` -------------------------------- ### Load Environment Variables with Override Files Source: https://context7.com/java-james/flutter_dotenv/llms.txt Layer environment-specific values over a shared base configuration using override files. Ensure your .env files are listed in pubspec.yaml assets. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; // .env (base) // API_URL=https://api.example.com // LOG_LEVEL=warning // TIMEOUT=30 // .env.staging // API_URL=https://staging.api.example.com // LOG_LEVEL=debug // .env.production // API_URL=https://prod.api.example.com // LOG_LEVEL=error Future main() async { const environment = String.fromEnvironment('ENV', defaultValue: 'staging'); await dotenv.load( fileName: '.env', overrideWithFiles: ['.env.$environment'], isOptional: true, // Don't throw if override file missing ); // With staging environment: print(dotenv.get('API_URL')); // => "https://staging.api.example.com" print(dotenv.get('LOG_LEVEL')); // => "debug" print(dotenv.get('TIMEOUT')); // => "30" (from base, not overridden) runApp(const MyApp()); } // pubspec.yaml: // flutter: // assets: // - .env // - .env.staging // - .env.production ``` -------------------------------- ### Define Executable Target Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/runner/CMakeLists.txt Defines the main executable for the Flutter Windows application. Ensure BINARY_NAME is consistent with the top-level CMakeLists.txt for `flutter run` compatibility. Add all application source files here. ```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 Standard Compilation Settings Function Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt A reusable function to apply common compilation features and options to a target. Avoid adding new options here unless necessary for all targets. ```cmake function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_17) target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") target_compile_options(${TARGET} PRIVATE /EHsc) target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") endfunction() ``` -------------------------------- ### Manage Flutter Assets Directory Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt Ensures the Flutter assets directory is correctly copied and updated on each build. It removes the old directory before copying new assets. ```cmake 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) ``` -------------------------------- ### Load Environment Variables from Asset File Source: https://context7.com/java-james/flutter_dotenv/llms.txt Load environment variables from a `.env` file registered as a Flutter asset. The `load()` method is async and should be called in `main()` before `runApp()`. Ensure your `.env` files are listed in `pubspec.yaml` under the `assets` section. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; Future main() async { // Basic loading from default .env file await dotenv.load(); // Load from custom path with override files and merged values await dotenv.load( fileName: 'assets/.env', overrideWithFiles: ['assets/.env.staging'], mergeWith: {'BUILD_NUMBER': '42'}, isOptional: false, ); runApp(const MyApp()); } // pubspec.yaml configuration required: // flutter: // assets: // - .env // - assets/.env // - assets/.env.staging ``` -------------------------------- ### Include Flutter Generated Plugins Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/CMakeLists.txt Includes the CMake script that manages building and adding generated plugins to the application. ```cmake include(flutter/generated_plugins.cmake) ``` -------------------------------- ### Add Version Preprocessor Definitions Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/runner/CMakeLists.txt Adds preprocessor definitions for the build version, including major, minor, patch, and build numbers. These are useful for embedding version information into the application. ```cmake # 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}") ``` -------------------------------- ### Use isOptional to Suppress Loading Errors Source: https://context7.com/java-james/flutter_dotenv/llms.txt Use the isOptional flag to prevent errors if an environment file is missing or empty. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; Future main() async { // Use isOptional to suppress file/empty errors await dotenv.load( fileName: 'optional.env', isOptional: true, // No error if missing or empty ); // ... rest of main } ``` -------------------------------- ### Define Flutter Library Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/flutter/CMakeLists.txt Defines the Flutter library interface and includes necessary headers. Links against the Flutter library DLL. ```cmake 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) ``` -------------------------------- ### Define List Prepend Function in CMake Source: https://github.com/java-james/flutter_dotenv/blob/master/example/linux/flutter/CMakeLists.txt This custom CMake function mimics `list(TRANSFORM ... PREPEND ...)` for older CMake versions (3.10). It prepends a prefix to each element in a given list. ```cmake function(list_prepend LIST_NAME PREFIX) set(NEW_LIST "") foreach(element ${${LIST_NAME}}) list(APPEND NEW_LIST "${PREFIX}${element}") endforeach(element) set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) endfunction() ``` -------------------------------- ### Access Environment Variables Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Access loaded environment variables using dotenv.get(), dotenv.getInt(), and dotenv.getBool(). Provide fallback values for optional variables. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; // Inside a function, widget, or service — not as a top-level initializer final apiUrl = dotenv.get('API_URL'); final retries = dotenv.getInt('MAX_RETRIES', fallback: 1); final debug = dotenv.getBool('DEBUG', fallback: false); ``` -------------------------------- ### Handle FileNotFoundError Source: https://context7.com/java-james/flutter_dotenv/llms.txt Catch FileNotFoundError if the specified .env file is not found in the assets. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; Future main() async { // FileNotFoundError - env file not in assets try { await dotenv.load(fileName: 'missing.env'); } on FileNotFoundError catch (e) { print('File not found: $e'); } // ... rest of main } ``` -------------------------------- ### Custom Parsing with Parser Class Source: https://context7.com/java-james/flutter_dotenv/llms.txt Use the Parser class for custom parsing needs, including multi-line parsing into a map, single-line parsing, and interpolation with an existing environment map. Ensure the Parser class is imported. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; void customParsing() { const parser = Parser(); // Parse multiple lines into a map final envMap = parser.parse([ '# Configuration', 'FOO=bar', 'BAZ=qux', 'INTERPOLATED=$$FOO-$$BAZ', // => "bar-qux" ]); print(envMap); // => {FOO: bar, BAZ: qux, INTERPOLATED: bar-qux} // Parse a single line final single = parser.parseOne('export API_KEY="secret123"'); print(single); // => {API_KEY: secret123} // Parse with existing environment for interpolation final withEnv = parser.parseOne( 'FULL_URL=$$BASE/api', envMap: {'BASE': 'https://example.com'}, ); print(withEnv); // => {FULL_URL: https://example.com/api} // Variable interpolation final interpolated = parser.interpolate( r'Hello $NAME, your ID is ${USER_ID}', {'NAME': 'Alice', 'USER_ID': '12345'}, ); print(interpolated); // => "Hello Alice, your ID is 12345" // Utility methods print(parser.trimExportKeyword('export FOO=bar')); // => "FOO=bar" print(parser.removeCommentsFromLine('value # comment')); // => "value" print(parser.removeSurroundingQuotes('"quoted"')); // => "quoted" print(parser.getSurroundingQuoteCharacter("'single'")); // => "'" } ``` -------------------------------- ### Merge System Environment Variables with .env Source: https://context7.com/java-james/flutter_dotenv/llms.txt On platforms with dart:io support, merge system environment variables with your .env file. System environment variables have the highest priority. ```dart import 'dart:io' show Platform; import 'package:flutter_dotenv/flutter_dotenv.dart'; // .env file: // API_URL=https://api.example.com // CLIENT_URL=https://$CLIENT_ID.dev.example.com Future main() async { // Merge Platform.environment with .env values // mergeWith values have highest priority await dotenv.load( fileName: '.env', mergeWith: Platform.environment, ); // If CLIENT_ID is set in system environment to "acme": // CLIENT_URL => "https://acme.dev.example.com" // System env vars override .env file values // Priority: mergeWith > overrideWithFiles > base fileName runApp(const MyApp()); } ``` -------------------------------- ### Typed Getters for Environment Variables Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Use typed getters like getInt, getDouble, and getBool to parse environment variable values directly. Provide fallback values to avoid errors for missing variables. ```dart final retries = dotenv.getInt('MAX_RETRIES', fallback: 3); final rate = dotenv.getDouble('RATE', fallback: 0.5); final debug = dotenv.getBool('DEBUG', fallback: false); ``` -------------------------------- ### Handle NotInitializedError Source: https://context7.com/java-james/flutter_dotenv/llms.txt Catch NotInitializedError when accessing environment variables before calling dotenv.load(). ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; Future main() async { // NotInitializedError - accessing before load try { var value = dotenv.env['KEY']; } on NotInitializedError catch (e) { print('Must call load() first: $e'); } // ... rest of main } ``` -------------------------------- ### Merge System Environment Variables Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Use this to merge system environment variables into dotenv. Platform.environment is not available on Flutter web. Merged values take precedence over values declared in the env file. ```dart import 'dart:io' show Platform; await dotenv.load(mergeWith: Platform.environment); ``` -------------------------------- ### Add Flutter Assemble Dependency Source: https://github.com/java-james/flutter_dotenv/blob/master/example/windows/runner/CMakeLists.txt Ensures that the Flutter tool's assembly process is completed before the application target is built. This is a mandatory step for Flutter applications. ```cmake # Run the Flutter tool portions of the build. This must not be removed. add_dependencies(${BINARY_NAME} flutter_assemble) ``` -------------------------------- ### Handle FormatException for Type Parsing Source: https://context7.com/java-james/flutter_dotenv/llms.txt Catch FormatException when attempting to parse an environment variable value into an integer and the value is not a valid integer. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; Future main() async { // FormatException - type parsing failure dotenv.loadFromString(envString: 'NOT_A_NUMBER=abc'); try { int value = dotenv.getInt('NOT_A_NUMBER'); } on FormatException catch (e) { print('Cannot parse as int: $e'); } // ... rest of main } ``` -------------------------------- ### Configure Flutter Library Target in CMake Source: https://github.com/java-james/flutter_dotenv/blob/master/example/linux/flutter/CMakeLists.txt Defines an INTERFACE library target for Flutter, setting include directories and linking against system libraries (GTK, GLIB, GIO) and the Flutter engine library. ```cmake add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") target_link_libraries(flutter INTERFACE PkgConfig::GTK PkgConfig::GLIB PkgConfig::GIO ) add_dependencies(flutter flutter_assemble) ``` -------------------------------- ### Validate Required Environment Variables Source: https://github.com/java-james/flutter_dotenv/blob/master/README.md Check if all required environment variables are defined using isEveryDefined(). This method returns true only if every listed variable exists with a non-empty value. ```dart const required = ['API_URL', 'MAX_RETRIES']; if (!dotenv.isEveryDefined(required)) { throw Exception('Missing required env variables'); } ``` -------------------------------- ### Create Flutter Assemble Custom Target in CMake Source: https://github.com/java-james/flutter_dotenv/blob/master/example/linux/flutter/CMakeLists.txt Defines a custom target 'flutter_assemble' that depends on the Flutter library and its headers. This target ensures these components are built. ```cmake add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ) ``` -------------------------------- ### Handle AssertionError for Missing Variables Source: https://context7.com/java-james/flutter_dotenv/llms.txt Catch AssertionError when trying to access a required environment variable that is not defined. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; Future main() async { // AssertionError - missing required variable dotenv.loadFromString(envString: 'FOO=bar'); try { var missing = dotenv.get('MISSING_VAR'); // No fallback provided } on AssertionError catch (e) { print('Missing required var: $e'); } // ... rest of main } ```