我创建了一个api,它使用laravel对数据库表中的总类别进行计数,并尝试在flutter中使用它并显示总计数值。我怎样才能做到这一点呢?
我的代码:
//Laravel查询计数
public function count_categories(){
$count_category = DB::table('category_menu')
->count();
return response()->json($count_category);
}//颤动代码
//接口URL
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正确打印计数值,如何在类widget中显示响应体结果?
发布于 2021-03-19 23:20:53
如果我没有理解错的话,那么您在这里要做的就是序列化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()或适当的状态管理解决方案将其加载到小部件中。
class SampleWidget extends StatelessWidget {
SampleWidget({this.model})
@override
Widget build(BuildContext context) {
return Container(
child: Text(model.count),
);
}
}发布于 2021-03-19 23:27:09
首先,根据我所看到的,从API中您发送的是数量( number ),因此当从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.
})
}https://stackoverflow.com/questions/66710692
复制相似问题