Skip to main content

Environment Configuration

Viax supports multiple environments with different backend configurations. Learn how to switch between local development, staging, and production setups.

Environment Types

Development

Local development with Laragon
  • Backend: localhost
  • Database: Local MySQL
  • Hot reload enabled
  • Debug mode active

Staging

Testing environment
  • Backend: Staging server
  • Database: Test database
  • Mirrors production
  • Safe for testing

Production

Live environment
  • Backend: VPS (76.13.114.194)
  • Database: Production MySQL
  • Optimized builds
  • Real user data

Configuration Architecture

Viax uses a centralized configuration system that automatically detects the environment based on the API base URL.

AppConfig Class

Location: lib/src/core/config/app_config.dart
class AppConfig {
  // Environment variable for API URL
  static const String _envBaseUrl = String.fromEnvironment(
    'API_BASE_URL',
    defaultValue: 'http://76.13.114.194', // Production by default
  );
  
  // Auto-detect environment
  static Environment get environment {
    if (_envBaseUrl.contains('localhost') || 
        _envBaseUrl.contains('10.0.2.2') || 
        _envBaseUrl.contains('192.168.')) {
      return Environment.development;
    } else if (_envBaseUrl.contains('staging')) {
      return Environment.staging;
    }
    return Environment.production;
  }
  
  // Base URL getter
  static String get baseUrl => _envBaseUrl;
  
  // Microservice endpoints
  static String get authServiceUrl => '$baseUrl/auth';
  static String get conductorServiceUrl => '$baseUrl/conductor';
  static String get adminServiceUrl => '$baseUrl/admin';
  static String get userServiceUrl => '$baseUrl/user';
}

Environment Setup

Development (Local)

The Android emulator maps localhost to 10.0.2.2.
flutter run --dart-define=API_BASE_URL=http://10.0.2.2/viax/backend
Full URL structure:
  • Base: http://10.0.2.2/viax/backend
  • Auth: http://10.0.2.2/viax/backend/auth
  • Conductor: http://10.0.2.2/viax/backend/conductor
  • User: http://10.0.2.2/viax/backend/user
  • Admin: http://10.0.2.2/viax/backend/admin

Staging (Optional)

If you have a staging server:
flutter run --dart-define=API_BASE_URL=https://staging.viax.com

Production

Connect to the live VPS server:
# Default - no need to specify
flutter run

# Or explicitly
flutter run --dart-define=API_BASE_URL=http://76.13.114.194

Backend Configuration

Development Backend (Laragon)

File: backend/config/database.php
<?php
class Database {
    private $host = 'localhost';
    private $db_name = 'viax';
    private $username = 'root';
    private $password = 'root';  // Default Laragon password
    private $conn;
    
    public function getConnection() {
        $this->conn = null;
        try {
            $this->conn = new PDO(
                "mysql:host=" . $this->host . ";dbname=" . $this->db_name,
                $this->username,
                $this->password
            );
            $this->conn->exec("set names utf8");
        } catch(PDOException $exception) {
            echo "Connection error: " . $exception->getMessage();
        }
        return $this->conn;
    }
}
?>

Production Backend (VPS)

File: backend/config/database.php
<?php
class Database {
    private $host = 'localhost';  // MySQL on same VPS
    private $db_name = 'viax_production';
    private $username = 'viax_user';
    private $password = 'YOUR_SECURE_PASSWORD_HERE';
    private $conn;
    
    public function getConnection() {
        $this->conn = null;
        try {
            $this->conn = new PDO(
                "mysql:host=" . $this->host . ";dbname=" . $this->db_name,
                $this->username,
                $this->password
            );
            $this->conn->exec("set names utf8mb4");
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $exception) {
            error_log("DB Connection error: " . $exception->getMessage());
            // Don't expose details in production
            throw new Exception("Database connection failed");
        }
        return $this->conn;
    }
}
?>

Environment Variables

Flutter Environment Variables

Viax supports custom configuration through Dart defines:
flutter run \
  --dart-define=API_BASE_URL=http://10.0.2.2/viax/backend \
  --dart-define=MAPBOX_ACCESS_TOKEN=pk.your_token_here \
  --dart-define=TOMTOM_API_KEY=your_key_here
Available Variables:
# Backend URL
API_BASE_URL=http://76.13.114.194

# Website URL for sharing
WEBSITE_URL=https://viaxcol.online
Create configuration files for different environments: config/dev.env:
API_BASE_URL=http://10.0.2.2/viax/backend
ENABLE_DEBUG_LOGS=true
ENABLE_ANALYTICS=false
config/prod.env:
API_BASE_URL=http://76.13.114.194
ENABLE_DEBUG_LOGS=false
ENABLE_ANALYTICS=true
Use with scripts:
# Load and run
source config/dev.env && flutter run --dart-define=API_BASE_URL=$API_BASE_URL

VS Code Launch Configurations

Create .vscode/launch.json for easy environment switching:
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Viax (Development)",
      "request": "launch",
      "type": "dart",
      "program": "lib/main.dart",
      "args": [
        "--dart-define=API_BASE_URL=http://10.0.2.2/viax/backend",
        "--dart-define=ENABLE_DEBUG_LOGS=true"
      ]
    },
    {
      "name": "Viax (Production)",
      "request": "launch",
      "type": "dart",
      "program": "lib/main.dart",
      "args": [
        "--dart-define=API_BASE_URL=http://76.13.114.194",
        "--dart-define=ENABLE_DEBUG_LOGS=false"
      ]
    },
    {
      "name": "Viax (Physical Device - Update IP)",
      "request": "launch",
      "type": "dart",
      "program": "lib/main.dart",
      "args": [
        "--dart-define=API_BASE_URL=http://192.168.1.100/viax/backend"
      ]
    }
  ]
}
Usage:
  1. Press F5 in VS Code
  2. Select configuration from dropdown
  3. App launches with selected environment

Testing Configuration

Verify Backend Connection

Create a simple test to verify your configuration:
// test/config_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:viax/src/core/config/app_config.dart';

void main() {
  test('Backend health check', () async {
    final url = '${AppConfig.baseUrl}/health.php';
    
    try {
      final response = await http.get(Uri.parse(url));
      
      expect(response.statusCode, 200);
      expect(response.body, contains('status'));
      
      print('✅ Backend connected: $url');
      print('Response: ${response.body}');
    } catch (e) {
      fail('❌ Backend connection failed: $e');
    }
  });
  
  test('Environment detection', () {
    print('Current environment: ${AppConfig.environment}');
    print('Base URL: ${AppConfig.baseUrl}');
    print('Auth Service: ${AppConfig.authServiceUrl}');
    
    expect(AppConfig.baseUrl, isNotEmpty);
  });
}
Run test:
flutter test test/config_test.dart

Manual Health Check

Test backend endpoints directly:
curl http://localhost/viax/backend/health.php

# Expected response:
{"status":"ok","timestamp":"2024-11-01 10:30:00"}

URL Structure Reference

Complete URL Mapping

ServiceURL
Basehttp://10.0.2.2/viax/backend
Healthhttp://10.0.2.2/viax/backend/health.php
Auth Loginhttp://10.0.2.2/viax/backend/auth/login.php
Auth Registerhttp://10.0.2.2/viax/backend/auth/register.php
User Profilehttp://10.0.2.2/viax/backend/user/get_profile.php
Driver Profilehttp://10.0.2.2/viax/backend/conductor/get_profile.php
Create Triphttp://10.0.2.2/viax/backend/user/create_trip_request.php
Admin Dashboardhttp://10.0.2.2/viax/backend/admin/dashboard_stats.php

Build Configurations

Development Build

# Debug build with hot reload
flutter run \
  --dart-define=API_BASE_URL=http://10.0.2.2/viax/backend \
  --debug

Staging Build

# Profile build for performance testing
flutter build apk \
  --dart-define=API_BASE_URL=https://staging.viax.com \
  --profile

Production Build

flutter build apk \
  --dart-define=API_BASE_URL=http://76.13.114.194 \
  --release

# Output: build/app/outputs/flutter-apk/app-release.apk

Environment-Specific Features

Debug Mode Features

import 'package:flutter/foundation.dart';
import 'package:viax/src/core/config/app_config.dart';

class DebugFeatures {
  static bool get isDebugMode => kDebugMode;
  static bool get isDevelopment => 
    AppConfig.environment == Environment.development;
  
  static void logApiCall(String endpoint, Map<String, dynamic> params) {
    if (isDebugMode) {
      print('🌐 API Call: $endpoint');
      print('Parameters: $params');
    }
  }
  
  static void logError(String message, [dynamic error, StackTrace? stack]) {
    if (isDebugMode) {
      print('❌ Error: $message');
      if (error != null) print('Details: $error');
      if (stack != null) print('Stack: $stack');
    }
  }
}

Analytics Control

class AppConfig {
  // ... existing code ...
  
  static bool get enableAnalytics {
    return environment == Environment.production;
  }
  
  static bool get enableCrashReporting {
    return environment == Environment.production;
  }
  
  static Duration get connectionTimeout {
    switch (environment) {
      case Environment.development:
        return Duration(seconds: 60); // Longer for debugging
      case Environment.staging:
        return Duration(seconds: 30);
      case Environment.production:
        return Duration(seconds: 15);
    }
  }
}

Troubleshooting

Problem: Can’t connect to localhost from Android emulatorSolution:
  • Use 10.0.2.2 instead of localhost
  • Verify Laragon/backend is running
  • Check firewall settings
# Test from emulator terminal (adb shell)
curl http://10.0.2.2/viax/backend/health.php
Problem: Can’t connect using local IPSolution:
  • Verify same WiFi network
  • Check IP address is correct
  • Disable firewall temporarily to test
  • Use explicit IP, not hostname
# Ping from device
ping 192.168.1.100
Problem: App using wrong environmentSolution:
  • Verify --dart-define syntax
  • Check for typos in URL
  • Print environment in app:
print('Environment: ${AppConfig.environment}');
print('Base URL: ${AppConfig.baseUrl}');
Problem: App still using old base URLSolution:
# Clean and rebuild
flutter clean
flutter pub get
flutter run --dart-define=API_BASE_URL=your_new_url

Best Practices

Never Hardcode URLs

Always use AppConfig.baseUrl instead of hardcoded URLs in your code.

Use Launch Configs

Set up VS Code launch configurations for quick environment switching.

Test All Environments

Test features in development before deploying to production.

Secure Production

Use HTTPS, strong passwords, and proper authentication in production.
Configuration Complete! You can now switch between environments seamlessly and configure Viax for any deployment scenario.

Build docs developers (and LLMs) love