Flutter网络请求(http)

Json字符串和Map相互转换

Json转Map

//Json字符串
 String userinfo = '{"username":"zhangsan","age":20}';
 //Json转Map
 Map u = json.decode(userinfo);
import 'dart:convert';

import 'package:flutter/material.dart';

class HttpGetPage extends StatefulWidget {
    
    
  HttpGetPage({
    
    Key? key}) : super(key: key);

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

class _HttpGetPageState extends State<HttpGetPage> {
    
    
  @override
  void initState() {
    
    
    // TODO: implement initState
    super.initState();
    String userinfo = '{"username":"zhangsan","age":20}';
    Map u = json.decode(userinfo);
    print(u["username"]);
  }

  @override
  Widget build(BuildContext context) {
    
    
    return Container();
  }
}

在这里插入图片描述

Map转Json

//Map类型数据
Map userInfo = {
    
    "username": "张三", "age": 20};
//Map转Json字符串
var a = json.encode(userInfo);
import 'dart:convert';

import 'package:flutter/material.dart';

class HttpGetPage extends StatefulWidget {
    
    
  HttpGetPage({
    
    Key? key}) : super(key: key);

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

class _HttpGetPageState extends State<HttpGetPage> {
    
    
  @override
  void initState() {
    
    
    // TODO: implement initState
    super.initState();
    Map userInfo = {
    
    "username": "张三", "age": 20};
    var a = json.encode(userInfo);
    print(json.encode(userInfo));
    print(userInfo is Map);
    print(a is String);
  }

  @override
  Widget build(BuildContext context) {
    
    
    return Container();
  }
}

在这里插入图片描述

Get请求

  _getData() async {
    
    
    var apiUrl = Uri.parse('https://jd.itying.com/api/httpget');
    var response = await http.get(apiUrl);
    print('Response status: ${response.statusCode}');
    //获取到的是Json数据
    print('Response body: ${response.body}');
    setState(() {
    
    
    //转换成Map类型的数据
      _msg = json.decode(response.body)["msg"];
    });
    print(_msg);
  }

Post请求

  _postData() async {
    
    
    var apiUrl = Uri.parse('https://jd.itying.com/api/httpPost');
    var response = await http.post(apiUrl,body: {
    
    "username":"张三","age":"20"});
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');
    // setState(() {
    
    
    //   _msg = json.decode(response.body)["msg"];
    // });
    print(_msg);
  }

数据解析

这里我们用到的是http解析数据,首先还是在https://pub.flutter-io.cn/中找到相关文档,添加依赖,导包等操作
在这里插入图片描述

这里用到的Json接口是网上随便找的一个
http://jsonplaceholder.typicode.com/posts
在这里插入图片描述
代码如下:

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

class HttpDemoPage extends StatefulWidget {
    
    
  HttpDemoPage({
    
    Key? key}) : super(key: key);

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

class _HttpDemoPageState extends State<HttpDemoPage> {
    
    
//把所有的map存入到一个集合
  List _list = [];
  @override
  void initState() {
    
    
    // TODO: implement initState
    super.initState();
    _getData();
  }

  _getData() async {
    
    
    var apiUrl = Uri.parse('http://jsonplaceholder.typicode.com/posts');
    var response = await http.get(apiUrl);
    if (response.statusCode == 200) {
    
    
      print(json.decode(response.body));
      setState(() {
    
    
        _list = json.decode(response.body);
      });
    }
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');
  }

  @override
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: Text("请求数据Demo")
      ),
      body: _list.length>0?ListView.builder(
        itemCount: _list.length,
        itemBuilder: (BuildContext context, int index) {
    
    
          return ListTile(title:Text( _list[index]["title"]),);
        },
        
      ):Text(""),
    );
  }
}

我们获取到的数据
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_46527751/article/details/122642970