美文网首页Flutter
Flutter StreamController基础应用,异步刷

Flutter StreamController基础应用,异步刷

作者: 翟小乙 | 来源:发表于2020-10-13 08:24 被阅读0次

    StreamController基础使用,不带缓存数据

    TestStreamControl 界面

    import 'package:flutter/material.dart';
    import 'package:flutter_home/ui/pages/paybillquery/sss.dart';
    
    class TestStreamControl extends StatefulWidget{
      @override
      State<StatefulWidget> createState() {
        return  TestStreamControlState();
      }
    }
    class TestStreamControlState extends State<TestStreamControl>{
      LoginBloc _loginBloc;
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text("StreamControl基础"),),
          body: Center(child: RaisedButton(onPressed: (){
    
            _loginBloc?.login(context, "zyj", "123456");
    
          },child: Text("登录"),),),
        );
      }
      @override
      void initState() {
        //初始化Stream
        _loginBloc = LoginBloc();
        super.initState();
      }
      @override
      void dispose() {
        //销毁Stream
        _loginBloc.dispose();
        super.dispose();
      }
    }
    

    LoginBloc 封装StreamController

    //这里主要处理登录页面的逻辑
    import 'dart:async';
    import 'package:dio/dio.dart';
    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter_home/model/user_models.dart';  
    
    class LoginBloc {
    
      UserModel _userModel;
      StreamController<UserModel> _streamController;
    
      LoginBloc(){
        _userModel=UserModel();
        _streamController= StreamController();
      }
      Stream<UserModel> getStream(){
        return _streamController.stream;
      }
    
      void login(BuildContext context,String name,String pwd) async{
        //做耗时操作
        if(name==""){
          print("请输入用户名");
          return;
        }
        if(pwd==""){
          print("请输入密码");
          return;
        } 
         
        _streamController.sink.add(_userModel);
        Response response =await Dio().request("www.baidu.com");
        if (response.statusCode == 200) {
          _userModel.phone="15732191826";
          _streamController.add(_userModel);
        } 
      }
      void dispose(){
        _streamController.close();
      }
    }
    

    相关文章

      网友评论

        本文标题:Flutter StreamController基础应用,异步刷

        本文链接:https://www.haomeiwen.com/subject/buefektx.html