首页 > 解决方案 > 如何不断获取http数据?

问题描述

我目前正在创建一个位置跟踪应用程序。它包含一个存储 lat 和 long 的后端。那么,我的 Flutter 应用程序如何在 Flutter 中使用 http 以一定的时间间隔从服务器获取数据呢?

标签: androidiosflutter

解决方案


如果您想坚持使用 HTTP,您可以使用 Timer 每隔一段时间请求服务器并使用 StreamBuilder 更新小部件的状态,但我建议使用 web-sockets,请查看https://flutter.dev/docs/cookbook/网络/网络套接字

主要.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;
}

 

获取的数据/活动流

正在获取数据


推荐阅读