无法在flutter dart中使用REST API发送拦截的短信

Pra*_*nha 5 api json dart flutter flutter-layout

问题: 我尝试拦截 SMS 消息正文,然后每次遇到 SMS 时使用 POST 调用 REST API 将消息正文发送到数据库。整个拦截和发送消息正文也应该在后台工作,而且也是自动进行的。

到目前为止我所取得的成就: 我使用电话插件来拦截消息正文,并且每次在 UI 级别收到消息正文时都能够打印消息正文,但无法调用 API 并发送 SMS 正文。

错误: 由于我没有找到如何在每次截获新消息时自动调用 API 的方法,因此我使用按钮来调用它,但即使这样也不起作用,它会抛出错误:

[error:flutter/lib/ui/ui_dart_state.cc(209)] unhandled exception: invalid argument(s) (onerror): the error handler of future.catcherror must return a value of the future's type
Run Code Online (Sandbox Code Playgroud)

另外,我没有管理如何在后台拦截短信正文。

为了更好地理解这个错误,我将附上一些代码片段:

API使用函数:

String body = "";
  DateTime currentPhoneDate = DateTime.now();
  final telephony = Telephony.instance;
  interceptMessage() {
    final messaging = ApiService();
    messaging.interceptedMessage({
      "id": 50,
      "body": "$body",
      "senderName": "IDK",
      "timeStamp": "2021-10-02 12:00:55"
    })
      ..then((value) {
        if (value.status == "Success") {
          print('Message Intercepted');
        } else {
          print('Somethig went wrong');
        }
      });
  }
Run Code Online (Sandbox Code Playgroud)

API类:

Future<SmsResponse> interceptedMessage(dynamic param) async {
    var client = http.Client();

    String? token = await storage.readSecureToken('key');
    if (token == null) {
      throw Exception("No token stored in storage");
    }
    try {
      var response = await client
          .post(
            Uri.https("baseURL", "endpoint"),
            headers: <String, String>{
              'Authorization': 'Token $token',
            },
            body: param,
          )
          .timeout(Duration(seconds: TIME_CONST))
          .catchError(handleError);
      if (response.statusCode == 200) {
        print('Response Body: ${response.body}');
        final data = await jsonDecode(response.body);
        return SmsResponse.fromJson(data);
      } else if (response.statusCode == 401) {
        print("Unauthorized Request");
        return param;
      } else {
        print("Bad Input");
        return param;
      }
    } catch(e){
      print(e);
   }
  }
Run Code Online (Sandbox Code Playgroud)

电话插件用法:

 @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  onMessage(
    SmsMessage message,
  ) async {
    setState(() {
      body = message.body ?? "Error reading message body.";
      print("$body");
    });
  }

  onSendStatus(SendStatus status) {
    setState(() {
      body = status == SendStatus.SENT ? "sent" : "delivered";
    });
  }

  Future<void> initPlatformState() async {
    final bool? result = await telephony.requestPhoneAndSmsPermissions;

    if (result != null && result) {
      telephony.listenIncomingSms(
        onNewMessage: onMessage,
        onBackgroundMessage: onBackgroundMessage,
        listenInBackground: true,
      );
    }
    if (!mounted) return;
  }
Run Code Online (Sandbox Code Playgroud)

处理错误函数

void handleError(error) {
    //hideLoading();
    if (error is BadRequestException) {
      var message = error.message;
      DialogHelper.showErroDialog(description: message);
    } else if (error is FetchDataException) {
      var message = error.message;
      DialogHelper.showErroDialog(description: message);
    } else if (error is ApiNotRespondingException) {
      DialogHelper.showErroDialog(
          description: 'Oops! It took longer to respond.');
    } else if (error is SocketException) {
      print(
          error); //Have to remove this part this is already being handled at the service level
    } else {
      print("All OK");
    }
  }
Run Code Online (Sandbox Code Playgroud)

用户界面级别:

Text("$body");
Run Code Online (Sandbox Code Playgroud)

fzy*_*cjy 3

看着[error:flutter/lib/ui/ui_dart_state.cc(209)] unhandled exception: invalid argument(s) (onerror): the error handler of future.catcherror must return a value of the future's type

它说catcherror处理程序。那么让我们看看你的handleError函数。

如您所见,handleError 不返回任何内容。换句话说,它(自动)返回 null。

另一方面,看看你的var response = await client.post().catchError(),你的 client.post() 必须返回一些类型,例如 Response 或类似的东西。这就是错误所说的。

好的解决方案:花一个小时学习 Flutter 中的 async/await!稍后你会发现它非常非常有帮助。await ...然后使用and重构代码,catch不需要catchError()

解决方法(不太好)解决方案:throw e; 在您的 handleError.