我当前正在创建位置跟踪应用程序。它包含一个存储lat和long的后端。那么我的flutter应用程序如何在flutter中使用http继续在一定间隔内从服务器获取数据?
答案 0 :(得分:0)
如果要坚持使用HTTP,则可以在每个间隔内使用Timer请求服务器,并使用StreamBuilder更新小部件的状态,但是我建议使用网络套接字,请选中https://flutter.dev/docs/cookbook/networking/web-sockets。
main.dart
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;
import 'package:stream_builder_timer/user_model.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(body: MyWidget()),
);
}
}
class MyWidget extends StatelessWidget {
static const int totalItems = 10;
static StreamController<User> _streamController = StreamController<User>();
Timer timer = Timer.periodic(
new Duration(seconds: 1),
(Timer timer) async {
int randomId = Random().nextInt(11);
http
.get('https://jsonplaceholder.typicode.com/albums/$randomId')
.then((response) {
User user = User.parseJson(convert.jsonDecode(response.body));
_streamController.add(user);
});
// use some condition to cancel the timer
if (randomId == 10) {
timer.cancel();
}
},
);
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: _streamController.stream,
builder: (context, snapshot) {
debugPrint(snapshot.data.toString());
if (snapshot.connectionState == ConnectionState.active) {
return Center(child: Text(snapshot.data.title ?? ''));
}
return Center(child: CircularProgressIndicator());
});
}
}
user_model.dart
import 'package:meta/meta.dart';
class User {
int _userId;
int _id;
String _title;
User._({@required userId, @required id, @required title})
: this._userId = userId,
this._id = id,
this._title = title;
static User parseJson(dynamic json) {
return User._(userId: json['userId'], id: json['id'], title: json['title']);
}
int get userId => _userId;
int get id => _id;
String get title => _title;
}