You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Android端调用Firebase/Firestore加载速度慢问题排查

Flutter Android端Firestore加载性能远低于iOS的问题

背景信息

我开发了一款可在Android和iOS设备上运行的Flutter应用,该应用会从Firestore中的集合加载文档列表。

问题现象

Android设备上的加载时间明显更长。我在不同版本的Android和iOS模拟器、真机上进行了大量测试,iOS端始终表现出较快的加载速度,但Android真机的性能却差很多,当请求中添加orderBy条件后,性能会进一步下降。

真机测试结果示例

操作系统字段数文档数耗时
iOS1027500.5秒
Android1027502.8秒
iOS1047950.7秒
Android1047953.5秒

复现与测试方法

  • 下载测试代码仓库
  • 获取所需依赖包
  • 在真机上运行应用(模拟器上的结果可能不一致)

运行中的应用内有多个按钮可用于测试调用,结果可直接在应用内或日志中查看。


核心代码(main.dart)

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

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  FirebaseFirestore.instance.settings = const Settings(
    persistenceEnabled: false,
    cacheSizeBytes: Settings.CACHE_SIZE_UNLIMITED,
  );
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Android perf test',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blueAccent),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Android perf test'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String elapsedTime = '0';
  String itemLength = '0';
  bool loading = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(40),
        child: Stack(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('Call took : $elapsedTime sec',
                    textAlign: TextAlign.center),
                Text('For $itemLength documents', textAlign: TextAlign.center),
                const SizedBox(height: 40),
                ElevatedButton(
                  child: const Text('Test load with 10 fields'),
                  onPressed: () => testThis('products10'),
                ),
                const SizedBox(height: 30),
                ElevatedButton(
                  child: const Text('Test load with 50 fields'),
                  onPressed: () => testThis('products50'),
                ),
                const SizedBox(height: 30),
                ElevatedButton(
                  child: const Text('Test load with 10 fields and orderBy'),
                  onPressed: () => testThis('products10', withOrder: true),
                ),
                const SizedBox(height: 30),
                ElevatedButton(
                  child: const Text('Test load with 50 fields and orderBy'),
                  onPressed: () => testThis('products50', withOrder: true),
                ),
              ],
            ),
            if (loading)
              Container(
                color: Colors.white.withOpacity(0.5),
              ),
          ],
        ),
      ),
    );
  }

  Future<void> testThis(String collectionName, {bool withOrder = false}) async {
    setState(() {
      loading = true;
    });
    print('Test start with $collectionName');
    Stopwatch stopwatch = Stopwatch()..start();

    if (withOrder) {
      await FirebaseFirestore.instance
          .collection(collectionName)
          .orderBy('ein', descending: true)
          .orderBy('name')
          .orderBy('language')
          .orderBy('company')
          .get()
          .then(
            (value) => setLength(value.docs.length),
          );
    } else {
      await FirebaseFirestore.instance.collection(collectionName).get().then(
            (value) => setLength(value.docs.length),
          );
    }

    stopwatch.stop();
    setState(() {
      elapsedTime = stopwatch.elapsed.toString();
    });
    print('Call took : ${stopwatch.elapsed}');
    setState(() {
      loading = false;
    });
  }

  void setLength(int length) {
    setState(() {
      itemLength = length.toString();
    });
    print('Documents loaded : $length');
  }
}

内容的提问来源于stack exchange,提问作者Nico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 19:41:00