无法访问 Futurebuilder 中的 Snapshot.data

Can't Access The Snapshot.data in Futurebuilder

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}');

但是 returns :

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

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

所以基本上 Dashboard 模型没问题。 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();
}

您有 2 个问题:

  1. 您应该将类​​型指定为 FutureBuilderFutureBuilder<DashboardModel>
  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
            ),
    );
  },
)