Flutter WordPress客户端插件wordpress_client的使用

发布于 1周前 作者 zlyuanteng 来自 Flutter

Flutter WordPress客户端插件wordpress_client的使用

🚀 Features

  • 📦 API discovery support.
  • ⏲️ Measures request completion time.
  • 📝 Supports all CRUD operations.
  • 🌐 Supports all common endpoints.
  • 🎨 Custom Requests & Authorization systems.
  • 🔐 3 Popular authorization methods.
  • 📦 Third party Database integration.
  • 🔧 Middlewares for request & response operations.
  • 🎣 Events for preprocessing response.
  • 🚀 Execute requests in Parallel.

Future

If you find any functionality missing, please share the details on GitHub Discussions.

📦 Installation

Add wordpress_client to your pubspec.yaml:

dependencies:
  wordpress_client: ^8.5.3

Then run flutter pub get to install the package.

🔧 Usage

Import the Package

import 'package:wordpress_client/wordpress_client.dart';

Initialization

You can initialize WordpressClient using two methods:

Simple Method

final baseUrl = Uri.parse('https://example.com/wp-json/wp/v2');
final client = WordpressClient(baseUrl: baseUrl);

For advanced initialization, refer to the Advanced Method.

Sending Requests

Example to retrieve 20 recent WordPress posts in ascending order:

final request = ListPostRequest(
  page: 1,
  perPage: 20,
  order: Order.asc,
);

final response = await client.posts.list(request);

// Dart 3 style
switch (response) {
  case WordpressSuccessResponse():
    final data = response.data; // List<Post>
    break;
  case WordpressFailureResponse():
    final error = response.error; // WordpressError
    break;
}

// Using map method to handle both success and failure
final result = response.map(
  onSuccess: (response) {
    print(response.message);
    return response.data;
  },
  onFailure: (response) {
    print(response.error.toString());
    return <Post>[];
  },
);

// You can cast to a state directly; this will throw an error if the response is of the wrong type
final result = response.asSuccess(); // or response.asFailure();

Refer to the documentation for more request examples.

🔒 Supported Authorization

AppPasswordAuth

By the WordPress Team, uses basic HTTP authentication where credentials are passed with every request. Details

BasicJwtAuth

Developed by Enrique Chavez, involves JSON Web Token (JWT) authentication where a token is issued and then used in subsequent requests. Details

UsefulJwtAuth

By Useful Team, another implementation using JWT for authentication purposes. Details

For custom authorization, check the Authorization Wiki.

📋 Supported REST Methods

Endpoint Create Read Update Delete
Posts
Comments
Categories
Tags
Users
Me
Media
Pages
Application Passwords
Search - - -

📢 Custom Response Types

Learn how to implement Custom Requests here.

🤝 Feedback & Contributing

  • For bugs or feature requests, use the issue tracker.
  • Contributions are always appreciated. PRs are welcome!

📄 License

This project is MIT licensed.

示例代码

// ignore_for_file: avoid_print, unused_local_variable

import 'package:wordpress_client/wordpress_client.dart';

import 'auth_middleware.dart';

Future<void> main() async {
  final baseUrl = Uri.parse('https://example.com/wp-json/wp/v2');

  // Simple Usage
  final client = WordpressClient(
    baseUrl: baseUrl,
    bootstrapper: (bootstrapper) => bootstrapper
        .withDebugMode(true)
        .withMiddleware(AuthMiddleware())
        .withMiddleware(
          DelegatedMiddleware(
            onRequestDelegate: (request) async {
              return request.copyWith(
                headers: {
                  'X-My-Custom-Header': 'My Custom Value',
                },
              );
            },
            onResponseDelegate: (response) async {
              return response;
            },
          ),
        )
        .build(),
  );

  final response = await client.posts.list(
    ListPostRequest(
      perPage: 1,
      order: Order.asc,
    ),
  );

  response.map<void>(
    onSuccess: (response) {
      print('Posts Count: ${response.data.length}');
      // prints Posts Count: 1, as expected
    },
    onFailure: (response) {
      print(response.error);
    },
  );
}

更多关于Flutter WordPress客户端插件wordpress_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter WordPress客户端插件wordpress_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用wordpress_client插件的示例代码。wordpress_client插件允许你与WordPress REST API进行交互,从而可以获取和发布内容。

前提条件

  1. 确保你已经安装了Flutter和Dart开发环境。
  2. 创建一个新的Flutter项目或在现有项目中添加wordpress_client插件。

步骤

1. 添加依赖

在你的pubspec.yaml文件中添加wordpress_client依赖:

dependencies:
  flutter:
    sdk: flutter
  wordpress_client: ^x.y.z  # 请替换为最新版本号

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

2. 配置WordPress API端点

在你的Flutter项目的某个合适位置(比如main.dart或专门的文件中),配置WordPress API端点。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: WordPressClientExample(),
    );
  }
}

class WordPressClientExample extends StatefulWidget {
  @override
  _WordPressClientExampleState createState() => _WordPressClientExampleState();
}

class _WordPressClientExampleState extends State<WordPressClientExample> {
  WordPressClient _wordpressClient;

  @override
  void initState() {
    super.initState();
    // 配置WordPress API端点
    _wordpressClient = WordPressClient(
      baseUrl: 'https://your-wordpress-site.com/wp-json',
      username: 'your-username',
      password: 'your-password',
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('WordPress Client Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _fetchPosts,
          child: Text('Fetch Posts'),
        ),
      ),
    );
  }

  void _fetchPosts() async {
    try {
      // 获取帖子列表
      var posts = await _wordpressClient.getPosts();
      print(posts);
      // 你可以在这里更新UI来显示帖子列表
    } catch (e) {
      print('Error fetching posts: $e');
    }
  }
}

3. 运行应用

确保你的WordPress站点启用了REST API,并且你提供的用户名和密码具有足够的权限来访问API。然后运行你的Flutter应用:

flutter run

解释

  • WordPressClient: 这个类用于创建与WordPress API交互的客户端实例。
  • baseUrl: WordPress站点REST API的基础URL。
  • usernamepassword: 用于身份验证的用户名和密码。
  • getPosts(): 这个方法用于获取帖子列表。

注意事项

  1. 安全性: 在生产环境中,不要直接在代码中硬编码用户名和密码。考虑使用环境变量或安全的密钥管理服务。
  2. 错误处理: 示例代码中仅打印了错误,但在实际应用中,你可能需要更复杂的错误处理逻辑。
  3. API限制: 根据你的WordPress站点配置和API权限,某些操作可能受限。

这个示例演示了如何使用wordpress_client插件来与WordPress REST API进行基本的交互。根据你的需求,你可以进一步扩展这个示例来实现更多的功能,比如发布帖子、更新用户信息等。

回到顶部