我目前正在创建一个位置跟踪应用程序。它包含一个存储lat和long的后端。那么,我的flutter应用程序如何使用flutter中的http在特定的时间间隔内不断从服务器获取数据呢?
如果你想坚持使用HTTP,你可以使用Timer每隔一段时间请求服务器,并使用StreamBuilder更新小部件的状态,但我建议使用web套接字,检查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;
}
提取数据/活动流
正在提取数据