美文网首页Flutter
Flutter网络请求的处理和保持部件的状态

Flutter网络请求的处理和保持部件的状态

作者: StevenHu_Sir | 来源:发表于2019-07-31 20:21 被阅读0次

    一、网络请求的处理

    import 'package:flutter/material.dart';
    import '../const.dart';
    import 'dart:convert';
    import 'package:http/http.dart' as http;
    import 'chat.dart';
    
    class ChatPage extends StatefulWidget {
      @override
      _ChatPageState createState() => _ChatPageState();
    }
    class _ChatPageState extends State<ChatPage> {
      List<Chat> _datas = [];
      bool _cancelConnect = false; //多次请求!
      @override
      void initState() {
        super.initState();
        getDatas().then((List<Chat> datas) {
          if(!_cancelConnect){
            setState(() {
              _datas = datas;
            });
          }
        }).catchError((e) {
          print('error$e');
        }).whenComplete((){
          print('完毕');
        }).timeout(Duration(seconds: 1)).catchError((timeOut){
          //超时:TimeoutException after 0:00:00.010000: Future not completed
          print('超时:${timeOut}');
          _cancelConnect = true;
        });//设置超时时间
      }
    
      Future<List<Chat>> getDatas() async {
        _cancelConnect = false;
        //await 等到 http.get 拿到响应之后再执行其他代码
        final response = await http
            .get('http://rap2api.taobao.org/app/mock/225870/api/chat/list');
        if (response.statusCode == 200) {
          //获取响应数据,并且转换成Map类型
          final responseBody = json.decode(response.body);
          //转换模型数组
          List<Chat> chatList = responseBody['chat_list']
              .map<Chat>((item) => Chat.fromJson(item))
              .toList();
          //print('chatList$chatList');
          return chatList;
        } else {
          throw Exception('statusCode:${response.statusCode}');
        }
      }
    
      //创建Item的方法!
      PopupMenuItem<String> _buildItem(String imgAss, String title) {
        return PopupMenuItem(
          child: Row(
            children: <Widget>[
              Image(
                image: AssetImage(imgAss),
                width: 20,
              ),
              Container(
                width: 20,
              ),
              Text(
                title,
                style: TextStyle(color: Colors.white),
              ),
            ],
          ),
        );
      }
    
      //回调方法
      List<PopupMenuItem<String>> _buildPopupMenuItem(BuildContext context) {
        return <PopupMenuItem<String>>[
          _buildItem('images/发起群聊.png', '发起群聊'),
          _buildItem('images/添加朋友.png', '添加朋友'),
          _buildItem('images/扫一扫1.png', '扫一扫'),
          _buildItem('images/收付款.png', '收付款'),
        ];
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: WeChatThemeColor,
            centerTitle: true,
            title: Text("微信"),
            actions: <Widget>[
              Container(
                margin: EdgeInsets.only(right: 10),
                child: PopupMenuButton(
                  offset: Offset(0, 60.0),
                  child: Image(
                    image: AssetImage('images/圆加.png'),
                    width: 25,
                  ),
                  itemBuilder: _buildPopupMenuItem,
                ),
              ),
            ],
          ),
          body: Container(
            child: _datas.length == 0
                ? Center(
                    child: Text('Loading...'),
                  )
                : ListView.builder(
                    itemCount: _datas.length,
                    itemBuilder: (BuildContext context, int index) {
                      return ListTile(
                        title: Text(_datas[index].name),
                        subtitle: Container(
                          height: 20,
                          width: 20,
                          child: Text(
                            _datas[index].message,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        leading: CircleAvatar(
                          backgroundImage: NetworkImage(_datas[index].imageUrl),
                        ),
                      );
                    },
                  ),
          ),
        );
      }
    }
    

    二、保持部件的状态

    1.混入(Mixins)

    用来给类增加功能,with 混入一个或多个mixin

    使用

    ///1.使用with AutomaticKeepAliveClientMixin<ChatPage>
    class _ChatPageState extends State<ChatPage>
    with AutomaticKeepAliveClientMixin<ChatPage>
    {
        @override
        // TODO: implement wantKeepAlive
        bool get wantKeepAlive => true;//保留setState状态
    }
    ///2.重写   super.build(context);
    @override 
    Widget build(BuildContext context) {
        super.build(context);
    }
    

    2.PageController 使用

    class _RootPageState extends State<RootPage> {
      final PageController _pageController = PageController(
        initialPage: 0,
      );
    
      List<Widget> pages = [
        ChatPage(),
        FriendsPage(),
        DiscoverPage(),
        MinePage(),
      ];
    
      int _currentIndex = 0; //选中Item时发生变化
    
      @override
      Widget build(BuildContext context) {
        return Container(
          child: Scaffold(
            bottomNavigationBar: BottomNavigationBar(
              onTap: (int index) {
                //点击事件,代理方法
                _currentIndex = index; //赋值当前索引
                setState(() {});
                _pageController.jumpToPage(index);
              },
              selectedFontSize: 12.0,
              //设置选中字体大小
              type: BottomNavigationBarType.fixed,
              //设置系统样式
              fixedColor: Colors.green,
              //设置选中颜色
              currentIndex: _currentIndex,
              //当前索引
              items: <BottomNavigationBarItem>[
                BottomNavigationBarItem(
                  icon: Image(
                      height: 20,
                      width: 20,
                      image: AssetImage('images/tabbar_chat.png')),
                  activeIcon: Image(
                      height: 20,
                      width: 20,
                      image: AssetImage('images/tabbar_chat_hl.png')),
                  title: Text('微信'),
                ),
                BottomNavigationBarItem(
                  icon: Image(
                      height: 20,
                      width: 20,
                      image: AssetImage('images/tabbar_friends.png')),
                  activeIcon: Image(
                      height: 20,
                      width: 20,
                      image: AssetImage('images/tabbar_friends_hl.png')),
                  title: Text('通讯录'),
                ),
                BottomNavigationBarItem(
                  icon: Image(
                      height: 20,
                      width: 20,
                      image: AssetImage('images/tabbar_discover.png')),
                  activeIcon: Image(
                      height: 20,
                      width: 20,
                      image: AssetImage('images/tabbar_discover_hl.png')),
                  title: Text('发现'),
                ),
                BottomNavigationBarItem(
                  icon: Image(
                      height: 20,
                      width: 20,
                      image: AssetImage('images/tabbar_mine.png')),
                  activeIcon: Image(
                      height: 20,
                      width: 20,
                      image: AssetImage('images/tabbar_mine_hl.png')),
                  title: Text('我'),
                ),
              ],
            ),
            body: PageView(
              ///onPageChanged  设置 PageView和TabBar联动
              onPageChanged: (int index){
                _currentIndex = index;
                setState(() {});
              },
              ///设置PageView不可滑动
              physics: NeverScrollableScrollPhysics(),
              controller: _pageController,
              children: pages,
            ), //显示当前页面 pages[_currentIndex]
          ),
        );
      }
    }
    

    效果图

    效果图

    相关文章

      网友评论

        本文标题:Flutter网络请求的处理和保持部件的状态

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