【问题标题】:Retrieved data is not showing up in widget检索到的数据未显示在小部件中
【发布时间】:2018-12-06 16:36:48
【问题描述】:

我的服务器上托管了一个 json 文件,看起来像这样。

{
  "score": "23/6"
}

分数一直在更新,我希望我的 Flutter 应用显示实时分数。

Flutter 代码在这里:

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
var json_score;
var json_overs;

class livee extends StatefulWidget {
  @override
  _liveeState createState() => _liveeState();
}

class _liveeState extends State<livee> {

  final String url = "path_to_my_json";

  @override
  void initState(){
    super.initState();
    this.getJsonData();
  }

  Future<String> getJsonData() async{
    http.Response response = await http.get(
      Uri.encodeFull(url),
      headers: {"Accept" : "application/json"}
    );


     var data = jsonDecode(response.body);
     json_score = data['score'];


     print(json_score.toString());

  }

  @override
  Widget build(BuildContext context) {

    //Status bar
    final status = Text(
        "XYZ College",
        style: TextStyle(fontSize: 12.0, fontWeight: FontWeight.bold),
        textAlign: TextAlign.center);


    final score = Container(
      alignment: Alignment(0.0, 0.0),
      child: Text(json_score.toString(),
          style: TextStyle(
              fontSize: 50.0,
              color: Colors.blueAccent,
              fontWeight: FontWeight.bold)),
    );


    return new Container(
      color: Colors.white,
      height: MediaQuery.of(context).size.height,
      child: ListView(
        shrinkWrap: true,
        children: <Widget>[
          livestatus,
          score,

        ],
      ),
    );
  }
}

我设法将分数添加到我的应用中,但它需要刷新应用才能显示更新后的分数。我怎样才能使这个以间隔更新分数?

【问题讨论】:

    标签: android asynchronous flutter hybrid-mobile-app


    【解决方案1】:

    这里缺少一些东西。

    首先,您已经使var json_score;var json_overs; 本质上是全局变量,我很确定这不是您的本意。除非您有非常具体的原因,否则通常不应在类之外使用(非常量)变量,因为它们将在对象的所有实例之间共享。

    此外,Flutter 的有状态小部件的工作方式是,当您更改其状态时,flutter 引擎会检查对象是否已更改,并且只有在更改时才重新构建。如果变量不在对象中,则对象不会发生变化,因此不会重建。

    您缺少的另一件事是,每次更改 State 对象的“状态”时,您都应该调用 setState(...) 并在该函数中执行状态突变。

    我已经稍微修改了你的代码:

    import 'dart:async';
    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    
    class Livee extends StatefulWidget {
      @override
      _LiveeState createState() => _LiveeState();
    }
    
    class _LiveeState extends State<Livee> {
      final String url = "path_to_my_json";
    
      var jsonScore;
      var jsonOvers;
    
      @override
      void initState() {
        super.initState();
        this.getJsonData();
      }
    
      Future<String> getJsonData() async {
        http.Response response = await http.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
    
        var data = jsonDecode(response.body);
    
        setState(() => jsonScore = data['score']);
    
        print(jsonScore.toString());
      }
    
      @override
      Widget build(BuildContext context) {
        //Status bar
        final status =
            Text("XYZ College", style: TextStyle(fontSize: 12.0, fontWeight: FontWeight.bold), textAlign: TextAlign.center);
    
        final score = Container(
          alignment: Alignment(0.0, 0.0),
          child: Text(jsonScore.toString(),
              style: TextStyle(fontSize: 50.0, color: Colors.blueAccent, fontWeight: FontWeight.bold)),
        );
    
        return new Container(
          color: Colors.white,
          height: MediaQuery.of(context).size.height,
          child: ListView(
            shrinkWrap: true,
            children: <Widget>[
              livestatus,
              score,
            ],
          ),
        );
      }
    }
    

    这应该更适合你,虽然我个人建议考虑将分数检索分成不同的类,并使用 StreamBuilder 将其连接到你的类,而不是你如何做,但这更多复杂。

    我还有其他一些与问题无关的评论,但与您的代码有关。

    1. 当您在 StackOverflow 上发帖时,如果您将代码缩减为您遇到的问题,这会很有帮助。这段代码没有那么长,所以解析起来并不难,但是如果你有一个复杂的问题,它可能是一个问题(你的问题越好,它就越有可能得到快速和有帮助的回答 =D )
    2. 我建议阅读并关注您的代码中的the dart style guide 和/或flutter style guide。遵循标准将使您的代码更清晰,更容易被其他人使用,这将使您更容易与其他人合作(即使您当前的项目只是为您准备的)。
    3. 您似乎略微遗漏了一些颤振的基本概念。他们在flutter.io website 上有一些实际上非常棒的教程 - 从长远来看,如果你花一点时间阅读和编写代码来遵循教程,你可能会节省自己的时间和头痛,因为你会学到更多那样。 This is the one 特别展示了有状态小部件的工作方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 2015-01-23
      • 2018-03-14
      • 2021-04-26
      相关资源
      最近更新 更多