【问题标题】:Unable to send the intercepted sms using REST API in flutter dart无法在颤振飞镖中使用 REST API 发送拦截的短信
【发布时间】:2021-11-07 05:15:18
【问题描述】:

问题: 我试图拦截 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

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

为了更好地理解这个错误,我将附上我的一些代码 sn-ps:

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");

【问题讨论】:

  • 是否将print(e); 更改为throw(e);,修复错误?您必须返回与帖子中的错误状态相同类型的对象。或者返回一个已初始化的类或将其更改为可为 null 并返回 null,然后在调用此函数的另一端检查返回的值是否为 null。
  • 已尝试将print(e); 更改为throw(e);,但错误仍然存​​在
  • 你的handleError函数是什么,粘贴一下
  • 一定是handleError的问题——如错误信息所说
  • @ch271828n 请检查我是否添加了handleError函数

标签: json flutter api dart flutter-layout


【解决方案1】:

[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

【讨论】:

  • 看到,handleError 函数在我调用所有其他 API 调用时执行得非常好,但是在这种特殊的 SMS 拦截期间,然后发送数据导致错误
  • 不,它还没有解决我的问题
猜你喜欢
  • 1970-01-01
  • 2019-10-21
  • 2020-08-12
  • 2020-11-05
  • 2019-01-07
  • 2020-11-28
  • 2020-01-28
  • 2019-02-05
  • 1970-01-01
相关资源
最近更新 更多