Flutter开发的小技巧

725 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第25天, 点击查看活动详情

Dart:从 URL 获取主机、路径和查询参数

在 Dart 中,您可以按照以下步骤从给定的 URL 字符串中提取有用的信息:

1.从你的 URL 字符串构造一个 Uri 对象:

const url = "...";
const uri = Uri.parse(url);

2、现在,你可以通过Uri对象的各种属性得到你想要的。以下是最常用的:

  • origin:基本 URL(如下所示:protocol://host:port
  • host:URL 的主机部分(域、IP 地址等)
  • 方案:协议(http、https等)
  • 端口:端口号
  • 路径:路径
  • pathSegments : URI 路径拆分为其段
  • query : 查询字符串
  • queryParameters : 查询被拆分成一个地图,方便访问

您可以在官方文档中找到有关Uri 类的更多详细信息。

// main.dart
void main() {
  // an ordinary URL
  const urlOne = 'https://www.JianGUO/some-category/some-path/';
​
  final uriOne = Uri.parse(urlOne);
  print(uriOne.origin); // https://www.JianGUO
  print(uriOne.host); // www.JianGUO
  print(uriOne.scheme); // https
  print(uriOne.port); // 443
  print(uriOne.path); // /some-category/some-path/
  print(uriOne.pathSegments); // [some-category, some-path]
  print(uriOne.query); // null
  print(uriOne.queryParameters); // {}
​
  // a URL with query paramters
  const urlTwo =
      'https://test.JianGUO/one-two-three?search=flutter&sort=asc';
  final uriTwo = Uri.parse(urlTwo);
  print(uriTwo.origin); // https://test.JianGUO
  print(uriTwo.host); // test.JianGUO
  print(uriTwo.scheme);
  print(uriTwo.port); // 443
  print(uriTwo.path); // /one-two-three
  print(uriTwo.pathSegments); // [one-two-three]
  print(uriTwo.query); // search=flutter&sort=asc
  print(uriTwo.queryParameters); // {search: flutter, sort: asc}
}

在 Flutter 中使用 GetX 发出 GET/POST 请求

GetX 是一个功能强大的开源 Flutter 库,是当今最流行的,在pub.dev上有超过 10,000 个赞。尽管 GetX 提供了广泛的功能,但每个功能都包含在一个单独的容器中,并且只有您在应用程序中使用的那些会被编译。因此,它不会不必要地增加您的应用程序大小。这篇简短的文章向您展示了如何使用库提供的GetConnect发出 POST 和 GET 请求。 您会感到惊讶,因为要编写的代码量非常少。

1.要开始使用,您需要通过执行以下命令来安装GetX :

flutter pub add get

\2. 然后将其导入到您的 Dart 代码中:

import 'package:get/get.dart';

\3. 下一步是创建GetConnect类的实例:

inal _connect = GetConnect();

\4. 像这样向模拟 API 端点发送 Get 请求(感谢 Typi Code 团队):

void _sendGetRequest() async {
    final response =
        await _connect.get('https://jsonplaceholder.typicode.com/posts/1');
​
    if (kDebugMode) {
      print(response.body);
    }
}

\5. 发出 Post 请求:

void _sendPostRequest() async {
    final response = await _connect.post(
      'https://jsonplaceholder.typicode.com/posts',
      {
        'title': 'one two three',
        'body': 'four five six seven',
        'userId': 1,
      },
    );
​
    if (kDebugMode) {
      print(response.body);
    }
}

完整示例:

// main.dart
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
​
void main() {
  runApp(const MyApp());
}
​
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
​
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'KindaCode.com',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const KindaCodeDemo(),
    );
  }
}
​
class KindaCodeDemo extends StatefulWidget {
  const KindaCodeDemo({Key? key}) : super(key: key);
​
  @override
  State<KindaCodeDemo> createState() => _KindaCodeDemoState();
}
​
class _KindaCodeDemoState extends State<KindaCodeDemo> {
  // Initialize an instance of GetConnect
  final _connect = GetConnect();
​
  // send Get request
  // and get the response
  void _sendGetRequest() async {
    final response =
        await _connect.get('https://jsonplaceholder.typicode.com/posts/1');
​
    if (kDebugMode) {
      print(response.body);
    }
  }
​
  // send Post request
  // You can somehow trigger this function, for example, when the user clicks on a button
  void _sendPostRequest() async {
    final response = await _connect.post(
      'https://jsonplaceholder.typicode.com/posts',
      {
        'title': 'one two three',
        'body': 'four five six seven',
        'userId': 1,
      },
    );
​
    if (kDebugMode) {
      print(response.body);
    }
  }
​
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('KindaCode.com')),
      body: Padding(
        padding: const EdgeInsets.all(30),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ElevatedButton(
                onPressed: _sendGetRequest,
                child: const Text('Send GET Request')),
            ElevatedButton(
                onPressed: _sendPostRequest,
                child: const Text('Send POST Request')),
          ],
        ),
      ),
    );
  }
}

按 2 个按钮并检查您的终端以查看输出。