Ad

How Do I Integrate Flutter_bloc With Method Channels?

I've started using flutter_bloc package instead of redux to try it out, but I'm not entirely sure how I'm going to call flutter bloc events when receiving things from native (Android/iOS). It was easier with redux because in my parent MyApp widget of my main.dart file, I passed in the redux store to a custom class I created, and dispatched methods from the said class (called MethodChannelHandler).

main.dart:

void main() {
    runApp(new MyApp());
}
class MyApp extends StatefulWidget {
    @override
    State<StatefulWidget> createState() => _MyAppState();
}


class _MyAppState extends State<MyApp> {
    final Store<AppState> store = Store<AppState>(
      // ... redux stuff ...
    );

    @override
    void initState() {

        // sauce
        MethodChannelHandler(store);

        super.initState();
    }
}

methodChannelHandler.dart:

class MethodChannelHandler {
    Store<AppState> store;

    MethodChannelHandler(this.store) {
        methodChannel.setMethodCallHandler(_handleMethod);
    }

    // Handle method calls from native
    Future _handleMethod(MethodCall call) async {
        if (call.method == A_METHOD) {
            store.dispatch("something from native")
        }
    }
}

NOTE: I'm inept when it comes to programming vocabulary so please, if possible, please give me a small snippet of example code like I have or link me to some GitHub repo I can refer to instead of giving me a block of text I'm probably not going to understand.

Ad

Answer

In very simple way it's look like this:

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<SomeBloc>(
      create: (_) {
        final bloc = SomeBloc(); //Create bloc

        MethodChannelHandler(bloc); //Add method handler

        return bloc;
      },
      lazy: false,
      child: Text("Content"),
    );
  }
}

class SomeBloc extends Bloc {
  SomeBloc() : super(SomeInitState());

  @override
  Stream mapEventToState(event) async* {
    if (event is SomeEvent) {
      //Handle SomeEvent
    }
  }
}

class MethodChannelHandler {
  final SomeBloc someBloc;

  MethodChannelHandler(this.someBloc) {
    methodChannel.setMethodCallHandler(_handleMethod);
  }

  // Handle method calls from native
  Future _handleMethod(MethodCall call) async {
    if (call.method == A_METHOD) {
      someBloc.add(SomeEvent("something from native"));
    }
  }
}
Ad
source: stackoverflow.com
Ad