【发布时间】:2020-05-20 04:34:18
【问题描述】:
我收到了回复,但问题是,当我点击我的 api 时,它首先显示 Getter Iterator Was Called On Null,然后在数据加载后显示。
这是我的实用程序类。
class BlocApi with ChangeNotifier {
BlocApi.instance() {
getAllItems();
}
List<Categories> _items;
List<Categories> get getItems => _items;
setItems(List<Categories> items) async {
_items = items;
notifyListeners();
}
Future<void> getAllItems() async {
Response response = await get('api Link');
if (response.statusCode == 200) {
var data = json.decode(response.body);
var rest1 = data['Categories'] as List;
List<Categories> totalList = new List<Categories>();
for (var u in rest1) {
final items1 = Categories.fromJson(u);
totalList.add(items1);
}
setItems(totalList);
} else {}
}
}
然后这是我的第一个选项卡,我将我的 api 调用到不同的选项卡。
class _BevaragesState extends State<Bevarages> {
List<Itemsss> _items = new List<Itemsss>();
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
final BlocApi blocApi = Provider.of<BlocApi>(context);
for (var u in blocApi.getItems) {
if (u.categoryName == 'Bevarages') {
for (var v in u.items) {
_items.add(v);
}
}
}
return Scaffold(
body: Container(
child: ListView.builder(
itemCount: blocApi.getItems == null ? 0 : _items.length,
itemBuilder: (BuildContext context, int index) {
return Container(
margin: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 25.0),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Flexible(
flex: 1,
child: Container(
margin: EdgeInsets.only(left: 5.0),
child: Image.network(
'http://dum9b973t0902.cloudfront.net/${_items[index].itemImage}',
height: 70.0,
width: 70.0,
),
),
),
Flexible(
flex: 2,
child: Container(
margin: EdgeInsets.only(left: 5.0),
child: Column(
children: <Widget>[
Container(
alignment: Alignment.centerLeft,
child: Wrap(
children: <Widget>[
Text(
_items[index].itemName,
style: TextStyle(
fontFamily: 'Arimo',
fontWeight: FontWeight.w700,
fontStyle: FontStyle.normal,
fontSize: 15.0,
),
),
],
),
),
Container(
margin: EdgeInsets.only(top: 5.0),
child: Row(
children: <Widget>[
Text(
'Price : ',
textAlign: TextAlign.left,
),
Text(
_items[index].price,
style: TextStyle(
fontFamily: 'Arimo',
fontWeight: FontWeight.w400,
fontStyle: FontStyle.normal,
fontSize: 13.0,
decoration: TextDecoration.lineThrough,
),
),
],
),
),
【问题讨论】:
-
您可以使用 FutureBuilder 包装您的 ListView,或者您可以使用三元运算符检查您的响应状态。如果不是 200 则显示 CircularProgressIndicator,如果是 200 则显示列表视图。
-
是的,我正在检查状态,它即将到来 200。我对我的问题有一些疑问。 1. M 使用提供者,所以 m 在 Build 方法中使用上下文?如果我不会在构建方法中使用,那么我的代码会抛出错误。
-
是的,您应该使用上下文,因为您使用的是 Provider。
-
是的,这是这里的主要问题,我在构建方法中使用我的上下文,这就是为什么我的列表在第一个选项卡活动加载时变为空的原因。所以我想解决这个问题。我想在列表为空时显示闪烁效果意味着当我的活动处于初始化状态时
-
那么,最好将该逻辑移至 bloc。
标签: flutter dart flutter-layout flutter-test