【发布时间】: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