我尝试按照 flutter 文档进行操作 文字 但未能显示数据, 我怀疑问题出在 futureBuilder 中,尚未实现 try-catch,因为我不确定要调用什么。此外,当我在类声明级别使用
late Future futurePrayer;
时,数据会显示,但会出现调用错误。但如果我将 late Future<Prayer> futurePrayer;
与类类型注释一起使用,错误就会消失,但不会显示数据
错误图像:
错误图像仅用于显示数据示例
代码: 构建器功能
FutureBuilder(
future: futurePrayer,
builder: (context, snapshot) {
if (snapshot.hasData) {
// TODO: fix NoSuchMethodError: 'call
// Dynamic call of object has no instance method 'call'.
return Text(snapshot.data.ashar());
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
}
),
ApiBaseHelper / getter
Future<Prayer> ApiBaseHelper() async {
final response = await http
.get(Uri.parse('https://api.myquran.com/v2/sholat/jadwal/1420/2025-01-05'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Prayer.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
await ApiBaseHelper().catchError(print);
throw Exception('Failed to load album');
}
}
祈祷资料课
// this class is not used yet
class PrayerResponse {
List<String>? prayerTime;
PrayerResponse({
required this.prayerTime,
});
PrayerResponse.fromJson(Map<String, dynamic> json) {
prayerTime = json['data']['jadwal'];
}
}
class Prayer {
final int id;
final String lokasi;
final String daerah;
final String ashar;
Prayer(
{
required this.id,
required this.lokasi,
required this.daerah,
required this.ashar,
}
);
factory Prayer.fromJson(Map<String, dynamic> json) {
return Prayer(
id : json['data']['id'],
lokasi : json['data']['lokasi'],
daerah : json['data']['daerah'],
ashar : json['data']['jadwal']['ashar'],
);
}
}
当我检查你的代码时,有一件事引起了我的注意。您正在对来自未来的数据使用函数符号 ()。我认为这可能会导致问题。此外,在向 API 发出请求时使用 try catch 块可能更有助于查找错误源。
您可以尝试这些代码来解决。
FutureBuilder<Prayer>(
future: futurePrayer,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else if (snapshot.hasData) {
return Text('Ashar Time: ${snapshot.data!.ashar}');
} else {
return const Text('No data available');
}
},
),
Future<Prayer> ApiBaseHelper() async {
try {
final response = await http.get(
Uri.parse('https://api.myquran.com/v2/sholat/jadwal/1420/2025-01-05'),
);
if (response.statusCode == 200) {
return Prayer.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
} else {
throw Exception('Failed to load prayer data');
}
} catch (e) {
throw Exception('Error fetching data: $e');
}
}