Repository: flutter
Issue: EventChannel.binaryMessenger Null check operator used on a null value when listening broadcaststream
Labels: platform-android,framework,has reproducible steps,a: null-safety,P2,found in release: 2.5,found in release: 2.6,team-android,triaged-android

I have a single page with a button. My eventchannel is working well if i dont use isolates. But i am using isolates because want to run this code even app is terminated. When i click the button, compute method runs startlistening method. In startlistening method, i create new eventchannel. There isnt any error before . But if i want to listen broadcaststream, it throws me error:

<details>
<summary>logs</summary>

```console
E/flutter (23095): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Exception: Null check operator used on a null value
E/flutter (23095): #0      EventChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:453:86)
E/flutter (23095): #1      EventChannel.receiveBroadcastStream.<anonymous closure> (package:flutter/src/services/platform_channel.dart:473:7)
E/flutter (23095): #2      EventChannel.receiveBroadcastStream.<anonymous closure> (package:flutter/src/services/platform_channel.dart:472:64)
E/flutter (23095): #3      _runGuarded (dart:async/stream_controller.dart:773:24)
E/flutter (23095): #4      _BroadcastStreamController._subscribe (dart:async/broadcast_stream_controller.dart:207:7)
E/flutter (23095): #5      _ControllerStream._createSubscription (dart:async/stream_controller.dart:786:19)
E/flutter (23095): #6      _StreamImpl.listen (dart:async/stream_impl.dart:473:9)
E/flutter (23095): #7      startListening (package:fluttercallhandler/main.dart:12:36)
E/flutter (23095): #8      _IsolateConfiguration.apply (package:flutter/src/foundation/_isolates_io.dart:84:34)
E/flutter (23095): #9      _spawn.<anonymous closure> (package:flutter/src/foundation/_isolates_io.dart:91:65)
E/flutter (23095): #10     _spawn.<anonymous closure> (package:flutter/src/foundation/_isolates_io.dart:90:5)
E/flutter (23095): #11     Timeline.timeSync (dart:developer/timeline.dart:163:22)
E/flutter (23095): #12     _spawn (package:flutter/src/foundation/_isolates_io.dart:88:35)
E/flutter (23095): #13     _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:286:17)
E/flutter (23095): #14     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
E/flutter (23095): 
```
</details>

<details>
<summary>code sample</summary>

This is my main.dart

```dart
import 'dart:async';
import 'dart:isolate';
import 'dart:ui';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

Future <String> startListening(String s)  async{
  // WidgetsFlutterBinding.ensureInitialized();
  const EventChannel _stream = EventChannel('fluttercallchannel');
  _stream.receiveBroadcastStream().listen((data) {
    debugPrint("data : " + data.toString());
  });

  return "finish";
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());

}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(title: Text("FlutterCall")),
        body: Center(
          child: Column(
            children: [
              Text("Test"),
              ElevatedButton(
                  onPressed: () async {
                    print(await compute(startListening, ''));
                    // print();
                  },
                  child: Text("Press to Listen Phone State"))
            ],
          ),
        ),
      ),
    );
  }
}

```

And this is my MainActivity.kt

```kt
package com.example.fluttercallhandler
import android.app.AlarmManager
import android.app.PendingIntent
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.PersistableBundle
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager
import android.util.Log
import io.flutter.embedding.android.FlutterView
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant
import androidx.annotation.UiThread as UiThread1

class MainActivity: FlutterActivity() {
    private val CHANNEL = "samples.flutter.dev/battery"
    private val CHANNEL2 = "fluttercallchannel"
    private val TAG = "MainActivity"


    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
    }
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        EventChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL2).setStreamHandler(object : EventChannel.StreamHandler {
            override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
                val telephony: TelephonyManager =
                    context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
                telephony.listen( object : PhoneStateListener() {
                    @Override
                    override fun onCallStateChanged(state: Int, incomingNumber: String) {
                        super.onCallStateChanged(state, incomingNumber)
                        Log.i(TAG,"incomingNumber : $incomingNumber")
                        Log.i(TAG,"State oncallstatechanged : $state")
                        events?.success(incomingNumber)
                    }
                }, PhoneStateListener.LISTEN_CALL_STATE)

            }

            override fun onCancel(arguments: Any?) {
            }
        })

    }


} 
```
</details>

And flutter doctor -v 

```
[✓] Flutter (Channel stable, 2.5.1, on Ubuntu 20.04.3 LTS 5.11.0-37-generic, locale
    en_US.UTF-8)
    • Flutter version 2.5.1 at /home/ahmetbugra/snap/flutter/common/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision ffb2ecea52 (2 weeks ago), 2021-09-17 15:26:33 -0400
    • Engine revision b3af521a05
    • Dart version 2.14.2

[!] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
    • Android SDK at /home/ahmetbugra/Android/Sdk
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/linux#android-setup for more
      details.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Android Studio (version 4.2)
    • Android Studio at /snap/android-studio/113/android-studio
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.8+0-b944-P17168821)

[✓] Android Studio (version 2020.3)
    • Android Studio at /snap/android-studio/114/android-studio
    • Flutter plugin version 60.1.2
    • Dart plugin version 203.8292
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)

[✓] IntelliJ IDEA Community Edition (version 2021.2)
    • IntelliJ at /snap/intellij-idea-community/320
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code
    • VS Code at /snap/code/current
    • Flutter extension version 3.26.0

[✓] Connected device (2 available)
    • Mi Note 10 Lite (mobile) • 317de6c3 • android-arm64  • Android 11 (API 30)
    • Chrome (web)             • chrome   • web-javascript • Google Chrome 93.0.4577.63

! Doctor found issues in 1 category.

```