0

我正在开发我的第一个颤振应用程序,但是我真的是 firebase 和颤振的新手。

我的应用程序已经通过电子邮件和密码在 firebase 上进行身份验证,但我只知道如何向所有用户显示 db 集合,我想显示登录用户的具体数据。

现在我收到这个错误

'DocumentSnapshot' 类没有实例 getter 'documents'。接收方:“DocumentSnapshot”实例尝试调用:文档

但是当我调用文档时,它会显示一个新错误: 没有为“CollectionReference”类型定义方法“文档”。尝试将名称更正为现有方法的名称,或定义名为“文档”的方法。

我的登录代码

signIn() async {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();



      try {
            getData() async{
          String user = (await FirebaseAuth.instance.currentUser).uid;
          return Firestore.instance.collection('users').document(user);
        }
        UserCredential user = await FirebaseAuth.instance

            .signInWithEmailAndPassword(email: _email, password: _password);



            getUserDoc();


        Navigator.push(

            context, MaterialPageRoute(builder: (context) => Home()));


      }
      catch (e) {
        print(e.message);
      }
    }
  }
} 

主页代码

import 'dart:typed_data';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dio/dio.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:esys_flutter_share/esys_flutter_share.dart';
import 'dart:io';
import 'package:http/http.dart';
import 'package:flutter_cached_pdfview/flutter_cached_pdfview.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';
import 'package:image_viewer/image_viewer.dart';








class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  int _currentIndex = 0;

  Stream<DocumentSnapshot> getDatabase() async* {
    FirebaseUser user = await FirebaseAuth.instance.currentUser;
    yield* Firestore.instance
        .collection('users')
        .document(user.uid)
        .snapshots();
  }



  final tabs = [

    //TAB DE MANUAIS
    Center(
        child: (Scaffold(
            body: StreamBuilder (

                stream: FirebaseFirestore.instance.collection('users').document('user.uid').snapshots(),
                builder: (context, snapshot) {
                  if (snapshot.data == null) return CircularProgressIndicator();

                  return Container(
                    padding: EdgeInsets.all(16),
                    child: ListView.builder(
                        itemCount: snapshot.data.documents.length,
                        itemBuilder: (context, index) {
                          DocumentSnapshot manuais =
                          snapshot.data.documents[index];




                          var dio = Dio();


                          return Card(
                            color: Colors.grey[250],
                            child: Container(
                              padding: EdgeInsets.all(10),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,

                                children: <Widget>[

                                    new Image.asset('Images/pdflogo.png', width: 32,
                                    ),
                                  Center(
                                    child: Text(
                                      (manuais.data()['nome'].toString()),
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(fontSize: 16),

                                    ),
                                  ),

                                  ButtonBar(
                                    children: <Widget>[

                                        FlatButton(
                                          child: const Text('Compartilhar / Download'),
                                            onPressed: () async {
                                              var request = await HttpClient().getUrl(Uri.parse(manuais.data()['documento']));
                                              var response = await request.close();Uint8List bytes = await consolidateHttpClientResponseBytes(response);
                                              await Share.file(
                                                  'ESYS AMLOG',
                                                  'Manual.pdf',
                                                  bytes,
                                                  'image/jpg');
                                            }),





                                          ],
                                  ),
                                ],
                              ),
                            ),
                          );
                        }),
                  );
                })))),

    //TAB DE PRODUCAO
    Center(
        child: (Scaffold(
            body: StreamBuilder(
                stream: FirebaseFirestore.instance.collection('producao').snapshots(),
                builder: (context, snapshot) {
                  if (snapshot.data == null) return CircularProgressIndicator();

                  return Container(
                    padding: EdgeInsets.all(16),
                    child: ListView.builder(
                        itemCount: snapshot.data.documents.length,
                        itemBuilder: (context, index) {
                          DocumentSnapshot producao =
                          snapshot.data.documents[index];

                          return Card(
                            color: Colors.grey[250],
                            child: Container(
                              padding: EdgeInsets.all(10),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Center(
                                    child: Image.network(producao.data()['img'].toString(), width: 260,
                                    ),

                                  ),
                                  Text(
                                    (producao.data()['data'].toString()),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(fontSize: 22),
                                  ),
                                  Text(
                                    (producao.data()['detail'].toString()),
                                    style: TextStyle(fontSize: 16),
                                  ),
                                  ButtonBar(
                                    children: <Widget>[

                                      FlatButton(
                                          child: const Text('DETALHES'),
                                          onPressed: () {
                                            ImageViewer.showImageSlider(
                                              images: [
                                                (producao.data()['img']),
                                                //List of images' URLs
                                              ],
                                            );




                                          }),
                                      FlatButton(
                                          child: const Text('COMPARTILHAR'),
                                          onPressed: () async {

                                            var request = await HttpClient().getUrl(Uri.parse(producao.data()['img']));
                                            var response = await request.close();Uint8List bytes = await consolidateHttpClientResponseBytes(response);

                                            await Share.file(
                                                'ESYS AMLOG',
                                                'amlog.jpg',
                                                bytes,
                                                'image/jpg'
                                            );
                                          }),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          );
                        }),
                  );
                })))),
    Center(child: Text('Documentos')),
  ];

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(title: Text('Área do Cliente')),
      body: tabs[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.shifting,
        iconSize: 28,
        items: [
          BottomNavigationBarItem(
              icon: Icon(Icons.picture_as_pdf),
              title: Text('Manuais'),
              backgroundColor: Colors.indigo),
          BottomNavigationBarItem(
              icon: Icon(Icons.build),
              title: Text('Produção'),
              backgroundColor: Colors.indigo),
          BottomNavigationBarItem(
            icon: Icon(Icons.folder),
            title: Text('Documentos'),
            backgroundColor: Colors.indigo,
          )
        ],
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
    );
  }
}

```









4

2 回答 2

2

这是您可以获得子值的示例:

 FirebaseFirestore.instance.collection('users').document('user.uid').then((DataSnapshot snapshot) {
      if(snapshot.value != null){
        setState(() {
         String firebaseText=snapshot.value['your key name'].toString();
        });
      }
于 2020-09-16T13:15:56.533 回答
1
FirebaseFirestore.instance.collection('users').document('user.uid').snapshots()

此特定行仅返回 1 个文档。它不会为您提供文件列表。现在一个文档将有几个字段 - 键:值对。它也可以有一个集合。
要通过键访问字段,请使用snapshot.data[key]. 它会返回对应的值

于 2020-09-16T13:10:15.327 回答