首页 > 解决方案 > 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”异常触发......我无法弄清楚这一切。

如果有任何帮助,我将不胜感激。

标签: flutterfuture

解决方案


您应该始终检查是否snapshot没有error.

在您的情况下,您会收到错误,因为您使用 定义了变量var,这很棘手且容易出错,因为您没有得到编译器的全面帮助来让您知道您的代码将在运行时中断。始终尝试使用完全类型化的变量来避免这个陷阱,所以也要避免dynamic

您必须在存储库类中返回与T您相同类型的变量。Future<T>

此外,尽量不要丢弃 Exception 变量,以某种方式将其传递给新的 Exception 对象(将其应用到String或理想情况下,将其作为内部 Exception 传递给构造函数),它包含调试代码的有用信息。


推荐阅读