【发布时间】:2021-05-25 22:41:41
【问题描述】:
当我尝试调用 api 时,它会被调用并到达 ListView.builder 中的 itemCount,但随后会显示类似这样的错误,
在 null 上调用了 getter 'length'。
class ChopperNewsCard extends StatefulWidget {
@override
_ChopperNewsCardState createState() => _ChopperNewsCardState();
}
class _ChopperNewsCardState extends State<ChopperNewsCard> {
ScrollController scrollController = ScrollController();
ApiCall apiCall = ApiCall();
ChopperNews res = ChopperNews();
Future<void> getResponse() async {
res = await apiCall.getNews(5);
}
@override
void initState() {
super.initState();
getResponse();
}
@override
void dispose() {
super.dispose();
scrollController.dispose();
}
@override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
return Container(
height: height * 0.37,
width: double.infinity,
child: ListView.builder(
itemCount: res.articles.length + 1, //<--------here length getting null
controller: scrollController,
physics: AlwaysScrollableScrollPhysics(),
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemBuilder: (context, index) {
if (index == res.articles.length) {
if (index == res.totalResults) {
return null;
} else {
return Center(child: CircularProgressIndicator());
}
} else {
return Container(
width: width * 0.70,
padding: EdgeInsets.only(right: width * 0.05),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
elevation: 3,
child: Column(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(15),
child: CachedNetworkImage(
imageUrl: res.articles[index].urlToImage == null
? Url.noImage
: res.articles[index].urlToImage,
fit: BoxFit.cover,
width: double.infinity,
height: height * 0.2,
placeholder: (context, url) =>
Center(child: CircularProgressIndicator()),
errorWidget: (context, url, error) =>
Icon(Icons.error_outline_sharp),
),
),
],
),
),
);
}
},
),
);
}
}
从我尝试调用我的 api 的位置,
import 'package:chopper/chopper.dart';
import '../models/chopper_news.dart';
import 'chopper_api_service.dart';
class ApiCall {
ChopperApiService chopperApiService;
Future<ChopperNews> getNews(int page) async {
chopperApiService = ChopperApiService.create();
var apiResponse = await chopperApiService.getNews(pageSize: page);
return apiResponse.body;
}
}
在调试模式下,它会在长度被称为 null 后显示响应,所以我认为我的 api 调用工作正常
【问题讨论】: