首页 > 解决方案 > 抛出异常时,快照会包含错误吗?

问题描述

此方法发送消息并返回Future<bool>。我的情况是,当状态不是 200 时,快照会包含错误,还是会通过引发异常而使整个应用程序崩溃?

Future<bool> sendMessage(String id, String message) async {
  /* sendind logic */
  if (r.statusCode == 200) {
    return true;
  } else {
    print('Failed to send message. Status code: ${r.statusCode}');
    throw Exception('Failed to send message. Status code: ${r.statusCode}');
  }
}

并以这种方式进行

FutureBuilder(
    future: result,
    builder: (context, snapshot) {
      if (snapshot.hasData) {
      return Center(child: Text('Success'));
      } else if (snapshot.hasError) {
        return Center(child: Text("${snapshot.error}"));
      }
      return kLoading;
    },
  ),

如果方法返回Future<void>,我应该如何检查 FutureBuilder 是否已完成?

标签: flutterdart

解决方案


AsyncSnapshot是从与异步计算(例如服务器 API 调用、sqlite 数据库调用、shreadpref 调用等)的最新交互中接收到的结果的不可变表示。

snapshot.error因此,如果最新的计算导致该对象在该字段中也会出现错误(异常) 。所以在你的情况下,代码应该如下所示:

@override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: result,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            // Data is avialable. call snapshot.data 
          }
          else if(snapshot.hasError){     
             // Do error handling
          }
          else {
            // Still Loading. Show progressbar
          }
        });
  }

推荐阅读