从构建方法访问数据到initState

问题描述 投票:0回答:1

有没有办法从build方法到initState方法访问数据?因为我有来自 firestore 的数据,并且我使用 futureBuilder 获取它,但是当获取数据时整个 UI 都会更新。现在的问题是我只想从名为 participantKeys 的构建方法中获取变量以在 initState 方法中初始化它,因为我想从 futureBuilder 中获取数据,我尝试了很多解决方案但总是得到相同的结果(用户界面已更新)。

这是我的方法

Future? getBusinessListFuture;

  Future<ControllerModel?> getUserModelById(String uid) async {

    ControllerModel? userModel;

    try{
      DocumentSnapshot docSnap = await FirebaseFirestore.instance.collection("users").doc(uid).get();

      if(docSnap.data() != null) {
        userModel = ControllerModel.fromMap(docSnap.data() as Map<String, dynamic>);
      }

    }catch(e){
      print('$e (Firebase_helper)');
    }
    return userModel;

  }
  
  @override
  void initState() {
    streamBuilderChat = streamChat();
    getBusinessListFuture = getUserModelById(' '); <=====
    super.initState();
  }

用户界面屏幕

StreamBuilder(
                  stream: streamBuilderChat,
                  builder: (context, AsyncSnapshot snapshot) {
                    if (snapshot.connectionState == ConnectionState.active) {
                      if (snapshot.hasData) {
                        QuerySnapshot chatRoomSnapshot = snapshot.data as QuerySnapshot;
                        return Column(
                          children: [
                            ListView.builder(
                                physics: BouncingScrollPhysics(),
                                shrinkWrap: true,
                                itemCount: chatRoomSnapshot.docs.length,
                                itemBuilder: (BuildContext context, int index) {

                                  ChatRoomModel chatRoomModel = ChatRoomModel.fromMap(
                                      chatRoomSnapshot.docs[index].data()
                                      as Map<String, dynamic>);

                                  Map<String, dynamic> participants = chatRoomModel.participants!;

                                  List<String> participantKeys = participants.keys.toList();
                                  participantKeys.remove(widget.userModel.uid);

                                  return FutureBuilder(
                                    future:getBusinessListFuture,
                                    // FirebaseHelper.getUserModelById(participantKeys[0]), /// <=====
                                    builder: (context, userData) {

.....

谢谢。

flutter firebase google-cloud-firestore
1个回答
0
投票
class BusinessFuture extends StatefulWidget { 

  final String? uid; 

  const BusinessFuture ({super.key, required this.uid}); 

@override 
State<BusinessFuture > createState() => _BusinessFutureState(); 

}

class _BusinessFutureState extends State<LogInScreen> {

@override
  void initState() {

    streamBuilderChat = streamChat();

    getBusinessListFuture = getUserModelById(widget.uid!);

    super.initState();

  }
}
© www.soinside.com 2019 - 2024. All rights reserved.