Flutter 错误:无法在“WidgetsBinding”上调用方法“addPostFrameCallback”?因为它可能为空

TUS*_*HAR 12 gradle android-studio flutter flutter-dependencies

每当我尝试运行 flutter 应用程序时,都会收到此错误。

\n
../flutter/.pub-cache/hosted/pub.dartlang.org/percent_indicator-4.2.1/lib/linear_percent_indicator.dart:162:5: Warning: The class 'WidgetsBinding' cannot be null.\nTry replacing '?.' with '.'\n    WidgetsBinding?.instance.addPostFrameCallback((_) {\n    ^^^^^^^^^^^^^^\n../flutter/.pub-cache/hosted/pub.dartlang.org/percent_indicator-4.2.1/lib/linear_percent_indicator.dart:162:30: Error: Method 'addPostFrameCallback' cannot be called on 'WidgetsBinding?' because it is potentially null.\n - 'WidgetsBinding' is from 'package:flutter/src/widgets/binding.dart' ('../flutter/packages/flutter/lib/src/widgets/binding.dart').\nTry calling using ?. instead.\n    WidgetsBinding?.instance.addPostFrameCallback((_) {\n                             ^^^^^^^^^^^^^^^^^^^^\n\n\nFAILURE: Build failed with an exception.\n\n* Where:\nScript '/home/user/Downloads/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 1102\n\n* What went wrong:\nExecution failed for task ':app:compileFlutterBuildDebug'.\n> Process 'command '/home/user/Downloads/flutter/bin/flutter'' finished with non-zero exit value 1\n\n* Try:\nRun with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.\n\n* Get more help at https://help.gradle.org\n\nBUILD FAILED in 22s\nRunning Gradle task 'assembleDebug'...                             22.8s\nException: Gradle task assembleDebug failed with exit code 1\n\n
Run Code Online (Sandbox Code Playgroud)\n

这是我的 Flutter doctor 输出

\n
[\xe2\x9c\x93] Flutter (Channel stable, 2.10.3, on Ubuntu 20.04.4 LTS 5.13.0-41-generic, locale en_IN)\n    \xe2\x80\xa2 Flutter version 2.10.3 at /home/user/Downloads/flutter\n    \xe2\x80\xa2 Upstream repository https://github.com/flutter/flutter.git\n    \xe2\x80\xa2 Framework revision 7e9793dee1 (3 months ago), 2022-03-02 11:23:12 -0600\n    \xe2\x80\xa2 Engine revision bd539267b4\n    \xe2\x80\xa2 Dart version 2.16.1\n    \xe2\x80\xa2 DevTools version 2.9.2\n\n[\xe2\x9c\x93] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)\n    \xe2\x80\xa2 Android SDK at /home/user/Android/Sdk\n    \xe2\x80\xa2 Platform android-32, build-tools 32.1.0-rc1\n    \xe2\x80\xa2 Java binary at: /opt/android-studio-2021.1.1/android-studio/jre/bin/java\n    \xe2\x80\xa2 Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)\n    \xe2\x80\xa2 All Android licenses accepted.\n\n[\xe2\x9c\x93] Chrome - develop for the web\n    \xe2\x80\xa2 Chrome at google-chrome\n\n[\xe2\x9c\x93] Android Studio (version 2021.1)\n    \xe2\x80\xa2 Android Studio at /opt/android-studio-2021.1.1/android-studio\n    \xe2\x80\xa2 Flutter plugin version 66.0.1\n    \xe2\x80\xa2 Dart plugin version 211.7811\n    \xe2\x80\xa2 Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)\n\n[\xe2\x9c\x93] Android Studio\n    \xe2\x80\xa2 Android Studio at /opt/android-studio\n    \xe2\x80\xa2 Flutter plugin can be installed from:\n       https://plugins.jetbrains.com/plugin/9212-flutter\n    \xe2\x80\xa2 Dart plugin can be installed from:\n       https://plugins.jetbrains.com/plugin/6351-dart\n    \xe2\x80\xa2 Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)\n\n[\xe2\x9c\x93] Connected device (2 available)\n    \xe2\x80\xa2 sdk gphone64 x86 64 (mobile) \xe2\x80\xa2 emulator-5554 \xe2\x80\xa2 android-x64    \xe2\x80\xa2 Android 12 (API 31) (emulator)\n    \xe2\x80\xa2 Chrome (web)                 \xe2\x80\xa2 chrome        \xe2\x80\xa2 web-javascript \xe2\x80\xa2 Google Chrome 99.0.4844.82\n\n[\xe2\x9c\x93] HTTP Host Availability\n    \xe2\x80\xa2 All required HTTP hosts are available\n\n\xe2\x80\xa2 No issues found!\n\n
Run Code Online (Sandbox Code Playgroud)\n

我已经尝试过以下事情

\n
    \n
  1. 无效并重启android-studio
  2. \n
  3. 删除 .gradle 文件夹并再次尝试构建
  4. \n
  5. flutter clean然后“flutter pub 进行, flutter pub 缓存修复”\n
      \n
    • 还删除了 build 文件夹和 pubspec.lock 文件
    • \n
    \n
  6. \n
\n

但什么也没有,有效

\n

另外,这是我的 Gradle 文件

\n

android/app/build.gradle

\n
def localProperties = new Properties()\ndef localPropertiesFile = rootProject.file('local.properties')\nif (localPropertiesFile.exists()) {\n    localPropertiesFile.withReader('UTF-8') { reader ->\n        localProperties.load(reader)\n    }\n}\n\ndef flutterRoot = localProperties.getProperty('flutter.sdk')\nif (flutterRoot == null) {\n    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")\n}\n\ndef flutterVersionCode = localProperties.getProperty('flutter.versionCode')\nif (flutterVersionCode == null) {\n    flutterVersionCode = '1'\n}\n\ndef flutterVersionName = localProperties.getProperty('flutter.versionName')\nif (flutterVersionName == null) {\n    flutterVersionName = '1.0'\n}\n\napply plugin: 'com.android.application'\napply plugin: 'kotlin-android'\napply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"\napply plugin: 'com.google.gms.google-services'\nandroid {\n    compileSdkVersion flutter.compileSdkVersion\n\n    compileOptions {\n        sourceCompatibility JavaVersion.VERSION_1_8\n        targetCompatibility JavaVersion.VERSION_1_8\n    }\n\n    kotlinOptions {\n        jvmTarget = '1.8'\n    }\n\n    sourceSets {\n        main.java.srcDirs += 'src/main/kotlin'\n    }\n    splits {\n        abi {\n            enable true\n            reset()\n            include 'x86', 'armeabi-v7a'\n            universalApk true\n        }\n    }\n    defaultConfig {\n        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).\n        applicationId "com.example.app.example"\n        minSdkVersion 19\n        targetSdkVersion flutter.targetSdkVersion\n        versionCode flutterVersionCode.toInteger()\n        versionName flutterVersionName\n        multiDexEnabled = true\n    }\n    // signingConfigs {\n    //     debug {\n    //         if (debugKeystorePropertiesFile.exists()) {\n    //             keyAlias debugKeystoreProperties['keyAlias']\n    //             keyPassword debugKeystoreProperties['keyPassword']\n    //             storeFile file(debugKeystoreProperties['storeFile'])\n    //             storePassword debugKeystoreProperties['storePassword']\n    //         }\n    //     }\n    // }\n    buildTypes {\n        release {\n//            if (keystorePropertiesFile.exists()) {\n//                signingConfig signingConfigs.release\n//                println "Signing with key.properties"\n//            } else {\n                signingConfig signingConfigs.debug\n                println "Signing with debug keys"\n//            }\n        }\n    }\n}\n\nflutter {\n    source '../..'\n}\n\ndependencies {\n    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"\n    implementation platform('com.google.firebase:firebase-bom:29.2.1')\n    implementation 'com.google.firebase:firebase-auth-ktx'\n    implementation 'com.google.android.gms:play-services-safetynet:18.0.1'\n    implementation 'com.google.firebase:firebase-appcheck-safetynet:16.0.0-beta05'\n\n    implementation "androidx.browser:browser:1.3.0"\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n

android/build.gradle

\n
buildscript {\n    ext.kotlin_version = '1.6.10'\n    repositories {\n        google()\n        mavenCentral()\n    }\n\n    dependencies {\n        classpath 'com.android.tools.build:gradle:4.1.0'\n        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"\n        classpath 'com.google.gms:google-services:4.3.10'\n    }\n}\n\nallprojects {\n    repositories {\n        google()\n        mavenCentral()\n    }\n}\n\nrootProject.buildDir = '../build'\nsubprojects {\n    project.buildDir = "${rootProject.buildDir}/${project.name}"\n}\nsubprojects {\n    project.evaluationDependsOn(':app')\n}\n\ntask clean(type: Delete) {\n    delete rootProject.buildDir\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n
    \n
  • 我确实添加了android.useAndroidXandandroid.enableJetifier到 true
  • \n
  • 还添加android:exported="true"在androidmanifest.xml中
  • \n
\n

Cig*_*oSA 8

正如@DiyorbekDev 所说,您应该使用 4.0.1 版本。4.2.x 适用于 Flutter 3,存在一些空安全不兼容问题。

您不需要将percent_indicatorlib 添加到本地项目。我已经解决了同样的问题。我不得不强制pubspec.yaml使用4.0.1版本:

percent_indicator: 4.0.1
Run Code Online (Sandbox Code Playgroud)

OBS:不要使用(由于某种原因,它为我^4.0.1拉取了最后一个版本[ 4.2.1 ])


man*_*n21 3

你应该改变

WidgetsBinding?.instance.addPostFrameCallback
Run Code Online (Sandbox Code Playgroud)

WidgetsBinding.instance?.addPostFrameCallback
Run Code Online (Sandbox Code Playgroud)