【问题标题】:How can I Async in InitState before build?在构建之前如何在 InitState 中异步?
【发布时间】:2023-02-14 01:01:38
【问题描述】:

我试图在我的 initstate 中调用异步函数并且我成功了,问题是与它通常所做的不同,构建是在 initstate 之前执行的。 这是我的代码,当然它给了我一个错误,因为后期变量在构建之前没有分配:

  late int oraNotifiche;
  late int minutiNotifiche;

  aggiornaImpostazioni() async {
    final prefs = await SharedPreferences.getInstance();
    await checkNotificheCalendario();

    int timestap = await prefs.getInt("oraNotifiche") ??
        DateTime(DateTime.now().year, DateTime.now().month,
                DateTime.now().day - 1, 19, 0)
            .millisecondsSinceEpoch;

    DateTime orarioSalvato = DateTime.fromMillisecondsSinceEpoch(timestap);

    oraNotifiche = orarioSalvato.hour;
    minutiNotifiche = orarioSalvato.minute;
    if (!mounted) return;
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await aggiornaImpostazioni();
    });
  }

【问题讨论】:

标签: flutter


【解决方案1】:

像这样创建一个未来的方法

Future<void> yourDataLoadingMethod()async{
      /// your future call
    }

并在initState方法中调用这个方法,不用写await关键字

【讨论】:

  • 我刚刚试过了,它一直出错
  • 你遇到了什么错误?
  • “LateError(LateInitializationError:字段‘oraNotifiche’尚未初始化。)”
【解决方案2】:

在这种情况下,保留一些延迟变量的默认值,如下所示。

 int oraNotifiche = 0;
 int minutiNotifiche = 0;

如果您无法在使用前进行初始化,请避免使用后期变量。

【讨论】:

    猜你喜欢
    • 2020-03-20
    • 2020-07-15
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2020-06-07
    相关资源
    最近更新 更多