dart 如何处理Flutter中的_Future< dynamic>值?

ljsrvy3e  于 2023-01-06  发布在  Flutter
关注(0)|答案(1)|浏览(230)

我正在flutter中尝试从firebase获取值。在此期间,我正在接收Future〈〉类型返回函数返回的_Flutter值。请帮助其他人
我有一个从firebase获取值的代码..函数通过查询属性从firebase获取值

class FirebaseMethods {
  Future<List> findEvents(dynamic attribute, dynamic value) async {
    CollectionReference eventCollection =
        FirebaseFirestore.instance.collection('events');
    return eventCollection
        .where(attribute, isEqualTo: value)
        .get()
        .then((QuerySnapshot querySnapshot) {
      List events = [];
      querySnapshot.docs.forEach((doc) {
        events.add(doc.data());
      });
      return events;
    }).catchError((error) {
      print("Failed to retrieve events: $error");
    });
  }

  Future<List> findUsers(dynamic attribute, dynamic value) async {
    CollectionReference userCollection =
        FirebaseFirestore.instance.collection('profile');
    return userCollection
        .where(attribute, isEqualTo: value)
        .get()
        .then((QuerySnapshot querySnapshot) {
      List users = [];
      querySnapshot.docs.forEach((doc) {
        users.add(doc.data());
      });
      return users;
    }).catchError((error) {
      print("Failed to retrieve users: $error");
    });
  }
}

我用下面的方法调用上面的函数'findUsers':

dynamic database_functions = FirebaseMethods();

class RenderProfileView extends StatefulWidget {
  String email;
  RenderProfileView(this.email, {super.key});

  @override
  State<RenderProfileView> createState() => _RenderProfileViewState();
}

class _RenderProfileViewState extends State<RenderProfileView> {
  TextEditingController name_controller = TextEditingController();
  TextEditingController phone_number_controller = TextEditingController();

  late dynamic user_json = database_functions.findUser('email', widget.email);    // without late I am getting error and getting values with attribute 'email' = widget.email

  dynamic get_name() {
    print(user_json);
    return 'some_value';
  }
}

当调用'findUser'函数时,打印消息是-〉'_Future'的示例有人请帮助..如果有其他解决问题的方法,请提及。

6mw9ycah

6mw9ycah1#

Future描述了flutter中的异步操作。你必须等待所有Future结果。使用await关键字或者。then属性。
您可以尝试将initState添加到有状态小部件中,或者根据您的用例使用FutureBuilder。
下面是代码的编辑版本。

dynamic database_functions = FirebaseMethods();

class RenderProfileView extends StatefulWidget {
  String email;
  RenderProfileView(this.email, {super.key});

  @override
  State<RenderProfileView> createState() => _RenderProfileViewState();
}

class _RenderProfileViewState extends State<RenderProfileView> {
  TextEditingController name_controller = TextEditingController();
  TextEditingController phone_number_controller = TextEditingController();

  late dynamic user_json;

  @override
  void initState() {
   super.initState();
   database_functions.findUser('email', widget.email).then((data) {
    user_json = data
   });
  }

  String get name => 'some_value';
}

相关问题