代码之家  ›  专栏  ›  技术社区  ›  Lakshman Pilaka

Flutter-initState期望Future的返回值<String>

  •  0
  • Lakshman Pilaka  · 技术社区  · 1 年前

    我以前有代码可以工作,但在引入零安全之后,下面的代码出现了错误

    The body might complete normally, causing 'null' to be returned, but the return type, 'Future<String?>', is a potentially non-nullable type.
    Try adding either a return or a throw statement at the end.
    

    下面是代码,不确定需要更改什么

    @override
      void initState() {
        SystemChannels.lifecycle.setMessageHandler((msg) {
          // debugPrint('SystemChannels> $msg');
          super.initState();
    
          if (msg == AppLifecycleState.resumed.toString()) {
            // print("in resumed of payments");
            setState(() {
              dataLoaded = false;
            });
            customerPayments();
          } else {
            throw Exception("In Else");
          }
        });
      }
    

    customerPayments() 是一种void方法。

    1 回复  |  直到 1 年前
        1
  •  0
  •   Tyler2P Suraj Mandal    1 年前

    您已经在 initState 并且该函数需要每个可能结果的返回值。然而,在其他问题中,你不应该打电话 super.initState() 在您在其中声明的函数内部。你可以在之前或之后称之为,这取决于你在做什么。

    从本质上讲,对于这个特定的错误消息,它基本上是说,据Flutter所知,函数可能会在没有潜在返回值的情况下结束,从而返回null。

    https://api.flutter.dev/flutter/widgets/State/initState.html

    @override
    void initState() {
      SystemChannels.lifecycle.setMessageHandler((msg) {
        // debugPrint('SystemChannels> $msg');
        super.initState();
    
        if (msg == AppLifecycleState.resumed.toString()) {
          // print("in resumed of payments");
          setState(() {
            dataLoaded = false;
          });
          customerPayments();
        } else {
          throw Exception("In Else");
        }
        //Return statement would go here.
      });
    }