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

标签 json flutter api dart flutter-layout

问题:
我试图拦截 SMS 消息正文,然后在每次遇到 SMS 时使用 POST Call 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
另外,我没有管理如何在后台拦截短信正文。
为了更好地理解这个错误,我将附上一些我的代码片段:
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');
        }
      });
  }
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);
   }
  }
电话插件用法:
 @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;
  }
处理错误函数
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");
    }
  }
用户界面级别:
Text("$body");

最佳答案

[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 ... 重构您的代码和 catch并且没有 catchError()需要。
解决方法(不是很好)解决方案:throw e; 在您的 handleError .

关于json - 无法在 flutter dart 中使用 REST API 发送截获的短信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69136806/

相关文章:

c# - 忽略 Json.net 中的空字段

firebase - 在没有用户交互的情况下在构建期间调用 setState()

api - Facebook API、iFrame 中的 Canvas 应用、Javascript API、IE8 中的损坏?

android - 在调试时按下 Dart DevTools 中的调试按钮之前,无法按下我的 Flutter 应用程序中的按钮

javascript - 了解 Passport.authenticate ('local' ) 语法位

node.js - 如何对sequelize 查询的每个结果进行API 调用?

PHP - 从数据库获取数据到 JSON

javascript - 工厂方法 HTTP 不工作

C# Flurl 和 HttpClient,REST API 无响应

flutter - 来自原生android的Channel Invokemethod不调用flutter方法