GetX Scaffold

repository·master·Indexed 42 days ago

https://github.com/kxmrg/flutter_getx_scaffold

A rapid development framework for Flutter built on GetX, Dio, and ScreenUtil. It provides pre-configured templates, global utility methods, and standardized implementations for themes, internationalization, and network requests. Key features include the HttpService wrapper for Dio, LoadContainer for state management, optimized UI widgets (TextX, ButtonX, IconX), and a comprehensive set of utility classes for encryption, date formatting, and permission handling.

Tokens
21.6K
Snippets
83
Records
92
Agent score
53%

What's inside GetX Scaffold

  1. Implement LoadContainer for state management

    master

    The LoadContainer widget manages three built-in states: loading, network error, and empty data. You control these states via a LoadController (which uses BaseControllerMixin).

    To use it:

    1. Create a LoadController and instantiate a LoadController? property.
    2. Use loadController?.loading(), loadController?.error(), or loadController?.empty() to trigger state changes.
    3. Wrap your content in a LoadContainer and provide the onReLoad callback.

    Each state's widget can be customized.

    // Controller implementation
    class LoadContainerController extends GetxController with BaseControllerMixin {
      @override
      String get builderId => 'loadContainer';
    
      LoadController? loadController = LoadController();
    
      void onLoad() {
        loadController?.loading();
        // Perform logic then call complete()
        loadController?.complete();
      }
    
      void onEmpty() {
        loadController?.loading();
        loadController?.empty();
      }
    
      void onError() {
        loadController?.loading();
        loadController?.error();
      }
    }
    
    // Widget implementation
    LoadContainer(
      controller: controller.loadController!,
      onReLoad: controller.onLoad,
      child: _buildView(),
    )
  2. Create pages using GetView and BaseControllerMixin

    master

    The scaffold follows a pattern of separating view and logic.

    1. View: Extend GetView<TController>. Use GetBuilder<TController> in the build method, ensuring the id matches the controller's builderId.
    2. Controller: Extend GetxController and mix in BaseControllerMixin.

    Important: You must override String get builderId in your controller to match the id used in the GetBuilder in your view. This enables targeted UI updates via updateUi().

    // Controller
    class HomeController extends GetxController with BaseControllerMixin {
      @override
      String get builderId => 'home';
    
      @override
      void onInit() {
        super.onInit();
        updateUi(); // Refreshes the UI for this builderId
      }
    }
    
    // View
    class HomePage extends GetView<HomeController> {
      @override
      Widget build(BuildContext context) {
        return GetBuilder<HomeController>(
          init: HomeController(),
          id: 'home', // Must match controller's builderId
          builder: (_) {
            return Scaffold(body: Text('Hello'));
          },
        );
      }
    }
  3. Manage Android permissions with GetX Scaffold

    master

    GetX Scaffold provides encapsulated global methods to handle permission requests, specifically addressing requirements in many Chinese Android app markets that mandate showing a reason to the user before requesting permission.

    It simplifies the process by:

    1. Providing a way to show a rationale/message before the system permission dialog.
    2. Abstracting complex permissions (like photo gallery access) that vary across different Android SDK versions into single, unified methods.

    Note: You must configure the required permissions in your platform-specific configuration files (e.g., AndroidManifest.xml) before calling these methods. This package is built upon permission_handler.

    import 'package:getx_scaffold/getx_scaffold.dart';
    
    // 1. Request specific common permissions
    await requestCameraPermission();
    await requestPhotosPermission();
    
    // 2. Request custom permissions with a rationale message
    var result = await requestPermission(
      permission: Permission.microphone,
      message: 'We need access to your microphone for recording.',
      error: 'Please authorize microphone permission',
    );
    
    if (result) {
      // Permission granted
    }
  4. Implement internationalization with TranslationLibrary

    master

    To implement internationalization, create a class that extends Translations. You must define fallbackLocale, supportedLocales, the keys map (mapping locale codes to translation maps), and the localizationsDelegates required for Flutter's localization system.

    import 'package:flutter_localizations/flutter_localizations.dart';
    import 'package:getx_scaffold/getx_scaffold.dart';
    
    class TranslationLibrary extends Translations {
      static const fallbackLocale = Locale('zh', 'CN');
    
      static const supportedLocales = [
        Locale('zh', 'CN'),
        Locale('en', 'US'),
        Locale('es', 'ES'),
      ];
    
      @override
      Map<String, Map<String, String>> get keys => {
            'zh': zh,
            'en': en,
            'es': es,
          };
    
      static const localizationsDelegates = [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ];
    }
  5. Use optimized UI widgets in GetX Scaffold

    master

    GetX Scaffold provides a collection of optimized, pre-styled widgets to speed up UI development. It is not a full UI library, but a wrapper for common components.

    Key widget categories include:

    • TextX: Specialized text widgets with predefined typography styles (e.g., displayLarge, headlineMedium, titleSmall, bodyLarge) and weight support.
    • RichTextX: For creating clickable rich text using TextSpanItem.
    • TextTag: For styled tags/labels with support for outline and custom color.
    • ButtonX: Various button styles including primary, outline, icon, and text.
    • IconX: Support for standard icons, Ant Design icons (AntdIcon), SVGs, and images with built-in badge and background support.
    • NavigationX: A bottom navigation bar component using NavigationItemModel for items.
    • SpinKit: Integrated loading animations (e.g., SpinKitFoldingCube, SpinKitDoubleBounce).
    • ImageX: Simplified image loading from URLs with radius support.
    // Example of using TextX and ButtonX
    TextX.displayLarge('DisplayLarge'),
    ButtonX.primary(
      'Primary',
      onPressed: () {},
    ),
  6. Define application themes

    master

    The scaffold recommends using Material 2 for theme configuration to avoid Material 3 coloring issues. You can define light and dark ThemeData in a class. Once defined, you can access theme colors throughout the app using the ThemeColor utility class (e.g., ThemeColor.onPrimary, ThemeColor.onSurface).

    import 'package:flutter/material.dart';
    
    class AppTheme {
      static const Color themeColor = Color.fromARGB(255, 11, 107, 47);
      static const Color darkThemeColor = Color.fromARGB(255, 12, 16, 121);
    
      static ThemeData light = ThemeData(
        useMaterial3: false,
        colorScheme: ColorScheme.fromSeed(
          seedColor: themeColor,
          brightness: Brightness.light,
        ),
        // ... other theme settings
      );
    
      static ThemeData dark = ThemeData(
        useMaterial3: false,
        colorScheme: ColorScheme.fromSeed(
          seedColor: darkThemeColor,
          brightness: Brightness.dark,
        ),
        // ... other theme settings
      );
    }
  7. Install GetX Scaffold

    master

    To use GetX Scaffold in your Flutter project, add the following dependencies to your pubspec.yaml file:

    dependencies:
      getx_scaffold: ^0.0.1
    
      # Required if your project needs internationalization
      flutter_localizations:
        sdk: flutter
    dependencies:
      getx_scaffold: ^0.0.1
    
      # If your project needs internationalization, please add the following dependency.
      flutter_localizations:
        sdk: flutter
  8. Customize the iOS launch screen assets

    master

    To change the launch screen image for the iOS version of your Flutter application, you can use one of two methods:

    1. Direct File Replacement: Replace the existing image files directly within the example/ios/Runner/Assets.xcassets/LaunchImage.imageset/ directory with your own assets.
    2. Xcode Interface:
      • Open the iOS project in Xcode by running open ios/Runner.xcworkspace from your terminal.
      • In the Xcode Project Navigator, navigate to Runner/Assets.xcassets.
      • Drag and drop your desired images into the asset catalog to replace the existing ones.
    open ios/Runner.xcworkspace
  9. Initialize GetXScaffold in main.dart

    master

    Initialize the scaffold using the init() function before calling runApp(). This sets up global configurations like logging and supported locales. The scaffold uses GetxApp (a wrapper around GetMaterialApp and ScreenUtilInit) to handle screen adaptation, theme management, and localization via GlobalService.

    import 'package:getx_scaffold/getx_scaffold.dart';
    
    void main() async {
      WidgetsBinding widgetsBinding = await init(
        isDebug: kDebugMode,
        logTag: 'GetxScaffold',
        supportedLocales: TranslationLibrary.supportedLocales,
      );
      runApp(
        GetxApp(
          designSize: const Size(390, 844),
          enableLog: kDebugMode,
          defaultTransition: Transition.rightToLeft,
          themeMode: GlobalService.to.themeMode,
          theme: AppTheme.light,
          darkTheme: AppTheme.dark,
          locale: GlobalService.to.locale,
          translations: TranslationLibrary(),
          fallbackLocale: TranslationLibrary.fallbackLocale,
          supportedLocales: TranslationLibrary.supportedLocales,
          localizationsDelegates: TranslationLibrary.localizationsDelegates,
          title: 'GetxScaffold',
          home: const HomePage(),
          builder: (context, widget) {
            return widget!;
          },
        ),
      );
    }
  10. Install getx_scaffold dependency

    master

    To use the scaffold in your Flutter project, add getx_scaffold to your pubspec.yaml file. If you plan to use internationalization (i18n), you must also include flutter_localizations from the Flutter SDK.

    dependencies:
      getx_scaffold: ^0.0.1
    
      # If your project requires internationalization, add this dependency:
      flutter_localizations:
        sdk: flutter
  11. Use the event library for UI refreshing and lifecycle management

    master

    The event library provides mechanisms for handling UI refreshes and managing component lifecycles within the GetX Scaffold framework. It exports two primary modules:

    1. refresh_ui.dart: Contains logic and interfaces for triggering UI updates or refreshes.
    2. lifecycle.dart: Contains logic and interfaces for managing the lifecycle of components or events.

    To use these features, import the event library in your Dart files.

    import 'package:flutter_getx_scaffold/common/event/index.dart';
  12. Configure DayFormat for timeline output

    master

    The DayFormat enum controls the verbosity and style of the generated timeline string. Use these to decide how much detail to show for dates that are not 'just now'.

    • DayFormat.simple: Minimalist. Shows relative time like 'x days' or 'Yesterday'.
    • DayFormat.common: Shows month and day (e.g., MM-dd) for dates in the current year, and full date (e.g., yyyy-MM-dd) for past years.
    • DayFormat.full: Adds time to the common format (e.g., MM-dd HH:mm).
    enum DayFormat {
      simple,
      common,
      full,
    }