美文网首页
Flutter 网络请求、wechat聊天 页面

Flutter 网络请求、wechat聊天 页面

作者: 老黑来袭 | 来源:发表于2021-01-07 16:34 被阅读0次

网络请求

关于网络请求,官方提供了一个package http,我们在pubspec.yaml 中引入

dependencies:
  flutter:
    sdk: flutter
  http: 0.12.1

如何使用:

import 'package:http/http.dart' as http;
// await 代表这是个耗时操作 , 类似于iOS多线程
var url = 'https://example.com/whatsit/create';
var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');

print(await http.read('https://example.com/foobar.txt'));

这是官网官网!

再介绍一个mock数据平台 RAP

下面进入正题 微信首页最后一个页面源码:

import 'package:flutter/material.dart';
import 'package:wechat_demo/const.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

// 网络请求 pub.dev  -> http Dart 提供的 在 pubspec.yarm 中配置
// 使用 首先导入 import 'package:http/http.dart' as http; // as http 是重命名
// 官网 pub.dev 搜索 http 即可
// mock 数据地址 http://rap2.taobao.org/repository/editor?id=275004&itf=1846648
/*
*  Map 转 json
* *   final chatJson = json.encode(chat);
*    print(chatJson);
*    print(chat);
*
*    // json 转 Map
*    final newChat = json.decode(chatJson);
*    print(newChat);
*
*
*
*
*/
class ChatPage extends StatefulWidget {

  @override
  _ChatPageState createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {

  List<Chat> datas = [];
  
  @override
  void initState(){

    super.initState();
    final chat = {
      'name':'ss',
      'massage':'dasdasd'
    };

    // Map 转 json
    final chatJson = json.encode(chat);
    // print(chatJson);
    // print(chat);

    // json 转 Map
    final newChat = json.decode(chatJson);
    // print(newChat);

    getDatas().then((List<Chat> value) {
      setState(() {
        datas = value;
      });
    }).catchError((error){

    }).timeout(Duration(seconds: 1)).whenComplete(() => print('wancheng'));
  }
  
  // 网络请求数据
  Future<List<Chat>> getDatas() async /*这样代表这是一个异步方法*/{
    var url = 'http://rap2api.taobao.org/app/mock/275004/api/chat/list';
    
    final res = await /*代表这段代码是耗时操作*/ http.get(url);
    if (res.statusCode == 200) {
      final Map responseBody = json.decode(res.body);

      final List<Chat> chatList = responseBody['chat_list'].map<Chat>((item) {
        return Chat.fromJson(item);
      }).toList();
       // print(chatList);
       print('list __  check');
      return chatList;

    }else {
      throw Exception('statusCode${res.statusCode}');
    }
    // print(res.body);
  }
  
  
  Widget buildPopUpMenu(String imageAss, String title) {
    return Container(
      // color: Colors.black,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Image(
            image: AssetImage(imageAss),
            width: 20,
          ),
          Text(
            title,
            style: TextStyle(color: Colors.white),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          Container(
            margin: EdgeInsets.only(right: 10),
            child: PopupMenuButton(
              offset: Offset(0, 60),
              child: Image(
                image: AssetImage('images/圆加.png'),
                width: 25,
              ),
              itemBuilder: (context) {
                return [
                  PopupMenuItem(child: buildPopUpMenu('images/群聊.png', '发起群聊')),
                  PopupMenuItem(
                      child: buildPopUpMenu('images/添加朋友.png', '添加朋友')),
                  PopupMenuItem(
                      child: buildPopUpMenu('images/扫一扫1.png', '扫一扫')),
                  PopupMenuItem(child: buildPopUpMenu('images/收付款.png', '收付款')),
                ];
              },
            ),
          )
        ],
        title: Text(
          '微信',
          style: TextStyle(color: Colors.black),
        ),
        backgroundColor: weChatThemColor,
      ),
      body: Center(
        child: Container(child: datas.length == 0 ? Center(child: Text('loading') ,): ListView.builder(
            itemCount: datas.length,
            itemBuilder: (context, index) {
              return GestureDetector(
                onTap: (){
                  print('dianji');
                }, child: ListTile(title: Text(datas[index].name),subtitle: Container(height: 20,child: Text(datas[index].massage),),leading: CircleAvatar(backgroundImage: NetworkImage(datas[index].imageUrl),),),
              );
        }),)
      ),
    );
  }
}

// 模型
class Chat {
  final String name;
  final String massage;
  final String imageUrl;

  const Chat({this.name, this.massage, this.imageUrl});
// factory 工厂构造函数 , 创建对象的方式不同 ,只要返回一个对象就可以可以是任何对象
    factory Chat.fromJson(Map map){
      print(map['asdasd']);
    return Chat(name: map['nick_name'], massage: map['massage'],imageUrl: map['image_url']);
}
}

相关文章

网友评论

      本文标题:Flutter 网络请求、wechat聊天 页面

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