【发布时间】: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