Flutter: 中断http请求

import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'dart:async';
import 'package:rxdart/rxdart.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DashPage(),
    );
  }
}

class DashPage extends StatefulWidget {
  @override
  _DashPageState createState() => _DashPageState();
}

class _DashPageState extends State<DashPage> {
  int _currentIndex = 0;
  final PageController _controller = PageController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        currentIndex: _currentIndex,
        fixedColor: Colors.purple,
        onTap: (int index) {
          setState(() {
            _currentIndex = index;
            _controller.jumpToPage(index);
          });
        },
        items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(
              icon: Icon(Icons.home),
              activeIcon: Icon(Icons.home),
              title: Text("Home")),
          BottomNavigationBarItem(
              icon: Icon(Icons.search),
              activeIcon: Icon(Icons.search),
              title: Text("Search")),
        ],
      ),
      body: PageView(
        controller: _controller,
        onPageChanged: (int index) {
          setState(() {
            _currentIndex = index;
          });
        },
        children: <Widget>[
          HomePage(),
          Center(child: Text('Search Page')),
        ],
      ),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState(homeService: HomeService());
}

class _HomePageState extends State<HomePage> {
  _HomePageState({this.homeService});
  final HomeService homeService;

  @override
  void dispose() {
    super.dispose();
    homeService.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('中断http请求.'),
      ),
      body: Center(
        child: StreamBuilder<String>(
            stream: homeService.text$,
            builder: (context, snapshot) {
              print(snapshot.hasError);
              if (snapshot.hasError) return Text('Error: ${snapshot.error}');

              if (snapshot.connectionState == ConnectionState.waiting ||
                  !snapshot.hasData) return Text('loading...');

              return Text(snapshot.data);
            }),
      ),
    );
  }
}

class HomeService {
  HomeService() {
    _getData();
  }

  Stream<String> get text$ => _textSubject.stream;
  final _textSubject = BehaviorSubject<String>();
  String _text = '';
  Client client = http.Client();

  dispose() {
    _textSubject.close();
    client.close();
  }

  _getData() async {
    try {
      var r = await client.get("http://192.168.0.103:3000");
      if (r.statusCode != 200) {
        _textSubject.addError(r.body);
      } else {
        _text = r.body;
        print(_text);
        _textSubject.add(_text);
      }
    } on http.ClientException catch (_) {
      // 无视掉请求中断错误
    }
  }
}
上一篇:第 5 章 Nova - 036 - Snapshot Instance 操作详解


下一篇:java中用过滤器解决字符编码问题