flutter - Flutter Sql FutureBuilder 快照 null
问题描述
再次。对我来说,期货似乎是一个持续不断的困惑之源。
我正在尝试在页面上使用 FutureBuilder,但 snapshot.data 始终为空,即使我可以在 DBprovider 返回之前打印数据。
我有使用 initState 来创建未来的“CentreDetailScreen”类。
class _CentreDetailScreenState extends State<CentreDetailScreen> {
Future centreFuture;
@override
void initState() {
super.initState();
centreFuture = widget._centresBloc.getCentre(widget.centreReference);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: centreFuture,
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return CircularProgressIndicator();
case ConnectionState.active:
case ConnectionState.waiting:
return CircularProgressIndicator();
case ConnectionState.done:
print('snapshot: ${snapshot.data}'); <-always null
return Container(...//build UI
在 CentresBloc 我有:
Future<ClimbingCentre> getCentre(String centreId) async {
print('BloC get Centre'); <-- this prints
var _centre = await ClimbDB.db.getCentre(centreId);
print('Bloc has got a centre $_centre') <-- this doesn't
return _centre;
}
然后 DBprovider ClimbDB 有:
Future<ClimbingCentre> getCentre(String centreId) async {
try {
var map = Map<String, dynamic>();
map['action'] = _GET_ONE_ACTION;
map['centreId'] = centreId;
final response = await http.post(
'http://xxx.xxx.xx.x/flutter/climbinside/centre.php',
body: map);
if (200 == response.statusCode) {
var centre = json.decode(response.body);
var toReturn =
centre.map((centre) => new ClimbingCentre.fromJson(centre));
print($toReturn); <-prints 'instance of ClimbingCentre'
return toReturn;
} else {
throw Exception('we were not able to download json data');
}
} catch (e) {
throw Exception('Get centre: unable to download JSON');
}
}
我尝试了很多不同的东西......有时我会收到关于 Future 不是 Future 的子类型的错误......其他人会导致“无法下载 JSON”异常触发......我无法弄清楚这一切。
如果有任何帮助,我将不胜感激。
解决方案
您应该始终检查是否snapshot
没有error
.
在您的情况下,您会收到错误,因为您使用 定义了变量var
,这很棘手且容易出错,因为您没有得到编译器的全面帮助来让您知道您的代码将在运行时中断。始终尝试使用完全类型化的变量来避免这个陷阱,所以也要避免dynamic
。
您必须在存储库类中返回与T
您相同类型的变量。Future<T>
此外,尽量不要丢弃 Exception 变量,以某种方式将其传递给新的 Exception 对象(将其应用到String
或理想情况下,将其作为内部 Exception 传递给构造函数),它包含调试代码的有用信息。
推荐阅读
- active-directory - 预验证密码复杂性 .NET AD userPrincipal
- python - .txt 文件的 Python 字数统计程序不断将字符串索引超出范围显示为错误代码
- python - 如何在 sFTP 服务器上读取 gzip 压缩的 zip 文件?
- r - 创建一个循环来子集数据并合并空间数据图以创建 gif
- simics - Simics 1.1.0 "run-command-file targets\qsp-x86\firststeps.simics" 在启用反向执行时中断
- node.js - Nuxt 随每个请求更新会话 cookie
- javascript - 当我尝试使用 npm 安装 Brain.js 时遇到问题
- docker - 无法连接到主机外部的 Podman 容器
- r - 自动化脚本替换单词?
- python - 尝试从数据框中打开文本文件但索引超出范围错误