如何解决如何在flutter中返回并显示计数结果json响应api
我创建了一个 api,它使用 laravel 计算我的数据库表中的总类别,并试图在 flutter 中使用它并显示总计数值。请问我怎样才能做到这一点
我的代码:
//Laravel Query 计数
public function count_categories(){
$count_category = DB::table('category_menu')
->count();
return response()->json($count_category);
}
//颤动代码
//API 网址
static const COUNT_CATEGORY = "/count_category";
Future<List<Category>> countCategory() async {
String countCategory = COUNT_CATEGORY;
Map<String,String> headers = {'Accept': 'application/json'};
var response = await http.get(countCategory,headers: headers);
if (response.statusCode == 200) {
var body = jsonDecode(response.body);
print(response.body);
}
}
//response.body 正确打印计数值,如何在类小部件中显示响应正文结果?
解决方法
如果我正确理解您在此处尝试做的是序列化 json 响应,然后将其传递到 Widget。
虽然关于您的目标的更多详细信息会很有用,但它在这里
有很多方法可以做到,但最基本的方法是使用 json_serializable 或在线 converter。
如需参考,请参阅此答案 here。
一旦您将 json 响应转换为 Dart 类(可能看起来像)
class SampleModel {
String name;
int count;
SampleModel({this.name,this.count});
// You use this function to make a instance
// of class SampleModel and use it inside an UI Widget
SampleModel.fromJson(Map<String,dynamic> json) {
name = json['name'];
count = json['count'];
}
Map<String,dynamic> toJson() {
final Map<String,dynamic> data = new Map<String,dynamic>();
data['name'] = this.name;
data['count'] = this.count;
return data;
}
}
现在您可以使用 FutureBuilder、setState() 或适当的状态管理解决方案将其加载到 Widget 中。
class SampleWidget extends StatelessWidget {
SampleWidget({this.model})
@override
Widget build(BuildContext context) {
return Container(
child: Text(model.count),);
}
}
,
首先,据我所知,从 API 中您发送的是金额(数字),因此当从 Flutter 发出 GET 请求时,您将在正文中收到一个数字。
到目前为止一切都很好,但您必须修改函数的数据类型,您当前已定义:
Future<List<Category>> countCategory() async {...}
如果你想返回值,你必须为此修改它。
Future<int> countCategory() async {...}
现在,它也可以是 void 类型,但您必须将该值保存在一个变量中,然后在相应的小部件中使用该变量。
Future<void> countCategory() async {
...
setState(() {
count = response.body; // Assuming the variable is globally defined.
})
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。