为Flutter代码添加try-catch块报错:期望类成员
解决Flutter中"Expected a class member"报错问题
你的报错原因很明确:try-catch块不能直接放在类的顶层作用域中,Dart类的直接成员只能是变量、方法、构造函数这类元素,而try-catch是语句,必须放在方法或函数内部。
修正后的代码如下:
import 'package:http/http.dart'; import 'dart:convert'; class WorldTime { String location; // UI显示的地区名称 late String time; // 该地区的时间 String flag; // 国旗图标的资源路径 String url; // API接口的地区路径 WorldTime(this.location, this.time, this.flag, this.url); Future<void> getTime() async { try { Response response = await get(Uri.parse('http://worldtimeapi.org/api/timezone/$url')); Map data = jsonDecode(response.body); String dateTime = data['datetime']; String offSet = data['utc_offset'].substring(1, 3); DateTime now = DateTime.parse(dateTime); now = now.add(Duration(hours: int.parse(offSet))); time = now.toString(); } catch (e) { // 这里可添加异常处理逻辑,比如打印错误或给time赋值默认值 print('请求出错: $e'); time = '获取时间失败'; } } }
关键修改点:
- 将try-catch块移动到
getTime方法内部,包裹所有可能抛出异常的异步操作(网络请求、JSON解析、字符串截取、类型转换等) - 保留方法的
async关键字,确保await能正常使用 - 在catch块中补充实际的异常处理逻辑,避免程序崩溃或给用户反馈错误信息
内容的提问来源于stack exchange,提问作者HungerMadra
相关产品推荐
相关产品推荐

