Flutter网络请求插件mati_rest_api的使用

Flutter网络请求插件mati_rest_api的使用

mati_rest_api 是一个用于简化 Flutter 应用中网络请求的插件。它基于 Dart 的 http 包,提供了更简洁的 API 和更友好的接口来处理 RESTful API 请求。


使用步骤

1. 添加依赖

pubspec.yaml 文件中添加 mati_rest_api 作为依赖:

dependencies:
  mati_rest_api: ^1.0.0

然后运行以下命令以安装依赖:

flutter pub get

2. 初始化客户端

在应用启动时初始化 MatiRestClient,并设置基础 URL 和其他配置(如超时时间)。

import 'package:mati_rest_api/mati_rest_api.dart';

void main() {
  // 初始化 MatiRestClient
  MatiRestClient.instance.baseUrl = 'https://jsonplaceholder.typicode.com';
  MatiRestClient.instance.timeout = Duration(seconds: 10);

  runApp(MyApp());
}

3. 发送网络请求

GET 请求

import 'package:flutter/material.dart';
import 'package:mati_rest_api/mati_rest_api.dart';

class MyHomePage extends StatefulWidget {
  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _response = '';

  Future<void> fetchData() async {
    try {
      // 发送 GET 请求
      final response = await MatiRestClient.instance.get('/posts/1');

      // 处理响应
      setState(() {
        _response = response.body.toString();
      });
    } catch (e) {
      // 处理错误
      setState(() {
        _response = e.toString();
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GET 请求示例'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: fetchData,
              child: Text('获取数据'),
            ),
            SizedBox(height: 20),
            Text(_response),
          ],
        ),
      ),
    );
  }
}

POST 请求

Future<void> postData() async {
  try {
    // 定义请求体
    final body = {
      'title': 'foo',
      'body': 'bar',
      'userId': 1,
    };

    // 发送 POST 请求
    final response = await MatiRestClient.instance.post('/posts', body);

    // 处理响应
    setState(() {
      _response = response.body.toString();
    });
  } catch (e) {
    // 处理错误
    setState(() {
      _response = e.toString();
    });
  }
}

4. 错误处理

mati_rest_api 提供了统一的错误处理机制。当请求失败时,可以通过捕获异常来处理错误信息。

try {
  final response = await MatiRestClient.instance.get('/invalid-endpoint');
} on MatiApiException catch (e) {
  print('错误状态码: ${e.statusCode}');
  print('错误消息: ${e.message}');
} catch (e) {
  print('未知错误: $e');
}

完整示例代码

以下是一个完整的示例代码,展示了如何使用 mati_rest_api 进行 GET 和 POST 请求:

import 'package:flutter/material.dart';
import 'package:mati_rest_api/mati_rest_api.dart';

void main() {
  // 初始化 MatiRestClient
  MatiRestClient.instance.baseUrl = 'https://jsonplaceholder.typicode.com';
  MatiRestClient.instance.timeout = Duration(seconds: 10);

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _responseGet = '';
  String _responsePost = '';

  Future<void> fetchData() async {
    try {
      final response = await MatiRestClient.instance.get('/posts/1');
      setState(() {
        _responseGet = response.body.toString();
      });
    } catch (e) {
      setState(() {
        _responseGet = e.toString();
      });
    }
  }

  Future<void> postData() async {
    try {
      final body = {
        'title': 'foo',
        'body': 'bar',
        'userId': 1,
      };
      final response = await MatiRestClient.instance.post('/posts', body);
      setState(() {
        _responsePost = response.body.toString();
      });
    } catch (e) {
      setState(() {
        _responsePost = e.toString();
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('mati_rest_api 示例'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            ElevatedButton(
              onPressed: fetchData,
              child: Text('发送 GET 请求'),
            ),
            SizedBox(height: 20),
            Text(_responseGet),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: postData,
              child: Text('发送 POST 请求'),
            ),
            SizedBox(height: 20),
            Text(_responsePost),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter网络请求插件mati_rest_api的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter网络请求插件mati_rest_api的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


mati_rest_api 是一个用于 Flutter 的网络请求插件,它简化了与 RESTful API 的交互。以下是如何使用 mati_rest_api 插件的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 mati_rest_api 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  mati_rest_api: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 导入插件

在你的 Dart 文件中导入 mati_rest_api

import 'package:mati_rest_api/mati_rest_api.dart';

3. 初始化客户端

你可以使用 MatiRestApi 类来初始化一个 HTTP 客户端。通常你会在应用的某个地方(如 main.dart 或某个服务类中)初始化它:

final matiRestApi = MatiRestApi(
  baseUrl: 'https://api.example.com', // 你的 API 基础 URL
  headers: {
    'Authorization': 'Bearer your_access_token', // 如果需要,添加授权头
  },
);

4. 发起请求

mati_rest_api 提供了多种方法来发起 HTTP 请求,如 get, post, put, delete 等。

GET 请求

Future<void> fetchData() async {
  try {
    final response = await matiRestApi.get('/endpoint');
    print('Response: ${response.body}');
  } catch (e) {
    print('Error: $e');
  }
}

POST 请求

Future<void> postData() async {
  try {
    final response = await matiRestApi.post(
      '/endpoint',
      body: {'key': 'value'}, // 请求体
    );
    print('Response: ${response.body}');
  } catch (e) {
    print('Error: $e');
  }
}

PUT 请求

Future<void> updateData() async {
  try {
    final response = await matiRestApi.put(
      '/endpoint/1',
      body: {'key': 'new_value'}, // 请求体
    );
    print('Response: ${response.body}');
  } catch (e) {
    print('Error: $e');
  }
}

DELETE 请求

Future<void> deleteData() async {
  try {
    final response = await matiRestApi.delete('/endpoint/1');
    print('Response: ${response.body}');
  } catch (e) {
    print('Error: $e');
  }
}

5. 处理响应

mati_rest_api 返回的响应包含 statusCodebody,你可以根据需要进行处理。

Future<void> fetchData() async {
  try {
    final response = await matiRestApi.get('/endpoint');
    if (response.statusCode == 200) {
      // 成功处理数据
      print('Data: ${response.body}');
    } else {
      // 处理错误
      print('Failed to load data: ${response.statusCode}');
    }
  } catch (e) {
    print('Error: $e');
  }
}

6. 错误处理

mati_rest_api 会抛出异常来处理网络请求中的错误,你可以使用 try-catch 来捕获并处理这些异常。

Future<void> fetchData() async {
  try {
    final response = await matiRestApi.get('/endpoint');
    print('Response: ${response.body}');
  } catch (e) {
    print('Error: $e');
  }
}

7. 自定义请求

你可以通过传递 headersqueryParameters 等来自定义请求:

Future<void> fetchCustomData() async {
  try {
    final response = await matiRestApi.get(
      '/endpoint',
      headers: {'Custom-Header': 'value'},
      queryParameters: {'param': 'value'},
    );
    print('Response: ${response.body}');
  } catch (e) {
    print('Error: $e');
  }
}

8. 使用拦截器(可选)

mati_rest_api 支持拦截器,你可以在请求发送前或响应返回后进行一些操作。

matiRestApi.addInterceptor((request) {
  print('Request: ${request.method} ${request.url}');
  return request;
});

matiRestApi.addInterceptor((response) {
  print('Response: ${response.statusCode}');
  return response;
});

9. 清理资源

当你不再需要使用 matiRestApi 时,可以调用 dispose 方法来释放资源。

matiRestApi.dispose();
回到顶部