Flutter Firestore Read Write Response Very Slow in Ios

Viewed 576

I have added flutter firestore my ios app. The read-write update delete request to firestore is very quick as usual, but when I want to get the response of the read write update delete back from firestore server, it is very slow and fails sometimes.

The code for write and read in my main.dart is

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

final firestoreInstance = FirebaseFirestore.instance;
final auth = FirebaseAuth.instance;

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future<void> adduser() async {
    await firestoreInstance.collection("users").add({
      "mob": 9344122678292,
      "email": "usehhr5",
      "name": {"fname": "Sub", "lname": "Collec"},
      "array": [
        "raw",
        "pin",
        "hot",
      ],
      "time": FieldValue.serverTimestamp(),
    }).then((value) {
      
      print("added_data");
      
    }).catchError((error) => print("Failed to add user: $error"));
  }

  Future<void> readdata() async {
    await firestoreInstance.collection("users").get().then((querySnapshot) {
      //firestoreInstance.clearPersistence();
      querySnapshot.docs.forEach((result) {
        print(result.data());

        print("read_data");
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          //adduser();
          readdata();
        },
        tooltip: 'Read/Add data',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

So i want to get the response from read and write in print() statemen, but it takes 2-3 seconds to get the response and some times i get this error message in log

console response

Also sometime get this response

7.3.0 - [Firebase/Firestore][I-FST000001] Could not reach Cloud Firestore backend. Backend didn't respond within 10 seconds.
 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.

and this repsonse

[BackgroundTask] Background Task 22 ("GTMSessionFetcher-www.googleapis.com"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.

Please provide help, I tried the read and write response from firestore in ios emulator and a physical android device, it was perfect. I was getting instant response from the firesotre server. The issue is showing when i run the app in physical ios device running ios 14.4

1 Answers

As it seems, you are calling async methods directly from the StatefulWidget , that's not good. Those async methods are interacting with Firestore , and any slowness will directly affect the user experience.

few suggestions:
accessing Firestore right from the widget is not the right way. This will your app unresponsive. Widgets should be responsible for the user interaction and be responsive.
Data processing (Firestore etc) should be handled by BLoC and be done in an async way. State management plays essential role in building Flutter apps.

Related