在我的Ffltter项目中,我正在通过GET请求执行API调用来获取数据.在从响应中解析出JSON object之后,我只在Text小部件中显示值.虽然加载数据需要时间,但与此同时,我的文本小部件显示为空.

对于API调用部分,我有以下代码-

class Webservice {
  Future<T> load<T>(Resource<T> resource) async {
    var jwt = await LocalStore().getJWT();
    print(jwt);

    final response = await http.get(resource.url,
        headers: {
          'Content-Type': 'application/json',
          'token': '${Constants.TOKEN}',
          'jwt': '$jwt',
        }
    );
    if(response.statusCode == 200) {
      print('${response.body}');
      return resource.parse(response);
    } else {
      throw Exception('Failed to load data!');
    }
  }
}

我的JSON解析得了Model class分-

class Category {
  int catNote;
  int catTodo;
  int catRem;
  int catTag;
  int catUrgent;
  int catWork;
  int catOffice;
  int catPersonal;
  
  Category(
      {this.catNote,
        this.catTodo,
        this.catRem,
        this.catTag,
        this.catUrgent,
        this.catWork,
        this.catOffice,
        this.catPersonal});

  Category.fromJson(Map<String, dynamic> json) {
    catNote = json['cat_note'];
    catTodo = json['cat_todo'];
    catRem = json['cat_rem'];
    catTag = json['cat_tag'];
    catUrgent = json['cat_urgent'];
    catWork = json['cat_work'];
    catOffice = json['cat_office'];
    catPersonal = json['cat_personal'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['cat_note'] = this.catNote;
    data['cat_todo'] = this.catTodo;
    data['cat_rem'] = this.catRem;
    data['cat_tag'] = this.catTag;
    data['cat_urgent'] = this.catUrgent;
    data['cat_work'] = this.catWork;
    data['cat_office'] = this.catOffice;
    data['cat_personal'] = this.catPersonal;
    return data;
  }

  static Resource<Category> get allCategory {
    return Resource(
        url: '${Constants.BASE_URL}category',
        parse: (response) {
          print('my result ${response.body}');
          final result = json.decode(response.body);

          Category category = Category.fromJson(result) ;
          return category;

        }
    );

  }

}

现在,在我的主类中,我已经创建了一个函数,如下所示-

  void _getAllCategories() {
    Webservice().load(Category.allCategory).then((newsArticles) => {
        setState(() => {
      _category = newsArticles
    })
  });
 }

之后,我调用了initState函数中的函数,并将值保存在_category对象中.

然后,在文本小部件的Widget build(BuildContext context)函数中,我使用了来自_category对象的值,如下所示,使用一个三元运算符来判断对象是否为空.如果为NULL,则应显示0,如果不为NULL,则应显示原始值-

child: _category ==null?
                Text('0',
                style: TextStyle(
                    fontSize: 30,
                    fontWeight: FontWeight.bold
                ),
                ):
                Text('${_category.catToDo}',
                  style: TextStyle(
                      fontSize: 30,
                      fontWeight: FontWeight.bold
                  ),
                )

但它仍然显示空,而数据加载只需几秒钟,并显示如下所示的输出-

enter image description here

所以,我需要一个解决方案来显示一个进度对话框,或者在加载数据需要时间时,将默认值显示为0.如果有人能帮我解决这个问题,那就太好了.

推荐答案

在加载期间,使用FutureBuilder控制渲染;

  final categories = Webservice().load(Category.allCategory);

  Widget build(BuildContext context) {
    return FutureBuilder(
      future: categories,
      builder: (ctx, snapshot) {
        var value = (snapshot.connectionState == ConnectionState.done) ? '${_category.catToDo}' : '0';

        return Text(
          value,
          style: TextStyle(
            fontSize: 30,
            fontWeight: FontWeight.bold
          ),
        );
      }
    );
  }

或者,如果要显示加载动画,请执行以下操作:

  final categories = Webservice().load(Category.allCategory);

  Widget build(BuildContext context) {
    return FutureBuilder(
      future: categories,
      builder: (ctx, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return Text(
            '${_category.catToDo}',
            style: TextStyle(
              fontSize: 30,
              fontWeight: FontWeight.bold
            ),
          );
        }
        else {
          return CircularProgressIndicator();
        }
      }
    );
  }

Dart相关问答推荐

在Flutter中通过 Function(T) 传递泛型类型

在Flutter中使用底部导航栏在页面之间传递数据

Flutter - 自定义按钮点击区域

如何在动态链接中传递参数?

IndexedDB访问速度和效率

在 Dart 中,是否可以有一个 const 闭包映射?

如何在 GridView (Flutter) 中进行分页

Flutter Drawer Widget - 更改 Scaffold.body 内容

如何在 Dart 中获取数字的长度?

Flutter 在 main 中读取共享首选项,然后决定哪个启动页面?

单击 TextField 小部件时 Flutter 小部件重建

在flatter中在容器内生成可滚动文本

dart的Completer和Future?

如何判断switch/case中对象的类型?

Dart 中的构造函数和初始化列表有什么区别?

可选参数的默认值必须是常量

安装 dart-sdk 后找不到 pub 命令

如何在 Dart 中从外部查询 shadow DOM 中的元素?

如何在 Dart 中为 Completer.CompleteException(exception, stackTrace) 获取当前堆栈跟踪;

在 Dart 中克​​隆list列表、map或set集合