Flutter 如何在颤振中启动时调用函数

Flutter 如何在颤振中启动时调用函数,flutter,Flutter,我在我的应用程序中创建了新页面,但我想在不设置状态的情况下调用函数 这是我的职责: yaziGetir(Mahalle mahalle) { FirebaseFirestore.instance .collection("Mahalleler") .doc(mahalle.neighborhood) .get() .then((gelenVeri) { setState(() {

我在我的应用程序中创建了新页面,但我想在不设置状态的情况下调用函数

这是我的职责:

yaziGetir(Mahalle mahalle) {
    FirebaseFirestore.instance
        .collection("Mahalleler")
        .doc(mahalle.neighborhood)
        .get()
        .then((gelenVeri) {
      setState(() {
        gelenYaziBasligi = gelenVeri.data()['Eğitim'];
        gelenYaziIcerigi = gelenVeri.data()['Geri Dönüşüm'];
      });
    });
  }

可以在生成方法之前调用函数。例如:

  void yourFunction() {
    // This is your function
  }

  @override
  Widget build(BuildContext context) {
    // Call the function before build method
    yourFunction();
    return Scaffold(
      body: Text('ok'),
    );
  }
在您的情况下,因为您使用的是async函数,所以应该使用FutureBuilder

  Future<void> yourAsyncFunction() async {
    // This is your function
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      // Waiting your async function to finish
      future: yourAsyncFunction,
      builder: (context, snapshot) {
        // Async function finished
        if (snapshot.connectionState == ConnectionState.done) {
          // To access the function data when is done
          // you can take it from **snapshot.data**
          return Scaffold(
            body: Text('ok'),
          );
        } else {
          // Show loading during the async function finish to process
          return Scaffold(child: CircularProgressIndicator());
        }
      },
    );
  }
Future yourAsyncFunction()异步{
//这是你的职责
}
@凌驾
小部件构建(构建上下文){
回归未来建设者(
//等待异步函数完成
未来:功能,
生成器:(上下文,快照){
//异步函数已完成
if(snapshot.connectionState==connectionState.done){
//完成后访问功能数据的步骤
//您可以从**snapshot.data获取它**
返回脚手架(
正文:文本('ok'),
);
}否则{
//在异步函数完成过程中显示加载
返回脚手架(子项:循环压缩机指示器());
}
},
);
}

您应该在initState而不是小部件树中调用函数,因为每次小部件重建时,它都会调用函数一次又一次执行(导致更多读取)


InitState(){},您可以在这里调用函数

谢谢您,这是您的工作!如果有帮助的话,请为我投票
@override
void initState()
{
super.initState();
yourFunction();//call it over here
}