首页 > 解决方案 > Firebase Firestore 在物理设备上通过 wifi 故障转移并出现错误:无法访问 Cloud Firestore 后端

问题描述

尝试从 Firestore 获取文档时,如果设备通过 Wifi 连接,则连接失败并显示以下错误消息:

W/Firestore( 4903): (21.4.3) [OnlineStateTracker]: Could not reach Cloud Firestore backend. Backend didn't respond within 10 seconds
W/Firestore( 4903): This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.

重现

通常,在物理设备中运行时会发生错误。我创建了一个小应用程序,以便能够以最小的其余代码干扰来重现错误。请参阅下面的代码。

当您在调试器上点击运行(我正在使用 VSCode)然后我单击 (+) 按钮向 Firestore 发出请求时,它会尝试几秒钟(您会看到进度指示器没有测试应用程序) 然后调用snapshot = await docRef.get()失败并显示以下错误消息:

PlatformException(Error performing get, Failed to get document because the client is offline., null)

在此处输入图像描述

然后,如果你关闭 wifi,请求就会完美运行。从 Firestore 检索到的文档内容显示在屏幕中:

在此处输入图像描述

现在,如果您再次打开 wifi,则请求有效。有时数据是从服务器中检索的,而其他数据是从缓存中检索的。

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firestore Network Bug',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _loading = false;
  Map<String, dynamic> _firebaseDocument;
  String _firebaseError;
  String _source;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Firestore Network Bug"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Text('Tap the (+) button to try to read from Firestore...',
                style: TextStyle(fontSize: 20)),
            _showProgress(),
            _showResults(),
            _showErrors(),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _readFromFirebase,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  Widget _showProgress() {
    return Padding(
      padding: const EdgeInsets.only(top: 12.0),
      child: Container(
        height: 6.0,
        child: (_loading) ? LinearProgressIndicator() : Container(),
      ),
    );
  }

  Widget _showResults() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(height: 12.0),
        Text("Result:"),
        Container(
          height: 150,
          padding: const EdgeInsets.all(16),
          color: Colors.blue[100],
          child: (_firebaseDocument != null)
              ? Text("From $_source: \n\n" + _firebaseDocument?.toString(),
                  style: TextStyle(fontSize: 16))
              : Container(),
        ),
      ],
    );
  }

  Widget _showErrors() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(height: 12.0),
        Text("Errors:"),
        Container(
          height: 150,
          padding: const EdgeInsets.all(16),
          color: Colors.red[100],
          child: (_firebaseError != null)
              ? Text(_firebaseError?.toString(), style: TextStyle(fontSize: 16))
              : Container(),
        ),
      ],
    );
  }

  void _readFromFirebase() async {
    setState(() {
      _loading = true;
      _firebaseDocument = null;
      _firebaseError = null;
    });
    DocumentReference docRef =
        Firestore.instance.document("myCollection/myDocument");

    DocumentSnapshot snapshot = await docRef.get().catchError(
      (onError) {
        setState(() {
          _loading = false;
          _firebaseDocument = null;
          _firebaseError = onError.toString();
        });
      },
    );
    if (_firebaseError != null) return;

    _source = (snapshot.metadata.isFromCache) ? "cache" : "server";

    if (snapshot.exists) {
      setState(() {
        _loading = false;
        _firebaseDocument = snapshot.data;
      });
      print("Document found!");
      print("- ${_firebaseDocument.toString()}");
    } else {
      print("Document not found!");
    }
  }
}

预期行为 由于设备通过 wifi 具有完美的连接,除了请求工作正常并且从服务器检索到文档之外。

附加上下文 在模拟器上,一切正常。我在以下模拟器配置中进行了测试:Pixel 4 API 29、Pixel 5 API 25、Pixel 3 API 29。

我用来测试的物理设备(两者都失败了),其中:Pixel 4XL(Android 10 QQ3Q.200605.001)和 Pixel 3XL(Android 10 QQ2A.200305.002)。

扑医生

[✓] Flutter (Channel stable, v1.17.3, on Mac OS X 10.15.4 19E287, locale en-US)
    • Flutter version 1.17.3 at /Users/mlemos/Documents/flutter
    • Framework revision b041144f83 (8 days ago), 2020-06-04 09:26:11 -0700
    • Engine revision ee76268252
    • Dart version 2.8.4


[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at /Users/mlemos/Library/Android/sdk
    • Platform android-30, build-tools 29.0.2
    • 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-6222593)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.5)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.5, Build version 11E608c
    • CocoaPods version 1.9.1

[!] Android Studio (version 4.0)
    • Android Studio at /Applications/Android Studio.app/Contents
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)

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

[✓] Connected device (2 available)
    • Pixel 4 XL                • 99201FFBA000KF • android-arm64 • Android 10 (API 29)
    • Android SDK built for x86 • emulator-5554  • android-x86   • Android 7.1.1 (API 25) (emulator)

! Doctor found issues in 1 category.

发布规范.yaml

name: firestore_network_bug
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: ^0.1.3
  firebase_analytics: ^5.0.14
  cloud_firestore: ^0.13.6
dev_dependencies:
  flutter_test:
    sdk: flutter
flutter:
  uses-material-design: true

/build.gradle

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // Application specific configuration (dependencies)
        classpath 'com.google.gms:google-services:4.3.3'
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.1.1'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

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

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

/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"
// Application specific configuration (plugins)
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'


android {
    compileSdkVersion 28

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        applicationId "com.example.firestore_network_bug"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        // Application specific configuration (multidex)
        multiDexEnabled true

    }

    buildTypes {
        release {
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    // Application specific configuration (dependencies)
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'com.google.firebase:firebase-analytics:17.2.2'
    implementation 'com.google.firebase:firebase-crashlytics:17.0.0'
    implementation 'com.google.firebase:firebase-firestore:21.4.3'
}

这是调试控制台输出:

通过 Wifi - 发生错误时

请注意,通过 Wifi,Crashlytics 也会失败。

Launching lib/main.dart on Pixel 4 XL in debug mode...
✓ Built build/app/outputs/apk/debug/app-debug.apk.
Connecting to VM Service at ws://127.0.0.1:54122/cahgKkWqnBU=/ws
E/FirebaseCrashlytics(22411): Settings request failed.
E/FirebaseCrashlytics(22411): java.io.InterruptedIOException: timeout
E/FirebaseCrashlytics(22411):   at okhttp3.RealCall.timeoutExit(RealCall.java:107)
E/FirebaseCrashlytics(22411):   at okhttp3.RealCall.execute(RealCall.java:96)
E/FirebaseCrashlytics(22411):   at com.google.firebase.crashlytics.internal.network.HttpRequest.execute(com.google.firebase:firebase-crashlytics@@17.0.0:129)
E/FirebaseCrashlytics(22411):   at com.google.firebase.crashlytics.internal.settings.network.DefaultSettingsSpiCall.invoke(com.google.firebase:firebase-crashlytics@@17.0.0:86)
E/FirebaseCrashlytics(22411):   at com.google.firebase.crashlytics.internal.settings.SettingsController$1.then(com.google.firebase:firebase-crashlytics@@17.0.0:200)
E/FirebaseCrashlytics(22411):   at com.google.firebase.crashlytics.internal.settings.SettingsController$1.then(com.google.firebase:firebase-crashlytics@@17.0.0:193)
E/FirebaseCrashlytics(22411):   at com.google.android.gms.tasks.zzp.run(Unknown Source:2)
E/FirebaseCrashlytics(22411):   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
E/FirebaseCrashlytics(22411):   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
E/FirebaseCrashlytics(22411):   at com.google.firebase.crashlytics.internal.common.ExecutorUtils$1$1.onRun(com.google.firebase:firebase-crashlytics@@17.0.0:60)
E/FirebaseCrashlytics(22411):   at com.google.firebase.crashlytics.internal.common.BackgroundPriorityRunnable.run(com.google.firebase:firebase-crashlytics@@17.0.0:27)
E/FirebaseCrashlytics(22411):   at java.lang.Thread.run(Thread.java:919)
E/FirebaseCrashlytics(22411): Caused by: java.io.IOException: Canceled
E/FirebaseCrashlytics(22411):   at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:120)
E/FirebaseCrashlytics(22411):   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
E/FirebaseCrashlytics(22411):   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
E/FirebaseCrashlytics(22411):   at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
E/FirebaseCrashlytics(22411):   at okhttp3.RealCall.execute(RealCall.java:92)
E/FirebaseCrashlytics(22411):   ... 10 more
W/DynamiteModule(22411): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(22411): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller(22411): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
I/ore_network_bu(22411): The ClassLoaderContext is a special shared library.
I/chatty  (22411): uid=10227(com.example.firestore_network_bug) AsyncTask #1 identical 1 line
I/ore_network_bu(22411): The ClassLoaderContext is a special shared library.
W/ore_network_bu(22411): Accessing hidden method Lsun/misc/Unsafe;->getLong(Ljava/lang/Object;J)J (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(22411): Accessing hidden method Lsun/misc/Unsafe;->arrayBaseOffset(Ljava/lang/Class;)I (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(22411): Accessing hidden method Lsun/misc/Unsafe;->copyMemory(JJJ)V (greylist, linking, allowed)
W/ore_network_bu(22411): Accessing hidden method Lsun/misc/Unsafe;->objectFieldOffset(Ljava/lang/reflect/Field;)J (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(22411): Accessing hidden method Lsun/misc/Unsafe;->getByte(J)B (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(22411): Accessing hidden method Lsun/misc/Unsafe;->getByte(Ljava/lang/Object;J)B (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(22411): Accessing hidden method Lsun/misc/Unsafe;->getLong(J)J (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(22411): Accessing hidden method Lsun/misc/Unsafe;->putByte(JB)V (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(22411): Accessing hidden method Lsun/misc/Unsafe;->putByte(Ljava/lang/Object;JB)V (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(22411): Accessing hidden method Lsun/misc/Unsafe;->getLong(Ljava/lang/Object;J)J (greylist,core-platform-api, reflection, allowed)
W/ore_network_bu(22411): Accessing hidden method Lsun/misc/Unsafe;->getLong(Ljava/lang/Object;J)J (greylist,core-platform-api, reflection, allowed)
W/ore_network_bu(22411): Accessing hidden field Ljava/nio/Buffer;->address:J (greylist, reflection, allowed)
V/NativeCrypto(22411): Registering com/google/android/gms/org/conscrypt/NativeCrypto's 286 native methods...
W/ore_network_bu(22411): Accessing hidden method Ljava/security/spec/ECParameterSpec;->getCurveName()Ljava/lang/String; (greylist, reflection, allowed)
I/ProviderInstaller(22411): Installed default security provider GmsCore_OpenSSL
W/Firestore(22411): (21.4.3) [OnlineStateTracker]: Could not reach Cloud Firestore backend. Backend didn't respond within 10 seconds
W/Firestore(22411):
W/Firestore(22411): This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.
W/DynamiteModule(22411): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(22411): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller(22411): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
W/DynamiteModule(22411): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(22411): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller(22411): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
W/DynamiteModule(22411): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(22411): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller(22411): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
W/DynamiteModule(22411): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(22411): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller(22411): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
W/DynamiteModule(22411): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(22411): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller(22411): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
W/DynamiteModule(22411): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(22411): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller(22411): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.

通过 LTE - 当一切正常时

Launching lib/main.dart on Pixel 4 XL in debug mode...
✓ Built build/app/outputs/apk/debug/app-debug.apk.
Connecting to VM Service at ws://127.0.0.1:54345/egB1v0JRe6c=/ws
W/DynamiteModule(23529): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(23529): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller(23529): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
I/ore_network_bu(23529): The ClassLoaderContext is a special shared library.
I/chatty  (23529): uid=10227(com.example.firestore_network_bug) AsyncTask #1 identical 1 line
I/ore_network_bu(23529): The ClassLoaderContext is a special shared library.
W/ore_network_bu(23529): Accessing hidden method Lsun/misc/Unsafe;->getLong(Ljava/lang/Object;J)J (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(23529): Accessing hidden method Lsun/misc/Unsafe;->arrayBaseOffset(Ljava/lang/Class;)I (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(23529): Accessing hidden method Lsun/misc/Unsafe;->copyMemory(JJJ)V (greylist, linking, allowed)
W/ore_network_bu(23529): Accessing hidden method Lsun/misc/Unsafe;->objectFieldOffset(Ljava/lang/reflect/Field;)J (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(23529): Accessing hidden method Lsun/misc/Unsafe;->getByte(J)B (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(23529): Accessing hidden method Lsun/misc/Unsafe;->getByte(Ljava/lang/Object;J)B (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(23529): Accessing hidden method Lsun/misc/Unsafe;->getLong(J)J (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(23529): Accessing hidden method Lsun/misc/Unsafe;->putByte(JB)V (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(23529): Accessing hidden method Lsun/misc/Unsafe;->putByte(Ljava/lang/Object;JB)V (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(23529): Accessing hidden method Lsun/misc/Unsafe;->getLong(Ljava/lang/Object;J)J (greylist,core-platform-api, reflection, allowed)
W/ore_network_bu(23529): Accessing hidden method Lsun/misc/Unsafe;->getLong(Ljava/lang/Object;J)J (greylist,core-platform-api, reflection, allowed)
W/ore_network_bu(23529): Accessing hidden field Ljava/nio/Buffer;->address:J (greylist, reflection, allowed)
V/NativeCrypto(23529): Registering com/google/android/gms/org/conscrypt/NativeCrypto's 286 native methods...
W/ore_network_bu(23529): Accessing hidden method Ljava/security/spec/ECParameterSpec;->getCurveName()Ljava/lang/String; (greylist, reflection, allowed)
I/ProviderInstaller(23529): Installed default security provider GmsCore_OpenSSL
W/ore_network_bu(23529): Accessing hidden field Ljava/net/Socket;->impl:Ljava/net/SocketImpl; (greylist, reflection, allowed)
W/ore_network_bu(23529): Accessing hidden field Ljava/io/FileDescriptor;->descriptor:I (greylist, JNI, allowed)
W/ore_network_bu(23529): Accessing hidden method Ljava/security/spec/ECParameterSpec;->setCurveName(Ljava/lang/String;)V (greylist, reflection, allowed)
W/ore_network_bu(23529): Accessing hidden method Ldalvik/system/BlockGuard;->getThreadPolicy()Ldalvik/system/BlockGuard$Policy; (greylist,core-platform-api, linking, allowed)
W/ore_network_bu(23529): Accessing hidden method Ldalvik/system/BlockGuard$Policy;->onNetwork()V (greylist, linking, allowed)
I/flutter (23529): Document found!
I/flutter (23529): - {date: Timestamp(seconds=1590980400, nanoseconds=0), published: true, title: Hello World!, body: Firebase rocks and Firestore rocks also (when it works).}

标签: firebasefluttergoogle-cloud-firestore

解决方案


推荐阅读