firebase 如何在Flutter中显示Firestore的数据

ix0qys7i  于 2022-11-17  发布在  Flutter
关注(0)|答案(1)|浏览(207)

我想显示用户的全名。它存储在Firestore中,如下图所示。我正在尝试,但没有任何效果。我该如何解决此问题?
第一次

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:file_picker/file_picker.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:flutter_dev/reusable.dart';

class Fy extends StatefulWidget {
  const Fy({super.key});

  @override
  State<Fy> createState() => _FyState();
}

class _FyState extends State<Fy> {
  PlatformFile? pickedFile;

  dynamic data;

  dynamic user = FirebaseAuth.instance.currentUser;
  final db = FirebaseFirestore.instance;

  Future getName() async {
    final getFullName = db.collection("users").doc(user.uid);

    getFullName.get().then((DocumentSnapshot doc) {
      setState(() {
        dynamic data = doc.data["fullName"].toString();
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
          Text(
            'Hello $data}}',
            style: const TextStyle(color: Colors.white),
          ),
          Text(
            '${user.uid}',
            style: const TextStyle(color: Colors.white),
          ),
        ]),
      ),
    );
  }
}

错误行

swvgeqrz

swvgeqrz1#

“如果能帮助别人,我自己会找到”

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:file_picker/file_picker.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:flutter_dev/reusable.dart';

class Fy extends StatefulWidget {
  const Fy({super.key});

  @override
  State<Fy> createState() => _FyState();
}

class _FyState extends State<Fy> {
  PlatformFile? pickedFile;

  final db = FirebaseFirestore.instance;
  final user = FirebaseAuth.instance.currentUser;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: StreamBuilder(
          stream: db.collection("users").doc(user!.uid).snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) return const Text('Loading Data..');
            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('Hello ' +
                  snapshot.data!['fullName'],
                  style: const TextStyle(color: Colors.white, fontSize: 20),
                ),
                SizedBox(
                  height: 10,
                ),
                Text('Your email : ' +
                  snapshot.data!['email'],
                  style: const TextStyle(color: Colors.white, fontSize: 20),
                ),
              ],
            );
          }),
    ));
  }
}

相关问题