Source

contexts/FlutterContext.jsx

// Create FlutterContext.jsx
import React, { createContext, useContext } from 'react';
import toast from 'react-hot-toast';

/**
 * Context for interacting with the Flutter environment.
 * Provides functions to send data and messages to the Flutter app.
 */
const FlutterContext = createContext();

/**
 * Custom hook to access the Flutter context.
 * Throws an error if used outside of a FlutterProvider.
 * @returns The Flutter context value.
 */
export const useFlutter = () => {
  const context = useContext(FlutterContext);
  if (!context) {
    throw new Error('useFlutter must be used within FlutterProvider');
  }
  return context;
};

/**
 * Provider component for the Flutter context.
 * Wraps the application to make Flutter interaction functions available.
 * @param {Object} props - The component props.
 * @param {React.ReactNode} props.children - The child components.
 * @returns The FlutterProvider component.
 */
export const FlutterProvider = ({ children }) => {
  /**
   * Sends a message to the Flutter application.
   * @param {string} action - The action to be performed in Flutter.
   * @param {object} [data] - Optional data to send with the action.
   */
  const sendToFlutter = (action, data) => {
    try {
      if (window.ReactToFlutter) {
        const message = { action: action, ...data };
        window.ReactToFlutter.postMessage(JSON.stringify(message));
        console.log('📤 Sent to Flutter:', action);
      } else {
        toast.error('ReactToFlutter channel not available');
        console.warn('ReactToFlutter channel not available');
      }
    } catch (error) {
      console.error('Error sending to Flutter:', error);
    }
  };

  /**
   * Updates the user data stored in the Flutter application.
   * Retrieves user data from local storage and sends it to Flutter.
   */
  const updateUserInFlutter = () => {
      const userData = JSON.parse(localStorage.getItem('user'));
      sendToFlutter('updateUser', { userData });
      toast.success('User updated in Flutter');

  };

  /**
   * Displays a message within the Flutter application.
   * @param {string} message - The message to display.
   */

  const showFlutterMessage = (message) => {
    sendToFlutter('showMessage', { message });
  };

  return (
    <FlutterContext.Provider value={{
      sendToFlutter,
      updateUserInFlutter,
      showFlutterMessage
    }}>
      {children}
    </FlutterContext.Provider>
  );
};