Fixing keyboard-related crashes in Flutter

I've been using a bluetooth keyboard with my Flutter app. And in some cases, I experienced repeated crashes.

Some of the errors were:

E/InputEventSender( 4319): Exception dispatching finished signal.
E/MessageQueue-JNI( 4319): Exception in MessageQueue callback: handleReceiveCallback
E/MessageQueue-JNI( 4319): java.lang.IndexOutOfBoundsException: charAt: -1 < 0
E/MessageQueue-JNI( 4319): 	at android.text.SpannableStringBuilder.charAt(
E/MessageQueue-JNI( 4319): 	at java.lang.Character.codePointAt(
E/MessageQueue-JNI( 4319): 	at io.flutter.plugin.editing.FlutterTextUtils.getOffsetAfter(
E/MessageQueue-JNI( 4319): 	at io.flutter.plugin.editing.InputConnectionAdaptor.sendKeyEvent(
E/MessageQueue-JNI( 4319): 	at
E/MessageQueue-JNI( 4319): 	at io.flutter.view.FlutterView.onKeyDown(
E/MessageQueue-JNI( 4319): 	at android.view.KeyEvent.dispatch(
E/MessageQueue-JNI( 4319): 	at android.view.View.dispatchKeyEvent(

════════ Exception caught by services library ══════════════════════════════════
The following assertion was thrown during a platform message callback:
'package:flutter/src/widgets/shortcuts.dart': Failed assertion: line 344 pos 15: 'primaryContext != null': is not true.

Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:

When the exception was thrown, this was the stack
#2      ShortcutManager.handleKeypress
#3      _ShortcutsState._handleOnKey
#4      FocusManager._handleRawKeyEvent

════════ Exception caught by services library ══════════════════════════════════
Tried to get the bounds of a focus node that didn't have its context set yet.
The context needs to be set before trying to evaluate traversal policies. Setting the context is typically done with the attach method.
Failed assertion: line 727 pos 9: 'context != null'

Searches on Google didn't reveal anything useful. Some post on StackOverflow had related issues with Samsung phones, but I was able to reproduce my issue in an emulator.

Here's how I reproduced the issue in my app. In the main view, I was processing keyboard events myself with a RawKeyboardListener. I could also tap on a button to open another window that contained TextFields. When I came back to the main view and tapped anything on my keyboard, it would crash.

I ended up trying a few things, and eventually the error disappeared. I'm not curious enough to roll back each change one by one to pinpoint exactly how I fixed it, but all I ended up doing was making sure I disposed and closed all streams and listeners in my dispose methods. I really should have done it from the start. That will teach me!