MPFlutter Framework

repository·master·Indexed 24 days ago

https://github.com/mpflutter/mpflutter

A framework for running Flutter applications in specialized environments such as WeChat, Wegame, and desktop development modes. It provides tools for image encoding (MPFlutterImageEncoder), network image handling (MPFlutterNetworkImage), and JavaScript interoperability via JSObject, JSArray, and JSFunction. The framework includes WeChat-specific integrations like MPFlutterWechatAppDelegate for lifecycle events, MPFlutterWechatAppShareManager for sharing, and the MPApp wrapper for safe area and keyboard height adjustments.

Tokens
2.9K
Snippets
5
Records
23
Agent score
80%

What's inside MPFlutter

  1. How MPApp handles WeChat environment signals

    master

    MPApp communicates with the WeChat JavaScript context to synchronize the Flutter UI with the mini-program environment. It listens to the following JS context properties and callbacks:

    • safeAreaInsetTop: A numeric value representing the top safe area inset.
    • safeAreaInsetBottom: A numeric value representing the bottom safe area inset (defaults to 50.0 if not provided).
    • keyboardHeightChanged: A callback function (num value) => void triggered when the keyboard height changes. MPApp uses this to update the viewInsets in MediaQuery and notifies MPFlutterKeyboardObserver.shared.
    • onWegameShow: A callback that triggers a forced frame update in Flutter.
  2. Build Dev Mode artifacts for WeChat

    master

    To develop using MPFlutter in Dev Mode (which enables hot reload/connection features), you must build the application using the specific build script with the --devmode flag.

    Steps to run in WeChat:

    1. Build: Run the build script with the --devmode flag.
    2. Import: Use WeChat DevTools to import the generated artifacts.
    3. Run: Run the project directly in the WeChat simulator or scan the QR code to preview on a physical device.

    Note: Do not attempt to preview on both a simulator and a physical device simultaneously; ensure one is closed to avoid connection conflicts.

    dart scripts/build_wechat.dart --devmode
  3. Use MPApp to wrap your application for WeChat mini-programs

    master

    When building for WeChat mini-programs using MPFlutter, wrap your root widget with MPApp. This component automatically handles platform-specific layout adjustments, including safe area insets (top and bottom) and keyboard height changes, by injecting them into the MediaQuery data.

    Key behaviors:

    • Safe Area: Adjusts padding and viewPadding based on safeAreaInsetTop and safeAreaInsetBottom provided by the WeChat environment.
    • Keyboard Handling: Updates viewInsets based on the keyboardHeight reported by the JS context, allowing your UI to react to the keyboard appearing or disappearing.
    • Platform Check: If not running in an MPFlutter environment (kIsMPFlutter is false), it simply returns the provided child without modifications.
  4. Start an MPFlutter application with runMPApp()

    master

    Use runMPApp(Widget app) to initialize and launch your MPFlutter application. This function handles environment-specific setup, such as initializing the windowManager for desktop/dev modes, setting up the MemoryManager, and managing the splash screen.

    If running in kIsMPFlutterDevmode, it configures a window with a default size of 414x896. If running in standard MPFlutter mode, it automatically hides the splash screen after runApp is called.

  5. Work with JavaScript arrays using JSArray

    master

    The JSArray class is a specialized JSObject for interacting with JavaScript arrays. It provides common array manipulation methods that bridge the gap between Dart and JS.

    • add(value): Appends a value to the array (calls JS push).
    • addAll(List<dynamic> value): Appends multiple values from a Dart list.
    • length(): Returns the number of elements in the array.
    • value(): Converts the entire JavaScript array into a Dart List<dynamic>.
  6. Listen for theme changes with addThemeListener()

    master
    Use MPFlutterDarkmodeManager.addThemeListener(callback) to register a function that will be executed whenever the system theme changes (e.g., when the user toggles dark mode in system settings). The callback should be a Function() that triggers your application's UI update logic.
  7. Encode an image to a file path

    master

    Use MPFlutterImageEncoder.encodeToFilePath to save a ui.Image directly as a file in the mini-program environment. Once saved, you can use WeChat (WX) APIs to upload the file to a server or save it to the user's local photo album. This is the recommended method for high-performance file saving.

    Parameters:

    • image: The ui.Image to encode.
    • filePath: The destination path where the file should be saved.
    • format: The image format (MPFlutterImageByteFormat.png, MPFlutterImageByteFormat.jpeg, or MPFlutterImageByteFormat.webp). Defaults to png.
    • compressQuality: A double representing compression quality (0.0 to 1.0). Defaults to 0.92.
  8. Mock HTTP requests for testing network images

    master

    For testing purposes, MPFlutterNetworkImage uses a global httpRequestFactory which can be overridden with a custom web.XMLHttpRequest factory. This allows you to intercept or mock network requests during testing.

    To restore the default behavior (using the standard web.XMLHttpRequest), call debugRestoreHttpRequestFactory().

  9. Track navigation with MPNavigatorObserver

    master

    The MPNavigatorObserver class provides access to the current navigation state of the application. You can use it to inspect the active route or access the shared observer instance.

    • MPNavigatorObserver.currentRoute: Returns the currently active Route.
    • MPNavigatorObserver.shared: Returns the singleton instance of the private navigator observer.
  10. Interact with JavaScript objects using JSObject

    master

    The JSObject class provides a Dart wrapper for interacting with JavaScript objects in the host environment. It handles the bidirectional transformation between Dart types (like Map and List) and JavaScript objects.

    Key capabilities:

    • Property Access: Use the [] operator to get or set properties. The returned values are automatically transformed from JS types to MPJS types.
    • Method Invocation: Use callMethod(methodName, [arguments]) to call functions on the JS object. Arguments are automatically transformed to browser-compatible JS objects.
    • Asynchronous Methods: Use callMethodAwaitPromise(methodName, [arguments]) to call a JavaScript method that returns a Promise. This returns a Dart Future that completes when the Promise resolves or rejects.
    • Object Inspection: Use asMap() to convert the JavaScript object into a Dart Map.