更改Firebase Firestore上的数据后更新颤振UI

更改Firebase Firestore上的数据后更新颤振UI,firebase,flutter,user-interface,google-cloud-firestore,Firebase,Flutter,User Interface,Google Cloud Firestore,我有一个带有用户名、电子邮件和个人资料图片的个人资料页面的应用程序 我试图做的是,用户点击一个按钮来更改配置文件图片,打开一个新页面,其中包含一个简单的圆圈化身小部件和一个按钮,该按钮将图像上传到Firebase Storage和Firebase Firestore,并添加到该特定当前用户uid的Firestore集合中 一切正常,我可以看到Firebase存储上的更改,图像由uid+当前用户集合上的URL添加 这是编辑用户图像屏幕的代码: import 'dart:io'; import '

我有一个带有用户名、电子邮件和个人资料图片的个人资料页面的应用程序

我试图做的是,用户点击一个按钮来更改配置文件图片,打开一个新页面,其中包含一个简单的圆圈化身小部件和一个按钮,该按钮将图像上传到Firebase Storage和Firebase Firestore,并添加到该特定当前用户uid的Firestore集合中

一切正常,我可以看到Firebase存储上的更改,图像由uid+当前用户集合上的URL添加

这是编辑用户图像屏幕的代码:

import 'dart:io';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tradie_app/scr/providers/authService.dart';
import 'package:tradie_app/scr/widgets/loading.dart';

class EditCompanyImageScreen extends StatefulWidget {
  @override
  _EditCompanyImageScreenState createState() => _EditCompanyImageScreenState();
}

class _EditCompanyImageScreenState extends State<EditCompanyImageScreen> {
  // Keep track of the form for validation
  final _formKey = GlobalKey<FormState>();

  // Loading Icon
  bool loading = false;

  final AuthService _authService = AuthService();
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  final FirebaseFirestore _firebaseFirestore = FirebaseFirestore.instance;

  File _image;

  Future getImage(bool gallery) async {
    ImagePicker picker = ImagePicker();
    PickedFile pickedFile;
    // Let user select photo from gallery
    if (gallery) {
      pickedFile = await picker.getImage(
        source: ImageSource.gallery,
      );
    }
    setState(() {
      if (pickedFile != null) {
        _image = File(pickedFile.path);
        uploadFile(_image); // Use if you only need a single picture
      } else {
        print('No image selected.');
      }
    });
  }

  Future<String> uploadFile(File image) async {
    String downloadURL;
    Reference ref = FirebaseStorage.instance
        .ref()
        .child("images/${_firebaseAuth.currentUser.uid}");
    await ref.putFile(image);
    downloadURL = await ref.getDownloadURL();
    return downloadURL;
  }

  Future uploadToFirebase() async {
    final CollectionReference users =
        _firebaseFirestore.collection("Companies");
    final String uid = _firebaseAuth.currentUser.uid;

    String url = await uploadFile(
        _image); // this will upload the file and store url in the variable 'url'
    await users.doc(uid).update({'url': url});
    final result = await users.doc(uid).get();
    return result.data()["url"];
  }

  @override
  Widget build(BuildContext context) {
    return loading
        ? Loading()
        : Scaffold(
            appBar: AppBar(
              title: Text("Update Profile Image"),
            ),
            body: Form(
              key: _formKey,
              child: Column(
                children: [
                  Container(
                    child: Stack(
                      children: <Widget>[
                        Align(
                          alignment: Alignment.center,
                          child: IconButton(
                            icon: Icon(Icons.camera_alt),
                            onPressed: () async {
                              getImage(true);
                            },
                          ),
                        ),
                        Container(
                          child: _image != null
                              ? Container(
                                  height: 200,
                                  width: 200,
                                  decoration: BoxDecoration(
                                    image: DecorationImage(
                                        image: FileImage(
                                          _image,
                                        ),
                                        fit: BoxFit.contain),
                                  ),
                                )
                              : Container(
                                  decoration: BoxDecoration(
                                    color: Colors.grey[200],
                                    borderRadius: BorderRadius.circular(50),
                                  ),
                                  width: 100,
                                  height: 100,
                                  child: Icon(
                                    Icons.camera_alt,
                                    color: Colors.grey[800],
                                  ),
                                ),
                        ),
                      ],
                    ),
                  ),
                  Row(
                    children: [
                      ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          primary: Colors.black,
                        ),
                        child: Text(
                          "Submit",
                          style: TextStyle(color: Colors.white),
                        ),
                        onPressed: () async {
                          uploadToFirebase();
                          Navigator.pop(context);
                        },
                      ),
                    ],
                  ),
                ],
              ),
            ),
          );
  }
}
Stream getCompanyImageData() async* {
    final CollectionReference users =
        _firebaseFirestore.collection("Companies");
    final String uid = _firebaseAuth.currentUser.uid;
    final result = await users.doc(uid).get();
    yield result.data()["url"];
  }
Column(
    children: [
                                  StreamBuilder(
                                    stream: getCompanyImageData(),
                                    builder: (BuildContext context,
                                        AsyncSnapshot snapshot) {
                                      if (snapshot.connectionState ==
                                          ConnectionState.waiting) {
                                        return Center(
                                          child: CircularProgressIndicator(),
                                        );
                                      }
                                      return Image.network(
                                        snapshot.data.toString(),
                                        width: 100,
                                        height: 100,
                                      );
                                    },
                                  ),
                                ],
                              ),
我的问题:

import 'dart:io';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tradie_app/scr/providers/authService.dart';
import 'package:tradie_app/scr/widgets/loading.dart';

class EditCompanyImageScreen extends StatefulWidget {
  @override
  _EditCompanyImageScreenState createState() => _EditCompanyImageScreenState();
}

class _EditCompanyImageScreenState extends State<EditCompanyImageScreen> {
  // Keep track of the form for validation
  final _formKey = GlobalKey<FormState>();

  // Loading Icon
  bool loading = false;

  final AuthService _authService = AuthService();
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  final FirebaseFirestore _firebaseFirestore = FirebaseFirestore.instance;

  File _image;

  Future getImage(bool gallery) async {
    ImagePicker picker = ImagePicker();
    PickedFile pickedFile;
    // Let user select photo from gallery
    if (gallery) {
      pickedFile = await picker.getImage(
        source: ImageSource.gallery,
      );
    }
    setState(() {
      if (pickedFile != null) {
        _image = File(pickedFile.path);
        uploadFile(_image); // Use if you only need a single picture
      } else {
        print('No image selected.');
      }
    });
  }

  Future<String> uploadFile(File image) async {
    String downloadURL;
    Reference ref = FirebaseStorage.instance
        .ref()
        .child("images/${_firebaseAuth.currentUser.uid}");
    await ref.putFile(image);
    downloadURL = await ref.getDownloadURL();
    return downloadURL;
  }

  Future uploadToFirebase() async {
    final CollectionReference users =
        _firebaseFirestore.collection("Companies");
    final String uid = _firebaseAuth.currentUser.uid;

    String url = await uploadFile(
        _image); // this will upload the file and store url in the variable 'url'
    await users.doc(uid).update({'url': url});
    final result = await users.doc(uid).get();
    return result.data()["url"];
  }

  @override
  Widget build(BuildContext context) {
    return loading
        ? Loading()
        : Scaffold(
            appBar: AppBar(
              title: Text("Update Profile Image"),
            ),
            body: Form(
              key: _formKey,
              child: Column(
                children: [
                  Container(
                    child: Stack(
                      children: <Widget>[
                        Align(
                          alignment: Alignment.center,
                          child: IconButton(
                            icon: Icon(Icons.camera_alt),
                            onPressed: () async {
                              getImage(true);
                            },
                          ),
                        ),
                        Container(
                          child: _image != null
                              ? Container(
                                  height: 200,
                                  width: 200,
                                  decoration: BoxDecoration(
                                    image: DecorationImage(
                                        image: FileImage(
                                          _image,
                                        ),
                                        fit: BoxFit.contain),
                                  ),
                                )
                              : Container(
                                  decoration: BoxDecoration(
                                    color: Colors.grey[200],
                                    borderRadius: BorderRadius.circular(50),
                                  ),
                                  width: 100,
                                  height: 100,
                                  child: Icon(
                                    Icons.camera_alt,
                                    color: Colors.grey[800],
                                  ),
                                ),
                        ),
                      ],
                    ),
                  ),
                  Row(
                    children: [
                      ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          primary: Colors.black,
                        ),
                        child: Text(
                          "Submit",
                          style: TextStyle(color: Colors.white),
                        ),
                        onPressed: () async {
                          uploadToFirebase();
                          Navigator.pop(context);
                        },
                      ),
                    ],
                  ),
                ],
              ),
            ),
          );
  }
}
Stream getCompanyImageData() async* {
    final CollectionReference users =
        _firebaseFirestore.collection("Companies");
    final String uid = _firebaseAuth.currentUser.uid;
    final result = await users.doc(uid).get();
    yield result.data()["url"];
  }
Column(
    children: [
                                  StreamBuilder(
                                    stream: getCompanyImageData(),
                                    builder: (BuildContext context,
                                        AsyncSnapshot snapshot) {
                                      if (snapshot.connectionState ==
                                          ConnectionState.waiting) {
                                        return Center(
                                          child: CircularProgressIndicator(),
                                        );
                                      }
                                      return Image.network(
                                        snapshot.data.toString(),
                                        width: 100,
                                        height: 100,
                                      );
                                    },
                                  ),
                                ],
                              ),
当我从edit_user_image_屏幕返回到company_屏幕时,应用程序UI没有更新,我可以在Firebase上看到更改,如果我重新加载Android Studio,我可以在UI上看到更改,但不会自动

以下是我在公司屏幕上显示图像的代码:

import 'dart:io';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tradie_app/scr/providers/authService.dart';
import 'package:tradie_app/scr/widgets/loading.dart';

class EditCompanyImageScreen extends StatefulWidget {
  @override
  _EditCompanyImageScreenState createState() => _EditCompanyImageScreenState();
}

class _EditCompanyImageScreenState extends State<EditCompanyImageScreen> {
  // Keep track of the form for validation
  final _formKey = GlobalKey<FormState>();

  // Loading Icon
  bool loading = false;

  final AuthService _authService = AuthService();
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  final FirebaseFirestore _firebaseFirestore = FirebaseFirestore.instance;

  File _image;

  Future getImage(bool gallery) async {
    ImagePicker picker = ImagePicker();
    PickedFile pickedFile;
    // Let user select photo from gallery
    if (gallery) {
      pickedFile = await picker.getImage(
        source: ImageSource.gallery,
      );
    }
    setState(() {
      if (pickedFile != null) {
        _image = File(pickedFile.path);
        uploadFile(_image); // Use if you only need a single picture
      } else {
        print('No image selected.');
      }
    });
  }

  Future<String> uploadFile(File image) async {
    String downloadURL;
    Reference ref = FirebaseStorage.instance
        .ref()
        .child("images/${_firebaseAuth.currentUser.uid}");
    await ref.putFile(image);
    downloadURL = await ref.getDownloadURL();
    return downloadURL;
  }

  Future uploadToFirebase() async {
    final CollectionReference users =
        _firebaseFirestore.collection("Companies");
    final String uid = _firebaseAuth.currentUser.uid;

    String url = await uploadFile(
        _image); // this will upload the file and store url in the variable 'url'
    await users.doc(uid).update({'url': url});
    final result = await users.doc(uid).get();
    return result.data()["url"];
  }

  @override
  Widget build(BuildContext context) {
    return loading
        ? Loading()
        : Scaffold(
            appBar: AppBar(
              title: Text("Update Profile Image"),
            ),
            body: Form(
              key: _formKey,
              child: Column(
                children: [
                  Container(
                    child: Stack(
                      children: <Widget>[
                        Align(
                          alignment: Alignment.center,
                          child: IconButton(
                            icon: Icon(Icons.camera_alt),
                            onPressed: () async {
                              getImage(true);
                            },
                          ),
                        ),
                        Container(
                          child: _image != null
                              ? Container(
                                  height: 200,
                                  width: 200,
                                  decoration: BoxDecoration(
                                    image: DecorationImage(
                                        image: FileImage(
                                          _image,
                                        ),
                                        fit: BoxFit.contain),
                                  ),
                                )
                              : Container(
                                  decoration: BoxDecoration(
                                    color: Colors.grey[200],
                                    borderRadius: BorderRadius.circular(50),
                                  ),
                                  width: 100,
                                  height: 100,
                                  child: Icon(
                                    Icons.camera_alt,
                                    color: Colors.grey[800],
                                  ),
                                ),
                        ),
                      ],
                    ),
                  ),
                  Row(
                    children: [
                      ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          primary: Colors.black,
                        ),
                        child: Text(
                          "Submit",
                          style: TextStyle(color: Colors.white),
                        ),
                        onPressed: () async {
                          uploadToFirebase();
                          Navigator.pop(context);
                        },
                      ),
                    ],
                  ),
                ],
              ),
            ),
          );
  }
}
Stream getCompanyImageData() async* {
    final CollectionReference users =
        _firebaseFirestore.collection("Companies");
    final String uid = _firebaseAuth.currentUser.uid;
    final result = await users.doc(uid).get();
    yield result.data()["url"];
  }
Column(
    children: [
                                  StreamBuilder(
                                    stream: getCompanyImageData(),
                                    builder: (BuildContext context,
                                        AsyncSnapshot snapshot) {
                                      if (snapshot.connectionState ==
                                          ConnectionState.waiting) {
                                        return Center(
                                          child: CircularProgressIndicator(),
                                        );
                                      }
                                      return Image.network(
                                        snapshot.data.toString(),
                                        width: 100,
                                        height: 100,
                                      );
                                    },
                                  ),
                                ],
                              ),

这取决于你所在州的管理层

CollectionRef.users.doc(ViewModelUser.user.value.mobile).snapshots().listen((event) {
      ViewModelUser.setUser(UserModel.fromJson(event.data()));
    });

这是我的代码,我在其中侦听配置文件中的更改,当有更改时,firebase会向我发送更新的数据,我会更新我的用户数据,我的状态管理会更新UI的其余部分。

像这样尝试,并取消顶部函数
getCompanyImageData()


您是否使用了此
Image.network(snapshot.data.data()[“url”],
?我在回答中包含了它,可能您没有看到。嘿,谢谢,它起作用了!但是,更改图像的过程有点慢。另外,这部分:snapshot.data.data()[“url”],data.data,是故意的吗?快照是您的流结果。第一个
数据
是流是否有任何数据,第二个
数据()
是解锁文档快照。如果
打印(snapshot.data)
,如果
打印(snapshot.data.data()),您将获得DocumentSnapshot的
实例
,您将获得项目的地图,即{“url”:“”}。它速度很慢,但更像是它在图像到达时渲染图像。13秒是很长的时间,有些东西关闭了,除非你使用的是大型图像文件。图像的大小是多少?Firebase非常快,关于上传下载,我从来没有遇到过任何问题。将它用于一个有大量图像的市场应用程序。如何你每页都在处理哪些图片?