Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Restore error message explaining the need to call WidgetsFlutterBinding.ensureInitialized() #78028

Closed
lukepighetti opened this issue Mar 12, 2021 · 10 comments · Fixed by #89451
Closed
Labels
c: regression It was better in the past than it is now found in release: 2.1 Found to occur in 2.1 framework flutter/packages/flutter repository. See also f: labels. has reproducible steps The issue has been confirmed reproducible and is ready to work on P2 Important issues not at the top of the work list package flutter/packages repository. See also p: labels.

Comments

@lukepighetti
Copy link

lukepighetti commented Mar 12, 2021

When using shared_preferences: ^2.0.4, when calling SharedPreferences.getInstance() I get a null check exception.

Fails on

  • macOS
  • iOS
  • Android

Succeeds on

  • Web

Flutter version & devices

Flutter 2.1.0-10.0.pre • channel dev • https://github.com/flutter/flutter.git
Framework • revision cc9b78fc5c (2 weeks ago) • 2021-02-25 13:26:03 -0800
Engine • revision a252ec09b7
Tools • Dart 2.13.0 (build 2.13.0-77.0.dev)

SM S102DL (mobile)     • RF8N737S2CR                              • android-arm    • Android 10 (API 29)
Luke's iPhone (mobile) • 0bc0c4864d8e08aac4456893cded68bf0b6767d5 • ios            • iOS 14.4
macOS (desktop)        • macos                                    • darwin-x64     • macOS 11.2.1 20D74 darwin-x64
Chrome (web)           • chrome                                   • web-javascript • Google Chrome 89.0.4389.82

MCVE

name: shared_preferences_macos_issue
description: A new Flutter project.
publish_to: "none"
version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  shared_preferences: ^2.0.4

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() async {
  final prefs = await SharedPreferences.getInstance();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        body: Center(
          child: Text('shared_preferences error'),
        ),
      ),
    );
  }
}
[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Null check operator used on a null value
#0      MethodChannel.binaryMessenger
package:flutter/…/services/platform_channel.dart:142
#1      MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:148
#2      MethodChannel.invokeMethod
package:flutter/…/services/platform_channel.dart:331
#3      MethodChannel.invokeMapMethod
package:flutter/…/services/platform_channel.dart:358
#4      MethodChannelSharedPreferencesStore.getAll
package:shared_preferences_platform_interface/method_channel_shared_preferences.dart:44
#5      SharedPreferences._getSharedPreferencesMap
package:shared_preferences/shared_preferences.dart:181
#6      SharedPreferences.getInstance
package:shared_preferences/shared_preferences.dart:57
#7      main
package:shared_preferences_macos_issue/main.dart:5
#8      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:146:25)
#9      _rootRun (dart:async/zone.dart:1354:13)
#10     _CustomZone.run (dart:async/zone.dart:1258:19)
#11     _runZoned (dart:async/zone.dart:1789:10)
#12     runZonedGuarded (dart:async/zone.dart:1777:12)
#13     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:139:5)
#14     _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
#15     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
@TahaTesser TahaTesser added the in triage Presently being triaged by the triage team label Mar 12, 2021
@lukepighetti lukepighetti changed the title shared_preferences: Null check operator used on a null value thrown on getInstance() shared_preferences: null check exception thrown on getInstance() Mar 12, 2021
@SirusCodes
Copy link
Contributor

Can you run SharedPreferences.getInstance() Before runApp()?

@TahaTesser
Copy link
Member

Hi @lukepighetti
Thanks for all the information to reproduce the issue.

When running your code sample on the stable and beta channels, we can see the following message to add WidgetsFlutterBinding.ensureInitialized(); and adding the line in the main function before final prefs = await SharedPreferences.getInstance(); line fixes the null check exception error and app launches.

logs
[ +213 ms] Connecting to service protocol: http://127.0.0.1:62225/MZ5j6RDbyEE=/
[ +242 ms] Launching a Dart Developer Service (DDS) instance at http://127.0.0.1:0, connecting to VM service at
http://127.0.0.1:62225/MZ5j6RDbyEE=/.
[ +130 ms] DDS is listening at http://127.0.0.1:62233/df3nJKVqXD4=/.
[  +69 ms] [VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before
the binding was initialized.
           If you're running an application and need to access the binary messenger before `runApp()` has been called (for
example, during plugin initialization), then you need to explicitly call the `WidgetsFlutterBinding.ensureInitialized()`
first.
           If you're running a test, you can call the `TestWidgetsFlutterBinding.ensureInitialized()` as the first line in
your test's `main()` method to initialize the binding.
           #0      defaultBinaryMessenger.<anonymous closure> (package:flutter/src/services/binary_messenger.dart:97:7)
           #1      defaultBinaryMessenger (package:flutter/src/services/binary_messenger.dart:110:4)
           #2      MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:142:62)
           #3      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:148:36)
           #4      MethodChannel.invokeMethod (package:flutter/src/services/platfor<…>
[  +41 ms] Successfully connected to service protocol: http://127.0.0.1:62225/MZ5j6RDbyEE=/
[+1604 ms] DevFS: Creating new filesystem on the device (null)
[  +20 ms] DevFS: Created new filesystem on the device
(file:///Users/tahatesser/Library/Developer/CoreSimulator/Devices/BD94A45F-A994-4FC3-BAD9-448D8D2E0F1B/data/Containers/Data/Ap
plication/ED2609BF-51B0-4EF4-BD19-074669020D42/tmp/stable_flutter9BnASB/stable_flutter/)
[   +9 ms] Updating assets
[ +168 ms] Syncing files to device iPhone 12...

However on the dev and master channels, instead of the above message, we get Unhandled Exception: Null check operator used on a null value but adding WidgetsFlutterBinding.ensureInitialized(); also fixes the issue, and the app launches.

logs
[ +215 ms] Launching a Dart Developer Service (DDS) instance at http://127.0.0.1:0, connecting to VM service at
http://127.0.0.1:61914/nvKr2mRoZAY=/.
[ +169 ms] DDS is listening at http://127.0.0.1:61920/3Ju2HOPbk8o=/.
[  +84 ms] [VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: Null check operator used on a null value
           #0      MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:142:86)
           #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:148:36)
           #2      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:331:12)
           #3      MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:358:49)
           #4      MethodChannelSharedPreferencesStore.getAll
(package:shared_preferences_platform_interface/method_channel_shared_preferences.dart:44:25)
           #5      SharedPreferences._getSharedPreferencesMap (package:shared_preferences/shared_preferences.dart:181:57)
           #6      SharedPreferences.getInstance (package:shared_preferences/shared_preferences.dart:57:19)
           #7      main (package:triage/main.dart:5:41)
           #8      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:146:25)
           #9      _rootRun (dart:async/zone.dart:1354:1<…>
[  +40 ms] Successfully connected to service protocol: http://127.0.0.1:61914/nvKr2mRoZAY=/
[ +100 ms] DevFS: Creating new filesystem on the device (null)
[  +31 ms] DevFS: Created new filesystem on the device
(file:///Users/tahatesser/Library/Developer/CoreSimulator/Devices/BD94A45F-A994-4FC3-BAD9-448D8D2E0F1B/data/Containers/Data/Ap
plication/EAD05D9E-EAFA-441E-84A6-102FE2F98379/tmp/dev_flutterePbWK0/dev_flutter/)
[   +6 ms] Updating assets
[ +195 ms] Syncing files to device iPhone 12...
code sample
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final prefs = await SharedPreferences.getInstance();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        body: Center(
          child: Text('shared_preferences error'),
        ),
      ),
    );
  }
}
flutter doctor -v
[✓] Flutter (Channel stable, 2.0.1, on macOS 11.2.3 20D91 darwin-x64, locale en-GB)
    • Flutter version 2.0.1 at /Users/tahatesser/Code/flutter_stable
    • Framework revision c5a4b4029c (8 days ago), 2021-03-04 09:47:48 -0800
    • Engine revision 40441def69
    • Dart version 2.12.0

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Volumes/Extreme/SDK
    • Platform android-30, build-tools 30.0.3
    • ANDROID_HOME = /Volumes/Extreme/SDK
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Volumes/Extreme/Xcode.app/Contents/Developer
    • Xcode 12.4, Build version 12D4e
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • 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 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.54.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.20.0

[✓] Connected device (3 available)
    • iPhone 12 (mobile) • BD94A45F-A994-4FC3-BAD9-448D8D2E0F1B • ios            •
      com.apple.CoreSimulator.SimRuntime.iOS-14-4 (simulator)
    • macOS (desktop)    • macos                                • darwin-x64     • macOS
      11.2.3 20D91 darwin-x64
    • Chrome (web)       • chrome                               • web-javascript • Google
      Chrome 89.0.4389.82

• No issues found!
[✓] Flutter (Channel beta, 2.0.1, on macOS 11.2.3 20D91 darwin-x64, locale en-GB)
    • Flutter version 2.0.1 at /Users/tahatesser/Code/flutter_beta
    • Framework revision c5a4b4029c (8 days ago), 2021-03-04 09:47:48 -0800
    • Engine revision 40441def69
    • Dart version 2.12.0

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Volumes/Extreme/SDK
    • Platform android-30, build-tools 30.0.3
    • ANDROID_HOME = /Volumes/Extreme/SDK
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Volumes/Extreme/Xcode.app/Contents/Developer
    • Xcode 12.4, Build version 12D4e
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • 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 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.54.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.20.0

[✓] Connected device (3 available)
    • iPhone 12 (mobile) • BD94A45F-A994-4FC3-BAD9-448D8D2E0F1B • ios            •
      com.apple.CoreSimulator.SimRuntime.iOS-14-4 (simulator)
    • macOS (desktop)    • macos                                • darwin-x64     • macOS
      11.2.3 20D91 darwin-x64
    • Chrome (web)       • chrome                               • web-javascript • Google
      Chrome 89.0.4389.82

• No issues found!
[✓] Flutter (Channel dev, 2.1.0-10.0.pre, on macOS 11.2.3 20D91 darwin-x64, locale en-GB)
    • Flutter version 2.1.0-10.0.pre at /Users/tahatesser/Code/flutter_dev
    • Framework revision cc9b78fc5c (2 weeks ago), 2021-02-25 13:26:03 -0800
    • Engine revision a252ec09b7
    • Dart version 2.13.0 (build 2.13.0-77.0.dev)

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Volumes/Extreme/SDK
    • Platform android-30, build-tools 30.0.3
    • ANDROID_HOME = /Volumes/Extreme/SDK
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Volumes/Extreme/Xcode.app/Contents/Developer
    • Xcode 12.4, Build version 12D4e
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • 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 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.54.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.20.0

[✓] Connected device (3 available)
    • iPhone 12 (mobile) • BD94A45F-A994-4FC3-BAD9-448D8D2E0F1B • ios            •
      com.apple.CoreSimulator.SimRuntime.iOS-14-4 (simulator)
    • macOS (desktop)    • macos                                • darwin-x64     • macOS
      11.2.3 20D91 darwin-x64
    • Chrome (web)       • chrome                               • web-javascript • Google
      Chrome 89.0.4389.82

• No issues found!
[✓] Flutter (Channel master, 2.1.0-11.0.pre.229, on macOS 11.2.3 20D91 darwin-x64, locale
    en-GB)
    • Flutter version 2.1.0-11.0.pre.229 at /Users/tahatesser/Code/flutter_master
    • Framework revision d20ec4c7d8 (9 hours ago), 2021-03-11 22:18:51 -0800
    • Engine revision 1b68503bc8
    • Dart version 2.13.0 (build 2.13.0-125.0.dev)

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Volumes/Extreme/SDK
    • Platform android-30, build-tools 30.0.3
    • ANDROID_HOME = /Volumes/Extreme/SDK
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Volumes/Extreme/Xcode.app/Contents/Developer
    • Xcode 12.4, Build version 12D4e
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • 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 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.54.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.20.0

[✓] Connected device (4 available)
    • Redmi K20 Pro (mobile) • def0ad20                             • android-arm64  •
      Android 10 (API 29)
    • iPhone 12 (mobile)     • BD94A45F-A994-4FC3-BAD9-448D8D2E0F1B • ios            •
      com.apple.CoreSimulator.SimRuntime.iOS-14-4 (simulator)
    • macOS (desktop)        • macos                                • darwin-x64     •
      macOS 11.2.3 20D91 darwin-x64
    • Chrome (web)           • chrome                               • web-javascript •
      Google Chrome 89.0.4389.82

• No issues found!

Thank you for filing the issue!

@TahaTesser TahaTesser added found in release: 2.1 Found to occur in 2.1 has reproducible steps The issue has been confirmed reproducible and is ready to work on p: first party p: shared_preferences Plugin to read and write Shared Preferences c: regression It was better in the past than it is now and removed in triage Presently being triaged by the triage team labels Mar 12, 2021
@lukepighetti
Copy link
Author

I almost feel comfortable closing this issue now that it's documented. I'll leave it up to you. Thanks for the fast triage.

@stuartmorgan
Copy link
Contributor

@Piinks It looks like the deprecated codepath you removed (#73750) had a very useful warning, but the new codepath doesn't. Can we get this added to the new codepath as well?

(/cc @Hixie since it's about actionable error messages in core framework code.)

@stuartmorgan stuartmorgan added framework flutter/packages/flutter repository. See also f: labels. P2 Important issues not at the top of the work list and removed p: first party p: shared_preferences Plugin to read and write Shared Preferences labels Mar 18, 2021
@Piinks
Copy link
Contributor

Piinks commented Mar 18, 2021

@Piinks It looks like the deprecated codepath you removed (#73750) had a very useful warning, but the new codepath doesn't. Can we get this added to the new codepath as well?

Most definitely! Apologies, I did not realize we were losing that error message in the process.

@Hixie
Copy link
Contributor

Hixie commented Mar 20, 2021

I'm already working on that.

@stuartmorgan
Copy link
Contributor

@Hixie Is restoring this error message still something that's in progress?

@Jordan-Nelson
Copy link

Jordan-Nelson commented Jan 26, 2022

@Hixie @stuartmorgan It looks like this is already in progress, but if it is not, I am happy to take a shot at it. Putting the assertion back in place seems simple enough. It looks like you are planning to resolve this as part of a much larger change though.

Edit: It looks like a basic error message was already added back in master at least for MethodChannel in #92758. Looks like the in progress PR adds some more context and possibly some utils for checking that the bindings have been initialized. I'll wait for that 👍

@Hixie
Copy link
Contributor

Hixie commented Jan 26, 2022

Yeah a comprehensive fix is in #89451. It's taking a long time to land because it requires an intense number of changes to Google's codebase (Google has contributed all its code as tests, which is fantastic in terms of catching regressions, but makes life non-trivial when changing a core API...). (For non-Google codebases, dart fix will be enough to migrate a codebase, but unfortunately that tool doesn't work in Google's specific setup yet.)

@github-actions
Copy link

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Feb 17, 2022
@flutter-triage-bot flutter-triage-bot bot added the package flutter/packages repository. See also p: labels. label Jul 5, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
c: regression It was better in the past than it is now found in release: 2.1 Found to occur in 2.1 framework flutter/packages/flutter repository. See also f: labels. has reproducible steps The issue has been confirmed reproducible and is ready to work on P2 Important issues not at the top of the work list package flutter/packages repository. See also p: labels.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

7 participants