Flutter wordpress - Flutter WordPress API

Overview

Flutter Wordpress

pub.dev

This library uses WordPress REST API V2 to provide a way for your application to interact with your WordPress website.

Tutorial - by Ritesh Sharma

Screenshots

Requirements

For authentication and usage of administrator level REST APIs, you need to use either of the two popular authentication plugins in your WordPress site:

  1. Application Passwords
  2. JWT Authentication for WP REST API (recommended)

Getting Started

1. Import library

First:

Find your pubspec.yaml in the root of your project and add flutter_wordpress: ^0.2.0 under dependencies:

Second:

import 'package:flutter_wordpress/flutter_wordpress.dart' as wp;

2. Instantiate WordPress class

wp.WordPress wordPress;

// adminName and adminKey is needed only for admin level APIs
wordPress = wp.WordPress(
  baseUrl: 'http://localhost',
  authenticator: wp.WordPressAuthenticator.JWT,
  adminName: '',
  adminKey: '',
);

3. Authenticate User

Future<wp.User> response = wordPress.authenticateUser(
  username: 'ChiefEditor',
  password: 'chiefeditor@123',
);

response.then((user) {
  createPost(user);
}).catchError((err) {
  print('Failed to fetch user: $err');
});

4. Fetch Posts

Future<List<wp.Post>> posts = wordPress.fetchPosts(
  postParams: wp.ParamsPostList(
    context: wp.WordPressContext.view,
    pageNum: 1,
    perPage: 20,
    order: wp.Order.desc,
    orderBy: wp.PostOrderBy.date,
  ),
  fetchAuthor: true,
  fetchFeaturedMedia: true,
  fetchComments: true,
  postType: 'post'
);

5. Fetch Users

Future<List<wp.User>> users = wordPress.fetchUsers(
  params: wp.ParamsUserList(
    context: wp.WordPressContext.view,
    pageNum: 1,
    perPage: 30,
    order: wp.Order.asc,
    orderBy: wp.UsersOrderBy.name,
    roles: ['subscriber'],
  ),
);

6. Fetch Comments

Future<List<wp.Comment>> comments = wordPress.fetchComments(
  params: wp.ParamsCommentList(
    context: wp.WordPressContext.view,
    pageNum: 1,
    perPage: 30,
    includePostIDs: [1],
  ),
);

7. Create User

Future<void> createUser({@required String email, @required String username, @required String password, @required List<String> roles}) async {
    await widget.wordPress.createUser(
      user: wp.User(
        email: email,
        password: password,
        username: username,
        roles: roles
      )
    ).then((p) {
      print('User created successfully ${p}');
    }).catchError((err) {
      print('Failed to create user: $err');
    });
  }

8. Create Post

  void createPost({@required wp.User user}) {
    final post = widget.wordPress.createPost(
      post: new wp.Post(
        title: 'First post as a Chief Editor',
        content: 'Blah! blah! blah!',
        excerpt: 'Discussion about blah!',
        authorID: user.id,
        commentStatus: wp.PostCommentStatus.open,
        pingStatus: wp.PostPingStatus.closed,
        status: wp.PostPageStatus.publish,
        format: wp.PostFormat.standard,
        sticky: true,
      ),
    );

    post.then((p) {
      print('Post created successfully with ID: ${p.id}');
    }).catchError((err) {
      print('Failed to create post: $err');
    });
  }

9. create Comment

  void createComment({@required int userId, @required int postId}) {
    final comment = widget.wordPress.createComment(
      comment: new wp.Comment(
        author: userId,
        post: postId,
        content: "First!",
        parent: 0,
      ),
    );

    comment.then((c) {
      print('Comment successfully posted with ID: ${c.id}');
    }).catchError((err) {
      print('Failed to comment: $err');
    });
  }

10. Update Comment

Future<void> updateComment({@required int id, @required int postId, @required wp.User user}) async {
    await widget.wordPress.updateComment(
      comment: new wp.Comment(
        content: "Comment Updated2!",
        author: user.id,
        post: postId,
      ),
      id: id,
    ).then((c) {
      print('Comment updated successfully "$c"');
    }).catchError((err) {
      print('Failed to update Comment: $err');
    });
  }

11. Update Post

Future<void> updatePost({@required int id, @required int userId}) async {
    await widget.wordPress.updatePost(
      post: new wp.Post(
        title: 'First post as a Chief Editor',
        content: 'Blah! blah! blah!',
        excerpt: 'Discussion about blah!',
        authorID: userId,
        commentStatus: wp.PostCommentStatus.open,
        pingStatus: wp.PostPingStatus.closed,
        status: wp.PostPageStatus.publish,
        format: wp.PostFormat.standard,
        sticky: true,
      ),
      id: id, //
    ).then((p) {
      print('Post updated successfully with ID ${p}');
    }).catchError((err) {
      print('Failed to update post: $err');
    });
  }

12. Update User

Future<void> updateUser({@required int id, @required String username, @required String email}) async {
    await widget.wordPress.updateUser(
      user: new wp.User(
        description: "This is description for this user",
        username: username,
        id: id,
        email: email
      ),
      id: id,
    ).then((u) {
      print('User updated successfully $u');
    }).catchError((err) {
      print('Failed to update User: $err');
    });
  }

13. Delete Comment

Future<void> deleteComment({@required int id}) async {
    await widget.wordPress.deleteComment(id: id).then((c) {
      print('Comment Deleted successfully: $c');
    }).catchError((err) {
      print('Failed to Delete comment: $err');
    });
  }

14. Delete Post

  Future<void> deletePost({@required int id}) async {
    await widget.wordPress.deletePost(id: id).then((p) {
      print('Post Deleted successfully: $p');
    }).catchError((err) {
      print('Failed to Delete post: $err');
    });
  }

15. Delete User

  Future<void> deleteUser({@required int id, @required int reassign}) async {
    await widget.wordPress.deleteUser(id: id, reassign: reassign).then((u) {
      print('User Deleted successfully: $u');
    }).catchError((err) {
      print('Failed to Delete user: $err');
    });
  }

16. Upload Media

  uploadMedia(File image) async {
  var media = await wordPress.uploadMedia(image).then((m) {
    print('Media uploaded successfully: $m');
  }).catchError((err) {
    print('Failed to upload Media: $err');
  });
  int mediaID = media['id'];  
}

Future Work

  1. Implementing OAuth 2.0 authentication.

Contributors

Comments
  • Custom Post types

    Custom Post types

    How can I use this library to work with custom post types ? I created approx 20 custom post types for my app. Is there any way to use Custom Post Types?

    opened by Mayanktaker 8
  • featuredMedia doesn't get uploaded in createPost function

    featuredMedia doesn't get uploaded in createPost function

    When creating a post, featuredMedia is not getting uploaded to Wordpress nor it is setting as a featuredImage for the post, I tried passing many random .jpg and .png URLs from the internet but none of them worked. However, title, content, excerpt, and rest everything is working fine and a post is being created but without the Featured Media

    opened by GarvMaggu 6
  • remove flutter dependency

    remove flutter dependency

    Wonderful package!

    Use Case My intention is to create an API which does all the wordpress stuff (including dealing with several 1000 posts and a lot of categories) and packages it up all nice for the app. The api of course is dart, not flutter. I checked out some other packages, this is light years ahead, and set out to remove the flutter dependency. Turns out, that it's in name only, there isn't any flutter stuff which had to be moved to another package or redone in a different way.

    PR I just removed the flutter references from the pubspec.yaml. And the tests, because there weren't any, anyway.

    opened by yringler 3
  • Add fetchallCategories and fetchallPosts

    Add fetchallCategories and fetchallPosts

    This is something that I need to do. I can't imagine this ever being a good idea in a flutter app, but in a server side app I want to get the entire site and turn it into json optimized for my requirements.

    I have to do this one way or another - is it something which you'd be interesting in having in this plugin?

    opened by yringler 2
  • Issue regarding using your example app you provide in flutter_wordpress/example/lib

    Issue regarding using your example app you provide in flutter_wordpress/example/lib

    First it giving me this error: Android resource linking failed Output: C:\Users\Hp\Desktop\Development\flutter_wordpress\example\build\app\intermediates\incremental\mergeDebugResources\merged. To Solve this error i change the build.gradle file in flutter_wordpress\example\app. compileSdkVersion 27 to compileSdkVersion 28 which solve the error. After this the app is installed and running. As soon as I pass the username and password in the Form it comes with this error SocketException (SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 42706). I don't know how to solve this kindly tell me what i am doing wrong. My wordpress site is hosted at localhost with xammp server

    opened by shahryar-cmyk 2
  • Meta data & result header

    Meta data & result header

    • When fetching users, the wordpress backend returns the total amount of users in it's headers. This is returned in a FetchUserResult model, together with the list of users
    • Added meta data (as map<String,dynamic>) to be used in your application
    opened by harmjanr 2
  • JWT problem

    JWT problem

    i recive in login page: I/flutter ( 4103): WordPress Error! code: null, message: {"code":"jwt_auth_invalid_token","message":"Wrong number of segments","data":{"status":403}}, status: null

    but in postman work fine:

    opened by samatzhusup 1
  • Image Upload in createpost function: Feature request

    Image Upload in createpost function: Feature request

    Hi, can you please add the functionality for image upload to a Wordpress website? Or is there a way right now to attach images or featured media when creating a new post? @SachinGanesh

    opened by GarvMaggu 1
  • please help with error: A package may not list itself as a dependency

    please help with error: A package may not list itself as a dependency

    did i not follow step 1 correctly?

    Getting Started

    1. Import library First: Find your pubspec.yaml in the root of your project and add flutter_wordpress: ^0.2.0 under dependencies: ===================================

    pubspcc.yaml

    name: flutter_wordpress description: This library uses WordPress REST-API-V2 to provide a way for your application to interact with your WordPress website. version: 0.2.1 authors:

    environment: sdk: ">=2.0.0 <3.0.0"

    dependencies: flutter: sdk: flutter http: ^0.12.0+1 meta: ^1.1.8 flutter_wordpress: ^0.2.0

    dev_dependencies: flutter_test: sdk: flutter

    For information on the generic Dart part of this file, see the

    following page: https://www.dartlang.org/tools/pub/pubspec

    The following section is specific to Flutter.

    flutter:

    To add assets to your package, add an assets section, like this:

    assets:

    - images/a_dot_burr.jpeg

    - images/a_dot_ham.jpeg

    For details regarding assets in packages, see

    https://flutter.io/assets-and-images/#from-packages

    An image asset can refer to one or more resolution-specific "variants", see

    https://flutter.io/assets-and-images/#resolution-aware.

    To add custom fonts to your package, add a fonts section here,

    in this "flutter" section. Each entry in this list should have a

    "family" key with the font family name, and a "fonts" key with a

    list giving the asset and other descriptors for the font. For

    example:

    fonts:

    - family: Schyler

    fonts:

    - asset: fonts/Schyler-Regular.ttf

    - asset: fonts/Schyler-Italic.ttf

    style: italic

    - family: Trajan Pro

    fonts:

    - asset: fonts/TrajanPro.ttf

    - asset: fonts/TrajanPro_Bold.ttf

    weight: 700

    For details regarding fonts in packages, see

    https://flutter.io/custom-fonts/#from-packages

    =================================== [flutter_wordpress-master] flutter pub get Running "flutter pub get" in flutter_wordpress-master...
    Error on line 20, column 3 of pubspec.yaml: A package may not list itself as a dependency.

    opened by rays-github 1
  • Create, Update and Delete Comments. Create, Update and Delete Posts. Update and Delete Users added😍😎😉

    Create, Update and Delete Comments. Create, Update and Delete Posts. Update and Delete Users added😍😎😉

    ✔Create, Update and Delete Comments. ✔Create, Update and Delete Posts. ✔Update and Delete Users added 😍😎😉

    There is one thing left "Create New User" 😢 Will try to do that ASAP 😊

    opened by mymakarim 1
  • PostUpdate Added!

    PostUpdate Added!

    This package had postCreate but not the PostUpdate. So I forked and added this functionality to the package.

    I have coded the following as well😎 but not pushed it to the repo yet. If my pull request is accepted then I will push them and create another pull request.😊

    • Delete Posts
    • Create User
    • Update Users
    • Delete Users
    • Update Comments
    • Delete Comments
    opened by mymakarim 1
  • Creating new comment and post is not working: RangeError (index): Invalid value: Only valid value is 0: 1

    Creating new comment and post is not working: RangeError (index): Invalid value: Only valid value is 0: 1

    Getting a lot of errors when I try to add a post or comment.

    Failed to comment: RangeError (index): Invalid value: Only valid value is 0: 1

    I/flutter (17327): Failed to create post: NoSuchMethodError: The getter 'length' was called on null.
    I/flutter (17327): Receiver: null
    I/flutter (17327): Tried calling: length
    

    How can we solve this?

    opened by Siyaho 0
  • Login and post fetch works, but create post returns 404

    Login and post fetch works, but create post returns 404

    Hi, your example work correctly, after configuring JWT on my website, with login and posts fetch. But when I press the "create post" button it sends a request to https://MY_WEBSITE/wp-json/wp/v2/posts, passing default new post as parameter, and in response.statusCode I receive a 404 error. I've tried on the same URL with postman and it works correctly.

    Do you know why?

    opened by disu 1
  • Availability of 0.3.0 on pub.dev

    Availability of 0.3.0 on pub.dev

    Hi team. First off, thank you so much for such a great and easy to use library.

    I wanted to reach out and see if you guys are planning to push v0.3.0 to pub.dev? I see that PR #66 has been merged and the version has been bumped. The PR brings in a number of really useful changes. The http dependency upgrade to 0.13.0 is a big one, which would unblock some users from upgrading other http-dependent packages.

    Greatly appreciate your efforts.

    opened by nfattahi 1
  • Not able to get the data from my wordpress website

    Not able to get the data from my wordpress website

    I am not able to connect the server and get the data from my WordPress website with version ^0.2.1 I have tried with all the examples. But I am not getting the data from my website. Could you please help me what is the problem or do I need to install any plugin in my server? but I am not using any authentication. i just want to fetch the posts from my website. but it is not working.

    opened by PrakashKumar0143 0
Releases(v0.1.2)
Owner
Dreamsoft Innovations
AR | VR | Flutter App Development
Dreamsoft Innovations
Flutter-Wordpress-App - Cross platform wordpress news app built with Flutter

Flutter for Wordpress A flutter app for a wordpress websites with clean and elegant design. This app is available in free and pro version. You can cho

Madhav Poudel 243 Dec 23, 2022
Flutter ios/android app to get posts from Wordpress Rest Api

A Wordpress client for Flutter This project uses a simple WordPress website as a backend, without any additional plugin. for more information about Wo

Hooshyar 177 Dec 28, 2022
A WordPress API client for dart with support for WooCommerce and custom namespaces.

WordPress REST API client for Dart | Flutter Description A WordPress REST API client for dart with support for WooCommerce and custom namespaces/endpo

DHM Group 73 Nov 26, 2022
Fully Functional IOS/Android App for WordPress Website with Flutter

WordPress App with Flutter IOS/Android Native App for WordPress Website/Blog built using Flutter. No additional Plugins required for WordPress. Built

Atiq Samtia 155 Dec 30, 2022
Simple app that fetches data from a WordPress blog

Wordpress Blog App A simple Flutter Blog Application, which fetches data from naijatechguy.com, which is a blog, using the blog api. Still working on

Godsend Joseph 26 Nov 23, 2022
Bhagavad Gita app using flutter & Bhagavad-Gita-API is A lightweight Node.js based Bhagavad Gita API [An open source rest api on indian Vedic Scripture Shrimad Bhagavad Gita].

Gita Bhagavad Gita flutter app. Download App - Playstore Web Application About Bhagavad Gita app using flutter & Bhagavad-Gita-API is A lightweight No

Ravi Kovind 7 Apr 5, 2022
Beautiful Weather App using API with support for dark mode. Created by Jakub Sobański ( API ) and Martin Gogołowicz (UI, API help)

Flutter Weather App using API with darkmode support Flutter 2.8.1 Null Safety Beautiful Weather App using https://github.com/MonsieurZbanowanYY/Weathe

Jakub Sobański 5 Nov 29, 2022
Api Call Check flutter - A new Flutter project that demonstrates api calling and displays them in a scrollable list

api_fetch A new Flutter project that demonstrates api calling and displays them

Babish Shrestha 0 Jan 2, 2022
FLutter Api Integration - Flutter Rest API Integration

Flutter_Rest_Api_integration Flutter_Rest_Api_integration. Preview How To Use To

Rahul Ranjan Singh 0 Feb 17, 2022
This is a flutter app which uses the Bitrise Api(https://api-docs.bitrise.io/) to show the bitrise projects and builds and lets you download your artifacts.

Bitrise Artifact Downloader Introduction ??‍♂️ This is a flutter app which uses the Bitrise Api(https://api-docs.bitrise.io/) to show the bitrise proj

Jens Klingenberg 9 Apr 30, 2021
Api-Call - A basic mobile application for Networking in Flutter(API)

Github Api Call ?? ?? ?? Introduction This project is an basic mobile applicatio

navee-ramesh 5 Nov 11, 2022
APP desenvolvido em flutter que se comunica com uma API desenvolvida em python para controlar o mouse e teclado da maquina onde a API roda.

INSTRUÇÕES PARA EXECUÇÃO DA API Para executar a api em python, é necessario instalar as bibliotecas pynput, uvicorn e starlette e pyqrcode. Basta exec

João Paulo Prata 66 Mar 2, 2022
In this video we will learn how to Create CRUD Rest API for our Flutter application using NODEJS API.

Flutter CRUD Using NodeJS API In this video we will learn how to Create CRUD Rest API for our Flutter application using NODEJS API. ?? Packages Used h

SnippetCoder 14 Dec 30, 2022
Flutter project to Integrate API resources from JSON Place Holder API

rest_api_jsonplaceholder About This flutter project helps to Integrate API resources from JSON Place Holder API API Source: https://jsonplaceholder.ty

null 0 Apr 28, 2022
Dart API Client which wraps the QvaPay API

qvapay_api_client Dart API Client which wraps the QvaPay API The client needs Dio to perform the requests, you must inject an instance in the construc

QvaPay 7 Nov 2, 2022
A package help you to make api call and handle error faster, also you can check for internet before call api.

http_solver ##not for production use, only for learning purpose. A package help you to make api call and handle error faster, also you can check for i

Abdelrahman Saed 1 Jun 18, 2020
A most easily usable RESAS API wrapper in Dart. With this library, you can easily integrate your application with the RESAS API.

A most easily usable RESAS API wrapper library in Dart! 1. About 1.1. What Is RESAS? 1.2. Introduction 1.2.1. Install Library 1.2.2. Import It 1.2.3.

Kato Shinya 2 Apr 7, 2022
An Imgur API Client Library that uses Imgur's v3 API for Dart

imgur.dart An Imgur API Client Library that uses Imgur's v3 API for Dart. Usage

null 2 Dec 2, 2022
Federico 1 Feb 3, 2022