-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Description
Describe the bug
When trying to get a document from Firestore, if the device is connected through Wifi the connection fails with the following error message:
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.
To Reproduce
Usually, the error happens when running in a Physical device.
I created a small app to be able to reproduce the errors with minimal interference from the rest my code. See the code below.
When you hit run on the debugger (I'm using VSCode) and then I click on the (+) button to make the request to Firestore, it stays trying for a few seconds (you'll see the progress indicator no the test app) and then the call snapshot = await docRef.get() fails with the following error message:
PlatformException(Error performing get, Failed to get document because the client is offline., null)
Then, if you turn the wifi off, the request works perfectly. And the content of the document retrieved from Firestore is present in the screen:
Now if you turn the wifi again, the request works. Sometimes the data is retrieved from the server and other from the cache.
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!");
}
}
}
Expected behavior
Since the device has perfect connectivity over wifi, it was excepted that the request worked fine and the document was retrieved from the server.
Additional context
On the emulator, everything works perfectly.
I tested in the following emulator configurations: Pixel 4 API 29, Pixel 5 API 25, Pixel 3 API 29.
The physical devices I used to test (both failed identically) where: Pixel 4XL (Android 10 QQ3Q.200605.001) and Pixel 3XL (Android 10 QQ2A.200305.002).
Flutter doctor
[✓] 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.
pubspec.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'
}

