flutterflutter-platform-channel

how to subscribe to a listener from native code in flutter


I have a class with an initialization method, inside which a listener is created, and I don't quite understand how to subscribe to this listener from the Flutter side? Always return FlutterResult?

init() {
        //self.methodChannel = methodChannel
        LoggingService.Instance.logLevel = LogLevel.Debug
                
        try? mCore = Factory.Instance.createCore(configPath: "", factoryConfigPath: "", systemContext: nil)
        try? mCore.start()
        
        //Listeners
        mRegistrationDelegate = CoreDelegateStub(onAccountRegistrationStateChanged: { (core: Core, account: Account, state: RegistrationState, message: String) in
                    NSLog("New registration state is \(state) for user id \( String(describing: account.params?.identityAddress?.asString()))\n")
                    if (state == .Ok) {
                        self.loggedIn = true
                    } else if (state == .Cleared) {
                        self.loggedIn = false
                    }
                })
        mCore.addDelegate(delegate: mRegistrationDelegate)

    }

Solution

  • Here's an example that demonstrates how to achieve that:

    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatefulWidget {
      static const platform = const MethodChannel('your_channel_name');
    
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      bool loggedIn = false;
    
      // Subscribe to the listener in your native code
      void subscribeToListener() async {
        try {
          await MyApp.platform.invokeMethod('subscribeToListener');
        } catch (e) {
          print('Error subscribing to listener: $e');
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('Listener Example'),
            ),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  ElevatedButton(
                    onPressed: subscribeToListener,
                    child: Text('Subscribe to Listener'),
                  ),
                  SizedBox(height: 20),
                  Text('Logged In: ${loggedIn ? 'Yes' : 'No'}'),
                ],
              ),
            ),
          ),
        );
      }
    }