【问题标题】:Can't Access The Snapshot.data in Futurebuilder无法访问 Futurebuilder 中的 Snapshot.data
【发布时间】:2021-11-27 01:12:05
【问题描述】:

I Have created this class named DashboardModel with 4 items:

class DashboardModel {
  int status;
  String message;
  List<dynamic> errors;
  Data data;

  DashboardModel({
    this.status,
    this.message,
    this.errors,
    this.data,
  });
}

No problem here. 然后我有这个函数可以从我的 API 中获取信息,如下所示:

Future<DashboardModel> getDashboard() async {
    var url = "https://SomeAPI.kuttenbugeservice.ru";
    var _pref = await SharedPreferences.getInstance();
    String token = _pref.getString('token');
    var header = {'token': token, 'najvaToken': _pref.getString('najvaToken')};
    var response = await http.get(url, headers: header);
    //-----------------------------------------------------------------------
    var model = DashboardModel.fromJson(json.decode(response.body));
    return model;
  }

那我想获取getDashboard()返回的模型,显示如下:

FutureBuilder > builder > AnimatedSwitcher > child:

FutureBuilder(
          future: _service.getDashboard(),
          builder: (context, snapshot) {
            print('Must Be Ckecked${snapshot.data}');
            return AnimatedSwitcher(
                duration: const Duration(seconds: 1),
                child: (snapshot.connectionState == ConnectionState.waiting)
                    ? Align(
                        alignment: Alignment.center,
                        child: Container(
                          child: LinearProgressIndicator(
                            color: Colors.amber,
                          ),
                        ))
                    : **HomeViewPagerFul(
                   data: snapshot.data,
                 );**
                );
          },
        ),

问题从这里开始,因为包含loaded DashboardModel{snapshot.data} 不能作为内容传递给HomeViewPagerFul()

如下如你所见,我打印了 snapshot.data 以查看问题所在:

print('Must Be Ckecked${snapshot.data}');

但它会返回:

I/flutter ( 9806): Must Be Ckecked[Instance of 'DashboardModel']

================================================ ========

所以基本上仪表板模型很好。 getdashboard() 函数正在完成它的工作。 FutureBuilder 正在显示承诺,但我无法访问快照。

I can't use snapshot.data.status which I can Access in getDashboard()

只是我遇到了这个错误:

A value of type 'Object?' can't be assigned to a variable of type 'DashboardModel'.
Try changing the type of the variable, or casting the right-hand type to 'DashboardModel'.

HomeViewPagerFul()(如果需要):

class HomeViewPagerFul extends StatefulWidget {
  final DashboardModel data;

  HomeViewPagerFul({required this.data});

  @override
  _HomeViewPagerFulState createState() => _HomeViewPagerFulState();
}

【问题讨论】:

  • 你在使用 null-safety 吗?
  • 是的,但我认为这不是问题所在。正如我所说,{snapshot.data} 有一个值,但它不适合我的“DashboardModel”

标签: flutter flutter-layout flutter-dependencies flutter-animation


【解决方案1】:

您有 2 个问题:

  1. 您应该将类​​型指定为FutureBuilderFutureBuilder&lt;DashboardModel&gt;
  2. snapshot 在加载时没有数据,您应该检查snapshot.hasData 并在尚未获取数据时显示加载小部件

具体来说:

FutureBuilder<DashboardModel>(
  future: _service.getDashboard(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return LoadingWidget();
    }
    print('Must Be Ckecked${snapshot.data}');
    return AnimatedSwitcher(
      duration: const Duration(seconds: 1),
      child: (snapshot.connectionState == ConnectionState.waiting)
          ? Align(
              alignment: Alignment.center,
              child: Container(
                child: LinearProgressIndicator(
                  color: Colors.amber,
                ),
              ))
          : HomeViewPagerFul(
              data: snapshot.data!, // Safe since you checked if hasData
            ),
    );
  },
)

【讨论】:

  • 谢谢@Lulupointu!!不敢相信它奏效了!虽然我不得不在这里添加一个空安全标志(!):HomeViewPagerFul(data: snapshot.data!), 并做一个扑腾清洁但除此之外,一切都很好:
  • 哦,是的,你是对的,我更新了我的答案。 flutter clean 看起来很奇怪,但它不会受到伤害,所以为什么不呢:D
猜你喜欢
  • 2021-10-08
  • 1970-01-01
  • 1970-01-01
  • 2020-05-02
  • 1970-01-01
  • 2020-11-30
  • 2021-08-29
  • 2019-05-31
  • 2014-01-29
相关资源
最近更新 更多