Flutter 网络页面心得

1.将网络数据转化模型数据

创建模型类

class Chat {

  final String name;

  final String message;

  final String imageUrl;

  const Chat({required this.name, required this.message, required this.imageUrl});

  factory Chat.formMap(Map map) {

    return Chat(

      name: map['name'],

      message: map['message'],

      imageUrl: map['imageUrl'],

    );

  }

}


加载网络数据

Future<List<Chat>> getDatas() async {

    _cancelConnect = false;

    final url =

        Uri.parse('网络请求');

    //发送请求

    final response = await http.get(url);

    if (response.statusCode == 200) {

      //获取响应数据,转成Map类型

      final responsBody = json.decode(response.body);

      //map 作为List的遍历方法。

      List<Chat> chatList = responsBody['chat_list']

          .map<Chat>((item) => Chat.formMap(item))

          .toList();

      return chatList;

    } else {

      throw Exception('statusCode:${response.statusCode}');

    }

  }

json.decode 解析返回的json数据, responsBody['chat_list'] 通过map 函数生成 List<Chat>类型的数组。注意map<Chat>()要指定 返回的类型是Chat,(不然会解析成dynamic类型的)

使用 await 和async 表示getDatas这个方法是异步的

加载UI页面

可以使用 FutureBuilder() 完成,但直接在build 方法中通过属性 更加灵活

定义数组

List<Chat> _datas = [];

在initState 方法中赋值数组,通过 setState 更新页面

//获取网络数据

    getDatas()

        .then((List<Chat> datas) {

        // _cancelConnect 自己定义属性 ,更灵活控制 网络数据的加载

          if (!_cancelConnect) {

            setState(() {

              _datas = datas;

            });

          }

        })

        .catchError((e) {

          _cancelConnect = true;

          print(e);

        })

        .whenComplete(() {

          print('完毕!');

        })

2. 缓存底部Tabbar页面和数据

将Tabbar 所用对应的页面,放在widget 树里面

通过 PageView 组件 和 PageController 的配合


缓存Tabbar 单个页面的数据和状态

继承 AutomaticKeepAliveClientMixin 混合

class _ChatPageState extends State<ChatPage> with AutomaticKeepAliveClientMixin<ChatPage>

重写AutomaticKeepAliveClientMixin的方法

@override

  bool get wantKeepAlive => true;

在build 方法中添加 super.build(context); 代码

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ![Flask](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAW...
    极客学院Wiki阅读 7,273评论 0 3
  • 不知不觉易趣客已经在路上走了快一年了,感觉也该让更多朋友认识知道易趣客,所以就谢了这篇简介,已做创业记事。 易趣客...
    Physher阅读 3,441评论 1 2
  • 双胎妊娠有家族遗传倾向,随母系遗传。有研究表明,如果孕妇本人是双胎之一,她生双胎的机率为1/58;若孕妇的父亲或母...
    邺水芙蓉hibiscus阅读 3,722评论 0 2
  • 晴天,拥抱阳光,拥抱你。雨天,想念雨滴,想念你。 我可以喜欢你吗可以啊 我还可以喜欢你吗可以,可是你要知道我们不可...
    露薇霜凝阅读 1,240评论 1 2