【问题标题】:Flutter Error: Method 'addPostFrameCallback' cannot be called on 'WidgetsBinding?' because it is potentially nullFlutter 错误:无法在“WidgetsBinding”上调用方法“addPostFrameCallback”?因为它可能为空
【发布时间】:2022-06-25 17:03:27
【问题描述】:

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

../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.
Try replacing '?.' with '.'
    WidgetsBinding?.instance.addPostFrameCallback((_) {
    ^^^^^^^^^^^^^^
../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.
 - 'WidgetsBinding' is from 'package:flutter/src/widgets/binding.dart' ('../flutter/packages/flutter/lib/src/widgets/binding.dart').
Try calling using ?. instead.
    WidgetsBinding?.instance.addPostFrameCallback((_) {
                             ^^^^^^^^^^^^^^^^^^^^


FAILURE: Build failed with an exception.

* Where:
Script '/home/user/Downloads/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 1102

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command '/home/user/Downloads/flutter/bin/flutter'' finished with non-zero exit value 1

* Try:
Run 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.

* Get more help at https://help.gradle.org

BUILD FAILED in 22s
Running Gradle task 'assembleDebug'...                             22.8s
Exception: Gradle task assembleDebug failed with exit code 1

这是我的 Flutter 医生输出

[✓] Flutter (Channel stable, 2.10.3, on Ubuntu 20.04.4 LTS 5.13.0-41-generic, locale en_IN)
    • Flutter version 2.10.3 at /home/user/Downloads/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 7e9793dee1 (3 months ago), 2022-03-02 11:23:12 -0600
    • Engine revision bd539267b4
    • Dart version 2.16.1
    • DevTools version 2.9.2

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /home/user/Android/Sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: /opt/android-studio-2021.1.1/android-studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Android Studio (version 2021.1)
    • Android Studio at /opt/android-studio-2021.1.1/android-studio
    • Flutter plugin version 66.0.1
    • Dart plugin version 211.7811
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)

[✓] Android Studio
    • Android Studio at /opt/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.11+0-b60-7590822)

[✓] Connected device (2 available)
    • sdk gphone64 x86 64 (mobile) • emulator-5554 • android-x64    • Android 12 (API 31) (emulator)
    • Chrome (web)                 • chrome        • web-javascript • Google Chrome 99.0.4844.82

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

我已经尝试过以下事情

  1. 使 android-studio 失效并重启
  2. 已删除 .gradle 文件夹并尝试重新构建
  3. flutter clean 然后 'flutter pub get, flutter pub 缓存修复`
    • 还删除了构建文件夹和 pubspec.lock 文件

但没有,工作

另外,这是我的 Gradle 文件

android/app/build.gradle

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.gms.google-services'
android {
    compileSdkVersion flutter.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
    splits {
        abi {
            enable true
            reset()
            include 'x86', 'armeabi-v7a'
            universalApk true
        }
    }
    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.app.example"
        minSdkVersion 19
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        multiDexEnabled = true
    }
    // signingConfigs {
    //     debug {
    //         if (debugKeystorePropertiesFile.exists()) {
    //             keyAlias debugKeystoreProperties['keyAlias']
    //             keyPassword debugKeystoreProperties['keyPassword']
    //             storeFile file(debugKeystoreProperties['storeFile'])
    //             storePassword debugKeystoreProperties['storePassword']
    //         }
    //     }
    // }
    buildTypes {
        release {
//            if (keystorePropertiesFile.exists()) {
//                signingConfig signingConfigs.release
//                println "Signing with key.properties"
//            } else {
                signingConfig signingConfigs.debug
                println "Signing with debug keys"
//            }
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation platform('com.google.firebase:firebase-bom:29.2.1')
    implementation 'com.google.firebase:firebase-auth-ktx'
    implementation 'com.google.android.gms:play-services-safetynet:18.0.1'
    implementation 'com.google.firebase:firebase-appcheck-safetynet:16.0.0-beta05'

    implementation "androidx.browser:browser:1.3.0"
}

android/build.gradle

buildscript {
    ext.kotlin_version = '1.6.10'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.10'
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

  • 我确实已将 android.useAndroidXandroid.enableJetifier 添加到 true
  • 还在 androidmanifest.xml 中添加了android:exported="true"

【问题讨论】:

  • 这个问题是由 percent_indicator 引起的:^4.0.0 我评论了这个库的使用,也从 pubspec 中删除了,然后它就可以工作了。

标签: flutter android-studio gradle flutter-dependencies


【解决方案1】:

您的? 位置错误。尝试像这样更改代码

// WidgetsBinding?.instance.addPostFrameCallback
-> WidgetsBinding.instance?.addPostFrameCallback

【讨论】:

    【解决方案2】:

    你应该改变

    WidgetsBinding?.instance.addPostFrameCallback
    

    WidgetsBinding.instance?.addPostFrameCallback
    

    【讨论】:

      【解决方案3】:

      似乎包将 null 感知运算符放在 WidgetsBinding 而不是实例上。

      dart:162:5:警告:“WidgetsBinding”类不能为空。尝试 替换'?.'和 '。' WidgetsBinding?.instance.addPostFrameCallback((_) { ^^^^^^^^^^^^^^

      应该是:

      WidgetsBinding.instance?.addPostFrameCallback((_) {
      

      【讨论】:

        【解决方案4】:

        pubspec.yaml 中的 percent_indicator 依赖项更改为:

        percent_indicator: #update flutter 3
        git:
          url: https://github.com/XuannThucc/flutter_percent_indicator.git
          ref: be51b3d56e729ca1889f77a5f6311b5287fa611d
        

        【讨论】:

        • 试过了,还是一样的错误
        • 你是否尝试运行 Flutter clean 来清除缓存并重建?
        • 是的,在将 percent_indicator git repo 添加到 pubspec.yaml 后,我触发了 flutter clean 然后 flutter pub get,我还尝试了 Invalidate/Restart android studio。但是没有用。
        【解决方案5】:

        使用 percent_indicator 4.0.1 版。更高版本被定制为颤振3.0,所以你有一个错误。或者将flutter升级到3.0版本

        【讨论】:

        【解决方案6】:

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

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

        percent_indicator: 4.0.1
        

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

        【讨论】:

        • 好的,谢谢分享。我不知道 4.0.1 会起作用。我会试试的,告诉你。
        • 这里一样 4.0.1 拉 4.2.1 所以我改了percent_indicator: git: url: https://github.com/diegoveloper/flutter_percent_indicator ref: 686feb842d7144c3c45f8ce8d305a380416f3b67
        【解决方案7】:

        已通过将 percent_indicator 库添加到本地项目来解决。

        因为我改变了,这个

        WidgetsBinding?.instance.addPostFrameCallback((_) {
                                     ^^^^^^^^^^^^^^^^^^^^
        

        到这里

        WidgetsBinding?.instance?.addPostFrameCallback((_) {
                                     
        

        它正在工作

        谢谢大家的回复

        【讨论】:

          猜你喜欢
          • 2021-12-30
          • 2022-11-12
          • 2021-08-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-03
          • 2022-11-26
          • 1970-01-01
          相关资源
          最近更新 更多