base_url_switcher 2.0.0 copy "base_url_switcher: ^2.0.0" to clipboard
base_url_switcher: ^2.0.0 copied to clipboard

A Flutter package for switching between base URLs with a beautiful UI switcher

Base URL Switcher #

A beautiful and easy-to-use Flutter package for switching between base URLs with a stunning UI switcher.

pub package License: MIT

Features #

  • ๐Ÿš€ Ultra Simple Usage - Just wrap your widget, that's it!
  • ๐Ÿ” Hidden Access - Tap multiple times to access settings
  • ๐Ÿ”’ Password Protection - Secure access with customizable password
  • ๐ŸŽจ Beautiful UI Switcher - Elegant environment switcher widget
  • ๐Ÿ“ฑ Ready-to-Use Screen - Complete settings page included
  • ๐Ÿ”ง Easy Configuration - Simple setup with default environments
  • ๐Ÿ’พ Persistent Storage - Remembers your environment choice
  • ๐ŸŽฏ Type Safety - Full type safety with Dart
  • ๐Ÿงช Well Tested - Comprehensive test coverage
  • ๐Ÿ“ฑ Responsive Design - Works on all screen sizes
  • ๐Ÿš€ Lightweight - Minimal dependencies

Installation #

Add this to your package's pubspec.yaml file:

dependencies:
  base_url_switcher: ^1.0.0

Then run:

flutter pub get

Quick Start #

1. Initialize the Service #

import 'package:base_url_switcher/base_url_switcher.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Initialize the EnvService
  await EnvService.initialize();
  
  runApp(MyApp());
}

2. Use the Ready-to-Use Screen (Easiest Way) #

import 'package:base_url_switcher/base_url_switcher.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My App'),
          actions: [
            // ุฒุฑ ู„ู„ุฐู‡ุงุจ ุฅู„ู‰ ุตูุญุฉ ุชุจุฏูŠู„ ุงู„ุจูŠุฆุงุช
            IconButton(
              icon: Icon(Icons.settings),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => EnvSwitcherScreen(
                      title: 'Environment Settings',
                      icon: Icons.swap_horiz,
                      primaryColor: Colors.blue,
                      onEnvironmentChanged: (env) {
                        print('Switched to ${env.name}');
                      },
                    ),
                  ),
                );
              },
            ),
          ],
        ),
        body: MyHomePage(),
      ),
    );
  }
}

3. Access Current Base URL (Super Easy) #

import 'package:base_url_switcher/base_url_switcher.dart';

// ุงู„ุญุตูˆู„ ุนู„ู‰ ุงู„ู€ Base URL ุงู„ุญุงู„ูŠ
final currentUrl = BaseUrlManager.instance.currentBaseUrl;
print('Current Base URL: $currentUrl');

// ุงู„ุญุตูˆู„ ุนู„ู‰ ุงุณู… ุงู„ุจูŠุฆุฉ ุงู„ุญุงู„ูŠุฉ
final envName = BaseUrlManager.instance.currentEnvironmentName;
print('Current Environment: $envName');

// ุงุณุชุฎุฏุงู… ุงู„ู€ URL ููŠ API calls
final response = await http.get(
  Uri.parse('${BaseUrlManager.instance.currentBaseUrl}/api/users'),
);

4. Use the Widget (Alternative) #

import 'package:base_url_switcher/base_url_switcher.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My App'),
          actions: [
            // Add environment switcher to app bar
            EnvSwitcher(
              onEnvironmentChanged: (env) {
                print('Switched to ${env.name}');
              },
            ),
          ],
        ),
        body: MyHomePage(),
      ),
    );
  }
}

Default Environments #

The package comes with three default environments:

  • Development - https://dev-api.example.com
  • Staging - https://staging-api.example.com
  • Production - https://api.example.com

Just Wrap Your Widget - That's It! #

import 'package:base_url_switcher/base_url_switcher.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('My App')),
        body: SimpleBaseUrlWrapper(
          // ูู‚ุท wrap ุงู„ู€ body - ุงู„ุจุงู‚ูŠ ุชู„ู‚ุงุฆูŠ!
          child: YourWidget(),
        ),
      ),
    );
  }
}

How It Works: #

  1. Wrap your widget with SimpleBaseUrlWrapper
  2. Tap anywhere 7 times quickly to access settings
  3. Enter password (default: "admin")
  4. Change environment and use the new Base URL

Customize Access: #

SimpleBaseUrlWrapper(
  password: "myapp123", // ุจุงุณูˆุฑุฏ ู…ุฎุตุต
  tapCount: 5, // 5 ุถุบุทุงุช ุจุฏู„ุงู‹ ู…ู† 7
  child: YourWidget(),
)

Show Current Environment: #

AppBar(
  title: Text('My App'),
  actions: [
    EnvironmentIndicator(), // ู…ุคุดุฑ ุงู„ุจูŠุฆุฉ ุงู„ุญุงู„ูŠุฉ
  ],
)

Get Base URL Anywhere: #

// ููŠ ุฃูŠ ู…ูƒุงู† ููŠ ุงู„ุชุทุจูŠู‚
final url = BaseUrlManager.instance.currentBaseUrl;
final response = await http.get(Uri.parse('$url/api/users'));

Alternative Usage #

Add Settings Screen Manually #

// ููŠ ุฃูŠ ู…ูƒุงู† ููŠ ุงู„ุชุทุจูŠู‚
Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => EnvSwitcherScreen(),
  ),
);

Set Your Own Default Base URL #

// ููŠ main() ู‚ุจู„ runApp()
await EnvService.initialize();

// ุฅุถุงูุฉ ุจูŠุฆุฉ ู…ุฎุตุตุฉ ูƒุงูุชุฑุงุถูŠ
final customEnv = BaseUrlManager.createDevelopmentEnv(
  baseUrl: 'https://your-api.com',
  description: 'Your custom API',
);

await BaseUrlManager.instance.addEnvironment(customEnv);
await BaseUrlManager.instance.setEnvironment('Development');

Customization #

Custom Environments #

final envService = EnvService.instance;

// Add custom environment
const customEnv = Environment(
  name: 'Custom',
  baseUrl: 'https://custom-api.com',
  description: 'Custom environment for testing',
  config: {
    'timeout': 30,
    'retries': 3,
  },
);

await envService.addEnvironment(customEnv);

Custom Styling #

EnvSwitcher(
  style: EnvSwitcherStyle(
    backgroundColor: Colors.blue,
    iconColor: Colors.white,
    borderRadius: BorderRadius.circular(12),
    elevation: 4,
    titleTextStyle: TextStyle(
      color: Colors.white,
      fontWeight: FontWeight.bold,
    ),
  ),
  onEnvironmentChanged: (env) {
    // Handle environment change
  },
)

Environment Configuration #

// Set configuration values
await envService.setConfigValue('api_key', 'your-api-key');
await envService.setConfigValue('timeout', 30);

// Get configuration values
final apiKey = envService.getConfigValue<String>('api_key');
final timeout = envService.getConfigValue<int>('timeout');

Advanced Usage #

Programmatic Environment Switching #

// Switch environment programmatically
await envService.setEnvironment('staging');

// Get specific environment
final stagingEnv = envService.getEnvironment('staging');

// Check if environment exists
if (envService.hasEnvironment('custom')) {
  // Do something
}

Environment Management #

// Update existing environment
const updatedEnv = Environment(
  name: 'development',
  baseUrl: 'https://new-dev-api.com',
  description: 'Updated development environment',
);

await envService.updateEnvironment('development', updatedEnv);

// Remove environment
await envService.removeEnvironment('old-environment');

// Reset to defaults
await envService.resetToDefaults();

Show in Release Mode #

By default, the environment switcher only shows in debug mode. To show it in release mode:

EnvSwitcher(
  showInRelease: true, // Show in release mode
  onEnvironmentChanged: (env) {
    // Handle environment change
  },
)

API Reference #

Environment Class #

class Environment {
  final String name;           // Environment name
  final String baseUrl;        // Base URL for API calls
  final Map<String, dynamic> config;  // Additional configuration
  final bool isDefault;        // Whether this is the default environment
  final String? description;   // Optional description
}

EnvService Class #

class EnvService {
  // Singleton instance
  static EnvService get instance;
  
  // Initialize the service
  static Future<void> initialize();
  
  // Environment management
  Map<String, Environment> get environments;
  Environment get currentEnvironment;
  Future<void> setEnvironment(String envName);
  
  // Environment CRUD operations
  Future<void> addEnvironment(Environment environment);
  Future<void> updateEnvironment(String envName, Environment environment);
  Future<void> removeEnvironment(String envName);
  
  // Utility methods
  Environment? getEnvironment(String envName);
  bool hasEnvironment(String envName);
  String get currentBaseUrl;
  String get currentEnvironmentName;
  
  // Configuration management
  T? getConfigValue<T>(String key);
  Future<void> setConfigValue(String key, dynamic value);
  
  // Data management
  Future<void> resetToDefaults();
  Future<void> clear();
}

EnvSwitcher Widget #

class EnvSwitcher extends StatefulWidget {
  final Function(Environment)? onEnvironmentChanged;
  final bool showInRelease;
  final EnvSwitcherStyle? style;
  final bool showDescriptions;
  final IconData? icon;
}

EnvSwitcherStyle Class #

class EnvSwitcherStyle {
  final EdgeInsets margin;
  final EdgeInsets padding;
  final Color backgroundColor;
  final Color iconColor;
  final double iconSize;
  final BorderRadius borderRadius;
  final Border? border;
  final double elevation;
  final TextStyle titleTextStyle;
  final TextStyle descriptionTextStyle;
  final TextStyle dialogTitleStyle;
}

SimpleBaseUrlWrapper Class #

class SimpleBaseUrlWrapper extends StatelessWidget {
  final Widget child;           // Widget to wrap
  final String? password;       // Password for access (default: "admin")
  final int? tapCount;         // Number of taps required (default: 7)
}

BaseUrlWrapper Class #

class BaseUrlWrapper extends StatefulWidget {
  final Widget child;                    // Widget to wrap
  final int tapCount;                    // Number of taps required
  final String password;                 // Password for access
  final String? settingsTitle;           // Settings screen title
  final IconData? settingsIcon;          // Settings screen icon
  final Color? primaryColor;             // Primary color
  final Function(Environment)? onEnvironmentChanged; // Callback
  final bool showInRelease;              // Show in release mode
}

EnvironmentIndicator Class #

class EnvironmentIndicator extends StatelessWidget {
  final Color? color;          // Indicator color
  final double? fontSize;      // Text size
}

EnvironmentInfo Class #

class EnvironmentInfo extends StatelessWidget {
  final bool showBaseUrl;      // Show base URL
  final bool showDescription;  // Show description
  final TextStyle? textStyle;  // Text style
}

Example App #

Check out the example app in the example/ directory to see the package in action.

cd example
flutter run

Testing #

Run the tests:

flutter test

Contributing #

Contributions are welcome! Please feel free to submit a Pull Request.

License #

This project is licensed under the MIT License - see the LICENSE file for details.

Support #

If you find this package helpful, please give it a โญ on pub.dev!

Changelog #

2.0.0 #

  • ๐Ÿš€ Ultra Simple Usage - Just wrap your widget with SimpleBaseUrlWrapper
  • ๐Ÿ” Hidden Access - Tap multiple times to access settings
  • ๐Ÿ”’ Password Protection - Secure access with customizable password
  • ๐Ÿ“ฑ Ready-to-Use Screen - Complete EnvSwitcherScreen included
  • ๐ŸŽฏ Environment Indicator - Show current environment in UI
  • ๐Ÿ“Š Environment Info Widget - Display environment details
  • ๐Ÿ”ง BaseUrlManager - Simplified API for accessing current Base URL
  • ๐ŸŽจ Enhanced UI - Beautiful and responsive design
  • ๐Ÿ“š Comprehensive Examples - Multiple usage examples included

1.0.0 #

  • Initial release
  • Environment management with persistent storage
  • Beautiful UI switcher widget
  • Comprehensive test coverage
  • Full documentation

Made with โค๏ธ for the Flutter community

7
likes
0
points
23
downloads

Publisher

unverified uploader

Weekly Downloads

A Flutter package for switching between base URLs with a beautiful UI switcher

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

flutter, shared_preferences

More

Packages that depend on base_url_switcher