目 录CONTENT

文章目录

Flutter 网络编程与数据存储

Sakura
2024-03-19 / 0 评论 / 0 点赞 / 22 阅读 / 0 字 / 正在检测是否收录...
温馨提示:
本文最后更新于163天前,若内容或图片失效,请留言反馈。 部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

Flutter 网络编程与数据存储

1. 发送 Get 请求

  1. pub.dev 搜索http 库

  1. 添加到项目中并引用

  • pubspec.yaml

  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.6
  http: ^1.2.1
  • http_study.dart

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

// 使用快捷键stf快速创建一个有状态的wiget
class HttpStudy extends StatefulWidget {
  const HttpStudy({super.key});

  @override
  State<HttpStudy> createState() => _HttpStudyState();
}

class _HttpStudyState extends State<HttpStudy> {
  var responseShow = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Http 请求操作"),),
      body: Column(
        children: [
          _doGet(),
          Text("返回的结果:$responseShow")
        ],
      ), 
    );
  }

  _doGet() {
    return ElevatedButton(onPressed: onPressed, child: const Text("发送Get请求"));
  }

  // 发送Get请求
  void onPressed() async {
    var url = Uri.parse("https://api.devio.org/uapi/test/test?requestPrams=11");
    var response = await http.get(url);

    // http请求成功
    if (response.statusCode == 200) {
      setState(() {
        responseShow = response.body;
      });
    } else {
      setState(() {
        responseShow = "请求失败: code: ${response.statusCode}, body:${response.body}";
      });
    }
  }
}
  • main.dart

import 'package:flutter/material.dart';
import 'package:flutterstudy/http_Study.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.

        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
	  // 引入页面
      home: const HttpStudy(),
    );
  }
}

2. 发送 Post 请求

2.1 表单类型

  void onPressed() async {
    var url = Uri.parse("http://192.168.227.1:8081/api/v1/");
    var postFrom = {"name": "Sakura"}; // 数据格式要求为Map<string,string>
    var response = await http.post(url, body: postFrom);


    // http请求成功
    if (response.statusCode == 200) {
      setState(() {
        responseShow = response.body;
      });
    } else {
      setState(() {
        responseShow =
            "请求失败: code: ${response.statusCode}, body:${response.body}";
      });
    }
  }

2.2 Json 类型

// 发送JSON 类型的Post请求
  void onPressed() async {
    var url = Uri.parse("http://192.168.227.1:8081/api/v1/");
    var data = {"name": "Sakura"}; // 数据格式要求为Map<string,string>
	// jsong序列化
    var response = await http.post(url, body: jsonEncode(data), headers: {
	  // 设置content-type为json类型
      "content-type": "application/json"
    });


    // http请求成功
    if (response.statusCode == 200) {
      setState(() {
        responseShow = response.body;
      });
    } else {
      setState(() {
        responseShow =
            "请求失败: code: ${response.statusCode}, body:${response.body}";
      });
    }
  }

3. json 解析

Flutter 中 JSON 可以解析为两种类型

  1. JSON -> Map

  2. JSON -> Dart Model

3.1 JSON -> Map [不推荐]

void main() {
  var jsonData = '{"name":"John","age":30,"city":"New York","address":{"street":"123 Main St","building":"A","apartment":"4B"}}';
  Map<String, dynamic> jsonMap = jsonDecode(jsonData);

  print("${jsonMap["name"]}"); // John
  print("${jsonMap["address"]["street"]}"); // 123 Main ST
}

需要自己解析层级嵌套

3.2 JSON -> Dart Model [推荐]

使用 json_serializable 进行 json 序列化

flutter json_serializable 的使用 - 知乎 (zhihu.com)

Flutter中使用json_serializable实现JSON数据的解析工作-duidaima 堆代码

  • 定制化需求

Flutter中高级JSON处理:使用json_serializable进行深入定制_flutter jsonserializable 能忽略字段吗-CSDN博客

0

评论区