Flutter学习9 - http 中 get/post 请求示例

1、配置 http

pubspec.yaml

dependencies:
  http:  ^0.13.4
  flutter:
    sdk: flutter

.dart

import 'package:http/http.dart' as http;

2、示例

(1)工具使用 - postman

  • 可以使用 postman 插件中的示例来测试 get/post 请求

在这里插入图片描述

(2)代码实现示例

  • 点击按钮,发起 Get/Post 请求,并将请求结果展示到界面上
    在这里插入图片描述

http_page.dart

import 'dart:convert';
import 'dart:typed_data';

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

class HttpDemo extends StatefulWidget {
   
  const HttpDemo({
   super.key});

  
  State<HttpDemo> createState() => _HttpDemoState();
}

class _HttpDemoState extends State<HttpDemo> {
   
  //展示请求结果
  var resultShow = "";

  //请求结果解析
  var resultDecodeShow = "";

  
  Widget build(BuildContext context) {
   
    return Scaffold(
      appBar: AppBar(
        title: const Text("Http 的 post 请求"),
      ),
      body: Column(
        children: [
          Center(
            child: _httpGetButton(),
          ),
          //post 请求按钮 - form
          Center(
            child: _httpPostFormButton(),
          ),
          //post 请求按钮 - json
          Center(
            child: _httpPostJsonButton(),
          ),
          Row(
            children: [
              Expanded(
                  child: Text(
                '请求结果:\n $resultShow',
                textAlign: TextAlign.left,
              )),
            ],
          ),
          Row(
            children: [
              Expanded(
                  child: Text(
                '请求结果(解析):\n $resultDecodeShow',
                textAlign: TextAlign.left,
              )),
            ],
          ),
        ],
      ),
    );
  }

  //get 按钮
  _httpGetButton() {
   
    return ElevatedButton(onPressed: _doGet, child: const Text('发起 Get 请求'));
  }

  //post 按钮 - form
  _httpPostFormButton() {
   
    return ElevatedButton(
        onPressed: _doFormPost, child: const Text('发起 post 请求 - form'));
  }

  //post 按钮 - json
  _httpPostJsonButton() {
   
    return ElevatedButton(
        onPressed: _doJsonPost, child: const Text('发起 post 请求 - json'));
  }

  // utf8 解码
  _decodeUtf8(String responseBody) {
   
    var bytes = Uint8List.fromList(responseBody.codeUnits);
    String decodeString = utf8.decode<
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KillerNoBlood

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值