Flutter For Web 从 Firestore 获取数据

Posted

技术标签:

【中文标题】Flutter For Web 从 Firestore 获取数据【英文标题】:Flutter For Web Fetching data from Firestore 【发布时间】:2020-04-01 07:42:43 【问题描述】:

如何使用 firebase 模块检索数据?

这是我的课:

import 'package:firebase/firebase.dart';
import 'package:firebase/firestore.dart';
import 'dart:convert' as json;
import 'package:projecthub/models/User.dart';

class DatabaseService 

  static final Firestore store = firestore();
  CollectionReference users = store.collection('users');
  CollectionReference projects = store.collection('projects');

  DatabaseService();

  void getUsers ()
    print("fetching data...");
    users.onSnapshot.listen((querySnapshot) 
      print(querySnapshot);
    );

  

  void createNewUser(String uid, String username, int reputaion, List followers)

  


这是 index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>projecthub</title>
  <script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-firestore.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-storage.js"></script>
  <script defer src="main.dart.js" type="application/javascript"></script>
</head>

<body>
  <script>
    document.addEventListener('keydown', function (event) 
      if (event.code == 'Tab') 
        event.preventDefault();
      
    );
    var perf = firebase.performance();
  </script>
</body>

</html>

这是 pubsec.yaml:

dependencies:
  flutter:
    sdk: flutter
  firebase: ^7.1.0

我正在 main.dart 中初始化应用程序

assert(()
    initializeApp(
      apiKey: "API KEY",
      authDomain: "AUTH DOMAIN",
      databaseURL: "DB URL",
      projectId: "Project Id",
      storageBucket: "storage bucket",
      messagingSenderId: "messaging id");
      return true;
  ());

我已尝试遵循 firebase 模块文档,但没有找到答案。 我正在使用 firebase:^7.1.0 已经尝试过 cloud_firestore 并没有找到答案。 如果您对此主题有任何疑问,请随时提问,谢谢。

【问题讨论】:

这应该可以工作 - 它不适合你怎么办?你打电话给getUsers?你调试过你的代码吗? @creativecreatorormaybenot 它打印“获取数据”,但它不打印我不知道为什么的查询快照 您是否将库添加为&lt;script&gt; 标签并初始化您的应用程序? @creativecreatorormaybenot yes I did 【参考方案1】:

试试下面的代码。它会工作

// 1
// FirestoreGet

import 'package:firebase/firebase.dart';
import 'package:firebase/firestore.dart' as fs;

class FirestoreGet 

    static Future<List<Users>> getUsers() async 
      fs.Firestore store = firestore();
      fs.CollectionReference ref = store.collection("users");

      List<Users> usersAry = List();

      ref.onSnapshot.listen((querySnapshot) 
      querySnapshot.docChanges().forEach((change) 
         if (change.type == "added") 
           // Do something with change.doc
          print("Count : $querySnapshot.size");
         
      );

      querySnapshot.docs.forEach((d) 
        usersAry.add(Users.fromJson(d.data(), d.id));
      );
      return usersAry;
    );
  


// 2
// User Model

class Users 
   String first_name;
   String last_name;
   String email_address;

  Users(
    String first_name = '',
    String last_name = '',
    String email_address = '',
  ) 
    this.first_name = first_name;
    this.last_name = last_name;
   this.email_address = email_address;
  

  Users.fromJson(Map<String, dynamic> jsonMap, String documentId) 
     first_name = jsonMap['first_name'];
     last_name = jsonMap['last_name'];
     email_address = jsonMap['email_address'];
  

 Map<String, dynamic> toMap() 
   return <String, dynamic>
     'first_name': this.first_name,
     'last_name': this.last_name,
     'email_address': this.email_address,
  ;
 


// 3
// main.dart

import 'package:firebase/firebase.dart' as fb;

void main()
  assert(()
    fb.initializeApp(
      apiKey: "API KEY",
      authDomain: "AUTH DOMAIN",
      databaseURL: "DB URL",
      projectId: "Project Id",
      storageBucket: "storage bucket",
      messagingSenderId: "messaging id");
      return true;
  ());
   runApp(Home());



// 4
// Home Page

class Home extends StatefulWidget 
  @override
  State<StatefulWidget> createState() 
    // TODO: implement createState
    return HomeState();
  


 class HomeState extends State<Home> 

  @override
  Widget build(BuildContext context) 
    //getting screen size
  

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

     var userAry = FirestoreGet.getUsers();
     print(userAry);
  


// 5
// index.html 

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script defer src="main.dart.js" type="application/javascript"></script>
</head>
<body>

  <script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-firestore.js"></script>

  <script>
    document.addEventListener('keydown', function (event) 
      // console.log('event key'+event.code);
      if (event.code == 'Tab') 
        event.preventDefault();
      
    );
    var perf = firebase.performance();

</script>
</body>
</html>

// 6
// pubspec.yaml

 dependencies:
  flutter:
    sdk: flutter
  firebase: ^7.1.0

【讨论】:

它不打印querySnapshot,我没有尝试用户解析。

以上是关于Flutter For Web 从 Firestore 获取数据的主要内容,如果未能解决你的问题,请参考以下文章

Flutter For Web 从 Firestore 获取数据

如何使用 Flutter for Web 从本地文件中读取内容?

为啥我的数据没有在 Flutter for web 中使用 api 从实时数据库中检索

如何将“Flutter for Web”转换为“Flutter for Mobile”?

flutter web(3) 快速创建web工程并运行

Flutter For Web实践