如何在Flutter中调用Laravel分类计数API并展示统计结果
嘿,你已经成功拿到API返回的计数结果啦,接下来只需要把这个数字优雅地展示到Flutter界面上就行,我给你梳理下具体步骤:
第一步:修正Flutter的API请求函数
你的现有函数返回类型不太匹配(API返回的是单个数字而非List<Category>),同时还要注意URL拼接和http.get的参数要求,调整后的代码如下:
// 记得替换成你的Laravel服务器实际地址(本地测试别用localhost,用电脑IP) static const String BASE_URL = "http://192.168.xxx.xxx:8000"; static const COUNT_CATEGORY = "/count_category"; Future<int> countCategory() async { // 拼接完整的API地址 String fullUrl = "$BASE_URL$COUNT_CATEGORY"; Map<String, String> headers = {'Accept': 'application/json'}; // http.get现在需要传入Uri对象,不能直接传字符串 var response = await http.get(Uri.parse(fullUrl), headers: headers); if (response.statusCode == 200) { // 将返回的字符串格式数字转为int类型 return int.parse(response.body); } else { // 请求失败时抛出异常,方便后续处理错误 throw Exception("加载分类总数失败"); } }
第二步:用FutureBuilder在Widget中展示数据
因为API请求是异步操作,Flutter提供了FutureBuilder组件专门处理这类异步数据的展示逻辑,它会根据请求的不同状态(加载中、成功、失败)自动渲染对应的UI:
class CategoryCountPage extends StatelessWidget { // 初始化请求Future,确保只发起一次请求 final Future<int> _categoryCountFuture = countCategory(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text("分类总数统计")), body: Center( child: FutureBuilder<int>( future: _categoryCountFuture, builder: (context, snapshot) { // 根据异步请求的状态展示不同内容 if (snapshot.connectionState == ConnectionState.waiting) { // 加载中:显示圆形加载指示器 return const CircularProgressIndicator(); } else if (snapshot.hasError) { // 请求失败:显示错误信息 return Text("加载失败:${snapshot.error}"); } else if (snapshot.hasData) { // 请求成功:展示统计数字 return Text( "分类总数:${snapshot.data}", style: const TextStyle( fontSize: 22, fontWeight: FontWeight.bold ), ); } else { // 无数据情况的兜底展示 return const Text("暂无数据"); } }, ), ), ); } }
一些额外注意点
- 如果是本地测试Laravel,不要用
localhost作为BASE_URL,换成你的电脑局域网IP(比如192.168.1.100),不然Flutter模拟器/真机可能访问不到API。 - 确保你的Laravel项目已经配置了CORS跨域支持,不然会出现请求被拦截的问题(可以用
barryvdh/laravel-cors包快速配置)。 - 如果需要手动刷新计数(比如加个刷新按钮),可以把
Future放到StatefulWidget的state里,通过setState重新发起请求。
内容的提问来源于stack exchange,提问作者Otis
相关产品推荐
相关产品推荐

