首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在flutter中返回并显示计数结果json response api

如何在flutter中返回并显示计数结果json response api
EN

Stack Overflow用户
提问于 2021-03-19 23:06:05
回答 2查看 337关注 0票数 0

我创建了一个api,它使用laravel对数据库表中的总类别进行计数,并尝试在flutter中使用它并显示总计数值。我怎样才能做到这一点呢?

我的代码:

//Laravel查询计数

代码语言:javascript
复制
public function count_categories(){

    $count_category = DB::table('category_menu')
    ->count();

   return response()->json($count_category);
}

//颤动代码

//接口URL

代码语言:javascript
复制
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中显示响应体结果?

EN

回答 2

Stack Overflow用户

发布于 2021-03-19 23:20:53

如果我没有理解错的话,那么您在这里要做的就是序列化json响应,然后将其传递给Widget。

虽然关于你的目标的更多细节会很有用,但这里是

有很多方法可以做到这一点,但最基本的方法是使用json_serializable或在线converter

有关参考信息,请参阅此答案here

一旦您将json响应转换为Dart类(可能如下所示)

代码语言:javascript
复制
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()或适当的状态管理解决方案将其加载到小部件中。

代码语言:javascript
复制
class SampleWidget extends StatelessWidget {
  
  SampleWidget({this.model})
  
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(model.count),
    );
  }
}
票数 0
EN

Stack Overflow用户

发布于 2021-03-19 23:27:09

首先,根据我所看到的,从API中您发送的是数量( number ),因此当从flutter发出GET请求时,您将在正文中收到一个数字。

到目前为止一切正常,但是您必须修改函数的数据类型,您当前已经定义了:

代码语言:javascript
复制
Future<List<Category>> countCategory() async {...}

如果要返回值,则必须为此进行修改。

代码语言:javascript
复制
Future<int> countCategory() async {...}

现在,它也可以是void类型,但是您必须将该值保存在一个变量中,然后在相应的小部件中使用该变量。

代码语言:javascript
复制
Future<void> countCategory() async {
 ...
 setState(() {
  count = response.body; // Assuming the variable is globally defined.
 })
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66710692

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档