Repository: dreamsoftin/flutter_wordpress Branch: master Commit: 06b429fcd3a3 Files: 98 Total size: 289.3 KB Directory structure: gitextract_x59_vvxd/ ├── .gitignore ├── .idea/ │ ├── codeStyles/ │ │ └── Project.xml │ ├── dictionaries/ │ │ └── suraj.xml │ ├── libraries/ │ │ ├── Dart_Packages.xml │ │ ├── Dart_SDK.xml │ │ └── Flutter_Plugins.xml │ ├── modules.xml │ ├── vcs.xml │ └── workspace.xml ├── .metadata ├── CHANGELOG.md ├── LICENSE ├── README.md ├── example/ │ ├── .flutter-plugins-dependencies │ ├── .gitignore │ ├── .metadata │ ├── README.md │ ├── analysis_options.yaml │ ├── android/ │ │ ├── .gitignore │ │ ├── app/ │ │ │ ├── build.gradle │ │ │ └── src/ │ │ │ ├── debug/ │ │ │ │ └── AndroidManifest.xml │ │ │ ├── main/ │ │ │ │ ├── AndroidManifest.xml │ │ │ │ ├── kotlin/ │ │ │ │ │ └── com/ │ │ │ │ │ └── example/ │ │ │ │ │ └── example/ │ │ │ │ │ └── MainActivity.kt │ │ │ │ └── res/ │ │ │ │ ├── drawable/ │ │ │ │ │ └── launch_background.xml │ │ │ │ ├── drawable-v21/ │ │ │ │ │ └── launch_background.xml │ │ │ │ ├── values/ │ │ │ │ │ └── styles.xml │ │ │ │ └── values-night/ │ │ │ │ └── styles.xml │ │ │ └── profile/ │ │ │ └── AndroidManifest.xml │ │ ├── build.gradle │ │ ├── gradle/ │ │ │ └── wrapper/ │ │ │ └── gradle-wrapper.properties │ │ ├── gradle.properties │ │ └── settings.gradle │ ├── ios/ │ │ ├── .gitignore │ │ ├── Flutter/ │ │ │ ├── AppFrameworkInfo.plist │ │ │ ├── Debug.xcconfig │ │ │ ├── Flutter.podspec │ │ │ └── Release.xcconfig │ │ ├── Podfile │ │ ├── Runner/ │ │ │ ├── AppDelegate.h │ │ │ ├── AppDelegate.m │ │ │ ├── AppDelegate.swift │ │ │ ├── Assets.xcassets/ │ │ │ │ ├── AppIcon.appiconset/ │ │ │ │ │ └── Contents.json │ │ │ │ └── LaunchImage.imageset/ │ │ │ │ ├── Contents.json │ │ │ │ └── README.md │ │ │ ├── Base.lproj/ │ │ │ │ ├── LaunchScreen.storyboard │ │ │ │ └── Main.storyboard │ │ │ ├── Info.plist │ │ │ ├── Runner-Bridging-Header.h │ │ │ └── main.m │ │ ├── Runner.xcodeproj/ │ │ │ ├── project.pbxproj │ │ │ ├── project.xcworkspace/ │ │ │ │ ├── contents.xcworkspacedata │ │ │ │ └── xcshareddata/ │ │ │ │ ├── IDEWorkspaceChecks.plist │ │ │ │ └── WorkspaceSettings.xcsettings │ │ │ └── xcshareddata/ │ │ │ └── xcschemes/ │ │ │ └── Runner.xcscheme │ │ └── Runner.xcworkspace/ │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata/ │ │ ├── IDEWorkspaceChecks.plist │ │ └── WorkspaceSettings.xcsettings │ ├── lib/ │ │ ├── display_posts.dart │ │ ├── generated_plugin_registrant.dart │ │ ├── login.dart │ │ ├── main.dart │ │ └── post_page.dart │ ├── pubspec.yaml │ └── test/ │ └── widget_test.dart ├── flutter_wordpress.iml ├── lib/ │ ├── constants.dart │ ├── flutter_wordpress.dart │ ├── requests/ │ │ ├── params_category_list.dart │ │ ├── params_comment_list.dart │ │ ├── params_media_list.dart │ │ ├── params_page_list.dart │ │ ├── params_post_list.dart │ │ ├── params_tag_list.dart │ │ └── params_user_list.dart │ └── schemas/ │ ├── avatar_urls.dart │ ├── capabilities.dart │ ├── category.dart │ ├── comment.dart │ ├── comment_hierarchy.dart │ ├── content.dart │ ├── excerpt.dart │ ├── fetch_user_result.dart │ ├── guid.dart │ ├── jwt_response.dart │ ├── labels.dart │ ├── links.dart │ ├── media.dart │ ├── page.dart │ ├── post.dart │ ├── post_statuses.dart │ ├── post_types.dart │ ├── settings.dart │ ├── tag.dart │ ├── taxonomies.dart │ ├── title.dart │ ├── user.dart │ └── wordpress_error.dart └── pubspec.yaml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .DS_Store .dart_tool/ .packages .pub/ build/ ios/.generated/ ios/Flutter/Generated.xcconfig ios/Runner/GeneratedPluginRegistrant.* ================================================ FILE: .idea/codeStyles/Project.xml ================================================ ================================================ FILE: .idea/dictionaries/suraj.xml ================================================ wordpress ================================================ FILE: .idea/libraries/Dart_Packages.xml ================================================ ================================================ FILE: .idea/libraries/Dart_SDK.xml ================================================ ================================================ FILE: .idea/libraries/Flutter_Plugins.xml ================================================ ================================================ FILE: .idea/modules.xml ================================================ ================================================ FILE: .idea/vcs.xml ================================================ ================================================ FILE: .idea/workspace.xml ================================================ FetchUsersResult fontVariationSettings jwt createPo createPost dynamic meta updatePost fetchPosts _onValidUser me then comment createComment updatepost userid user.id user >= 200 && response.statusCode < 300 deletePst update user with deleteUser fetchUsers createuser deleteComment updatePOst updateUser role createUser create import this. , ; :'${}', if(this.\ final set : E:\DSI\2019\Flutter\flutter_wordpress\lib\schemas 1549864063234 1586516766033 1587208860611 1587209299445 1587209498939 1587210411959 1587210912739 1587236306886 1587236473336 1587501064903 ================================================ FILE: .metadata ================================================ # This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # # This file should be version controlled and should not be manually edited. version: revision: 5391447fae6209bb21a89e6a5a6583cac1af9b4b channel: stable project_type: package ================================================ FILE: CHANGELOG.md ================================================ ## [0.3.0-nullsafety.0] - Type Safety * Added type safety ## [0.2.1] - 26/04/2020 * Custom post types ## [0.2.0] - 21/04/2020 * Create, Update and Delete Comments * Create, Update and Delete Posts * Update and Delete Users ## [0.1.4] - 27/02/2019 * Updated homepage URL ## [0.1.3] - 26/02/2019 * Update example. Update post fetching to include author, comments. Add fetching comments as a hierarchy. ## [0.1.2] - 16/02/2019 * Add fetch categories, tags, pages. Add create post, comments. ## [0.1.1] - 14/02/2019 * Update README.md. Add fetch users list, fetch comments list. * Implemented authorization function and fetching of Posts with parameters ## [0.1.0] - Added Models * Created model classes for Wordpress REST API and implemented user authentication function using JWT authentication system. ## [0.0.1] - TODO: Init. * Under Development. Nothing works now. ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2018 Sachin Ganesh Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # Flutter Wordpress [pub.dev](https://pub.dev/packages/flutter_wordpress) This library uses [WordPress REST API V2](https://developer.wordpress.org/rest-api/) to provide a way for your application to interact with your WordPress website. [Tutorial - by Ritesh Sharma](https://medium.com/flutter-community/building-flutter-apps-with-wordpress-backend-part-1-e56414a4a79b) ## 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](https://wordpress.org/plugins/application-passwords/) 2. [JWT Authentication for WP REST API](https://wordpress.org/plugins/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: ```dart import 'package:flutter_wordpress/flutter_wordpress.dart' as wp; ``` ### 2. Instantiate WordPress class ```dart 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 ```dart Future response = wordPress.authenticateUser( username: 'ChiefEditor', password: 'chiefeditor@123', ); response.then((user) { createPost(user); }).catchError((err) { print('Failed to fetch user: $err'); }); ``` ### 4. Fetch Posts ```dart Future> 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 ```dart Future> 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 ```dart Future> comments = wordPress.fetchComments( params: wp.ParamsCommentList( context: wp.WordPressContext.view, pageNum: 1, perPage: 30, includePostIDs: [1], ), ); ``` ### 7. Create User ```dart Future createUser({@required String email, @required String username, @required String password, @required List 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 ```dart 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 ```dart 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 ```dart Future 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 ```dart Future 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 ```dart Future 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 ```dart Future 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 ```dart Future 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 ```dart Future 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 ```dart 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 - [Suraj Shettigar](https://github.com/SurajShettigar) - [Sachin Ganesh](https://github.com/SachinGanesh) - [Harm-Jan Roskam](https://github.com/harmjanr) - [Yahya Makarim](https://github.com/ymakarim) - [Garv Maggu](https://github.com/GarvMaggu) ================================================ FILE: example/.flutter-plugins-dependencies ================================================ {"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"video_player_avfoundation","path":"/Users/ritheshsalyan/Developer/DevTools/flutter/.pub-cache/hosted/pub.dartlang.org/video_player_avfoundation-2.3.0/","dependencies":[]},{"name":"wakelock","path":"/Users/ritheshsalyan/Developer/DevTools/flutter/.pub-cache/hosted/pub.dartlang.org/wakelock-0.6.1+1/","dependencies":[]},{"name":"webview_flutter_wkwebview","path":"/Users/ritheshsalyan/Developer/DevTools/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_wkwebview-2.7.1/","dependencies":[]}],"android":[{"name":"video_player_android","path":"/Users/ritheshsalyan/Developer/DevTools/flutter/.pub-cache/hosted/pub.dartlang.org/video_player_android-2.3.0/","dependencies":[]},{"name":"wakelock","path":"/Users/ritheshsalyan/Developer/DevTools/flutter/.pub-cache/hosted/pub.dartlang.org/wakelock-0.6.1+1/","dependencies":[]},{"name":"webview_flutter_android","path":"/Users/ritheshsalyan/Developer/DevTools/flutter/.pub-cache/hosted/pub.dartlang.org/webview_flutter_android-2.8.3/","dependencies":[]}],"macos":[{"name":"wakelock_macos","path":"/Users/ritheshsalyan/Developer/DevTools/flutter/.pub-cache/hosted/pub.dartlang.org/wakelock_macos-0.4.0/","dependencies":[]}],"linux":[],"windows":[],"web":[{"name":"video_player_web","path":"/Users/ritheshsalyan/Developer/DevTools/flutter/.pub-cache/hosted/pub.dartlang.org/video_player_web-2.0.7/","dependencies":[]},{"name":"wakelock_web","path":"/Users/ritheshsalyan/Developer/DevTools/flutter/.pub-cache/hosted/pub.dartlang.org/wakelock_web-0.4.0/","dependencies":[]}]},"dependencyGraph":[{"name":"video_player","dependencies":["video_player_android","video_player_avfoundation","video_player_web"]},{"name":"video_player_android","dependencies":[]},{"name":"video_player_avfoundation","dependencies":[]},{"name":"video_player_web","dependencies":[]},{"name":"wakelock","dependencies":["wakelock_macos","wakelock_web"]},{"name":"wakelock_macos","dependencies":[]},{"name":"wakelock_web","dependencies":[]},{"name":"webview_flutter","dependencies":["webview_flutter_android","webview_flutter_wkwebview"]},{"name":"webview_flutter_android","dependencies":[]},{"name":"webview_flutter_wkwebview","dependencies":[]}],"date_created":"2022-02-23 10:31:39.189036","version":"2.8.1"} ================================================ FILE: example/.gitignore ================================================ # Miscellaneous *.class *.lock *.log *.pyc *.swp .DS_Store .atom/ .buildlog/ .history .svn/ *flutter_export_environment* # IntelliJ related *.iml *.ipr *.iws .idea/ # Visual Studio Code related .vscode/ # Flutter/Dart/Pub related **/doc/api/ .dart_tool/ .flutter-plugins .packages .pub-cache/ .pub/ build/ # Android related **/android/**/gradle-wrapper.jar **/android/.gradle **/android/captures/ **/android/gradlew **/android/gradlew.bat **/android/local.properties **/android/**/GeneratedPluginRegistrant.java # iOS/XCode related **/ios/**/*.mode1v3 **/ios/**/*.mode2v3 **/ios/**/*.moved-aside **/ios/**/*.pbxuser **/ios/**/*.perspectivev3 **/ios/**/*sync/ **/ios/**/.sconsign.dblite **/ios/**/.tags* **/ios/**/.vagrant/ **/ios/**/DerivedData/ **/ios/**/Icon? **/ios/**/Pods/ **/ios/**/.symlinks/ **/ios/**/profile **/ios/**/xcuserdata **/ios/.generated/ **/ios/Flutter/App.framework **/ios/Flutter/Flutter.framework **/ios/Flutter/Generated.xcconfig **/ios/Flutter/app.flx **/ios/Flutter/app.zip **/ios/Flutter/flutter_assets/ **/ios/ServiceDefinitions.json **/ios/Runner/GeneratedPluginRegistrant.* # Exceptions to above rules. !**/ios/**/default.mode1v3 !**/ios/**/default.mode2v3 !**/ios/**/default.pbxuser !**/ios/**/default.perspectivev3 !/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages ================================================ FILE: example/.metadata ================================================ # This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # # This file should be version controlled and should not be manually edited. version: revision: 5391447fae6209bb21a89e6a5a6583cac1af9b4b channel: stable project_type: app ================================================ FILE: example/README.md ================================================ # Flutter Wordpress Example Basic login, displaying posts and comments have been implemented in this example flutter app. ## Screenshots ================================================ FILE: example/analysis_options.yaml ================================================ # This file configures the analyzer, which statically analyzes Dart code to # check for errors, warnings, and lints. # # The issues identified by the analyzer are surfaced in the UI of Dart-enabled # IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be # invoked from the command line by running `flutter analyze`. # The following line activates a set of recommended lints for Flutter apps, # packages, and plugins designed to encourage good coding practices. include: package:flutter_lints/flutter.yaml linter: # The lint rules applied to this project can be customized in the # section below to disable rules from the `package:flutter_lints/flutter.yaml` # included above or to enable additional rules. A list of all available lints # and their documentation is published at # https://dart-lang.github.io/linter/lints/index.html. # # Instead of disabling a lint rule for the entire project in the # section below, it can also be suppressed for a single line of code # or a specific dart file by using the `// ignore: name_of_lint` and # `// ignore_for_file: name_of_lint` syntax on the line or in the file # producing the lint. rules: # avoid_print: false # Uncomment to disable the `avoid_print` rule # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule # Additional information about this file can be found at # https://dart.dev/guides/language/analysis-options ================================================ FILE: example/android/.gitignore ================================================ gradle-wrapper.jar /.gradle /captures/ /gradlew /gradlew.bat /local.properties GeneratedPluginRegistrant.java # Remember to never publicly share your keystore. # See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app key.properties **/*.keystore **/*.jks ================================================ FILE: example/android/app/build.gradle ================================================ def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdkVersion flutter.compileSdkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.example.example" minSdkVersion 19//flutter.minSdkVersion targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" } ================================================ FILE: example/android/app/src/debug/AndroidManifest.xml ================================================ ================================================ FILE: example/android/app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: example/android/app/src/main/kotlin/com/example/example/MainActivity.kt ================================================ package com.example.example import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { } ================================================ FILE: example/android/app/src/main/res/drawable/launch_background.xml ================================================ ================================================ FILE: example/android/app/src/main/res/drawable-v21/launch_background.xml ================================================ ================================================ FILE: example/android/app/src/main/res/values/styles.xml ================================================ ================================================ FILE: example/android/app/src/main/res/values-night/styles.xml ================================================ ================================================ FILE: example/android/app/src/profile/AndroidManifest.xml ================================================ ================================================ FILE: example/android/build.gradle ================================================ buildscript { ext.kotlin_version = '1.6.10' repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:4.1.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } allprojects { repositories { google() mavenCentral() } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } task clean(type: Delete) { delete rootProject.buildDir } ================================================ FILE: example/android/gradle/wrapper/gradle-wrapper.properties ================================================ #Fri Jun 23 08:50:38 CEST 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip ================================================ FILE: example/android/gradle.properties ================================================ org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true ================================================ FILE: example/android/settings.gradle ================================================ include ':app' def localPropertiesFile = new File(rootProject.projectDir, "local.properties") def properties = new Properties() assert localPropertiesFile.exists() localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" ================================================ FILE: example/ios/.gitignore ================================================ **/dgph *.mode1v3 *.mode2v3 *.moved-aside *.pbxuser *.perspectivev3 **/*sync/ .sconsign.dblite .tags* **/.vagrant/ **/DerivedData/ Icon? **/Pods/ **/.symlinks/ profile xcuserdata **/.generated/ Flutter/App.framework Flutter/Flutter.framework Flutter/Flutter.podspec Flutter/Generated.xcconfig Flutter/ephemeral/ Flutter/app.flx Flutter/app.zip Flutter/flutter_assets/ Flutter/flutter_export_environment.sh ServiceDefinitions.json Runner/GeneratedPluginRegistrant.* # Exceptions to above rules. !default.mode1v3 !default.mode2v3 !default.pbxuser !default.perspectivev3 ================================================ FILE: example/ios/Flutter/AppFrameworkInfo.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable App CFBundleIdentifier io.flutter.flutter.app CFBundleInfoDictionaryVersion 6.0 CFBundleName App CFBundlePackageType FMWK CFBundleShortVersionString 1.0 CFBundleSignature ???? CFBundleVersion 1.0 MinimumOSVersion 8.0 ================================================ FILE: example/ios/Flutter/Debug.xcconfig ================================================ #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" ================================================ FILE: example/ios/Flutter/Flutter.podspec ================================================ # # NOTE: This podspec is NOT to be published. It is only used as a local source! # Pod::Spec.new do |s| s.name = 'Flutter' s.version = '1.0.0' s.summary = 'High-performance, high-fidelity mobile apps.' s.description = <<-DESC Flutter provides an easy and productive way to build and deploy high-performance mobile apps for Android and iOS. DESC s.homepage = 'https://flutter.io' s.license = { :type => 'MIT' } s.author = { 'Flutter Dev Team' => 'flutter-dev@googlegroups.com' } s.source = { :git => 'https://github.com/flutter/engine', :tag => s.version.to_s } s.ios.deployment_target = '8.0' s.vendored_frameworks = 'Flutter.framework' end ================================================ FILE: example/ios/Flutter/Release.xcconfig ================================================ #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" ================================================ FILE: example/ios/Podfile ================================================ # Uncomment this line to define a global platform for your project # platform :ios, '9.0' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' project 'Runner', { 'Debug' => :debug, 'Profile' => :release, 'Release' => :release, } def flutter_root generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) unless File.exist?(generated_xcode_build_settings_path) raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" end File.foreach(generated_xcode_build_settings_path) do |line| matches = line.match(/FLUTTER_ROOT\=(.*)/) return matches[1].strip if matches end raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" end require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) flutter_ios_podfile_setup target 'Runner' do flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) end post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) end end ================================================ FILE: example/ios/Runner/AppDelegate.h ================================================ #import #import @interface AppDelegate : FlutterAppDelegate @end ================================================ FILE: example/ios/Runner/AppDelegate.m ================================================ #include "AppDelegate.h" #include "GeneratedPluginRegistrant.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [GeneratedPluginRegistrant registerWithRegistry:self]; // Override point for customization after application launch. return [super application:application didFinishLaunchingWithOptions:launchOptions]; } @end ================================================ FILE: example/ios/Runner/AppDelegate.swift ================================================ import UIKit import Flutter @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } } ================================================ FILE: example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json ================================================ { "images" : [ { "size" : "20x20", "idiom" : "iphone", "filename" : "Icon-App-20x20@2x.png", "scale" : "2x" }, { "size" : "20x20", "idiom" : "iphone", "filename" : "Icon-App-20x20@3x.png", "scale" : "3x" }, { "size" : "29x29", "idiom" : "iphone", "filename" : "Icon-App-29x29@1x.png", "scale" : "1x" }, { "size" : "29x29", "idiom" : "iphone", "filename" : "Icon-App-29x29@2x.png", "scale" : "2x" }, { "size" : "29x29", "idiom" : "iphone", "filename" : "Icon-App-29x29@3x.png", "scale" : "3x" }, { "size" : "40x40", "idiom" : "iphone", "filename" : "Icon-App-40x40@2x.png", "scale" : "2x" }, { "size" : "40x40", "idiom" : "iphone", "filename" : "Icon-App-40x40@3x.png", "scale" : "3x" }, { "size" : "60x60", "idiom" : "iphone", "filename" : "Icon-App-60x60@2x.png", "scale" : "2x" }, { "size" : "60x60", "idiom" : "iphone", "filename" : "Icon-App-60x60@3x.png", "scale" : "3x" }, { "size" : "20x20", "idiom" : "ipad", "filename" : "Icon-App-20x20@1x.png", "scale" : "1x" }, { "size" : "20x20", "idiom" : "ipad", "filename" : "Icon-App-20x20@2x.png", "scale" : "2x" }, { "size" : "29x29", "idiom" : "ipad", "filename" : "Icon-App-29x29@1x.png", "scale" : "1x" }, { "size" : "29x29", "idiom" : "ipad", "filename" : "Icon-App-29x29@2x.png", "scale" : "2x" }, { "size" : "40x40", "idiom" : "ipad", "filename" : "Icon-App-40x40@1x.png", "scale" : "1x" }, { "size" : "40x40", "idiom" : "ipad", "filename" : "Icon-App-40x40@2x.png", "scale" : "2x" }, { "size" : "76x76", "idiom" : "ipad", "filename" : "Icon-App-76x76@1x.png", "scale" : "1x" }, { "size" : "76x76", "idiom" : "ipad", "filename" : "Icon-App-76x76@2x.png", "scale" : "2x" }, { "size" : "83.5x83.5", "idiom" : "ipad", "filename" : "Icon-App-83.5x83.5@2x.png", "scale" : "2x" }, { "size" : "1024x1024", "idiom" : "ios-marketing", "filename" : "Icon-App-1024x1024@1x.png", "scale" : "1x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json ================================================ { "images" : [ { "idiom" : "universal", "filename" : "LaunchImage.png", "scale" : "1x" }, { "idiom" : "universal", "filename" : "LaunchImage@2x.png", "scale" : "2x" }, { "idiom" : "universal", "filename" : "LaunchImage@3x.png", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md ================================================ # Launch Screen Assets You can customize the launch screen with your own desired assets by replacing the image files in this directory. You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. ================================================ FILE: example/ios/Runner/Base.lproj/LaunchScreen.storyboard ================================================ ================================================ FILE: example/ios/Runner/Base.lproj/Main.storyboard ================================================ ================================================ FILE: example/ios/Runner/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName example CFBundlePackageType APPL CFBundleShortVersionString $(FLUTTER_BUILD_NAME) CFBundleSignature ???? CFBundleVersion $(FLUTTER_BUILD_NUMBER) LSRequiresIPhoneOS UILaunchStoryboardName LaunchScreen UIMainStoryboardFile Main UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UISupportedInterfaceOrientations~ipad UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIViewControllerBasedStatusBarAppearance ================================================ FILE: example/ios/Runner/Runner-Bridging-Header.h ================================================ #import "GeneratedPluginRegistrant.h" ================================================ FILE: example/ios/Runner/main.m ================================================ #import #import #import "AppDelegate.h" int main(int argc, char* argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } } ================================================ FILE: example/ios/Runner.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 9740EEB41CF90195004384FC /* Debug.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = 9740EEB21CF90195004384FC /* Debug.xcconfig */; }; 978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */; }; 97C146F31CF9000F007C117D /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 97C146F21CF9000F007C117D /* main.m */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ 9705A1C41CF9048500538489 /* Embed Frameworks */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 10; files = ( ); name = "Embed Frameworks"; runOnlyForDeploymentPostprocessing = 0; }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; 97C146F21CF9000F007C117D /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 97C146EB1CF9000F007C117D /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, 9740EEB31CF90195004384FC /* Generated.xcconfig */, ); name = Flutter; sourceTree = ""; }; 97C146E51CF9000F007C117D = { isa = PBXGroup; children = ( 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, CF3B75C9A7D2FA2A4C99F110 /* Frameworks */, ); sourceTree = ""; }; 97C146EF1CF9000F007C117D /* Products */ = { isa = PBXGroup; children = ( 97C146EE1CF9000F007C117D /* Runner.app */, ); name = Products; sourceTree = ""; }; 97C146F01CF9000F007C117D /* Runner */ = { isa = PBXGroup; children = ( 7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */, 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */, 97C146FA1CF9000F007C117D /* Main.storyboard */, 97C146FD1CF9000F007C117D /* Assets.xcassets */, 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, 97C147021CF9000F007C117D /* Info.plist */, 97C146F11CF9000F007C117D /* Supporting Files */, 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, ); path = Runner; sourceTree = ""; }; 97C146F11CF9000F007C117D /* Supporting Files */ = { isa = PBXGroup; children = ( 97C146F21CF9000F007C117D /* main.m */, ); name = "Supporting Files"; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 97C146ED1CF9000F007C117D /* Runner */ = { isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, ); buildRules = ( ); dependencies = ( ); name = Runner; productName = Runner; productReference = 97C146EE1CF9000F007C117D /* Runner.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 97C146E61CF9000F007C117D /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 0910; ORGANIZATIONNAME = "The Chromium Authors"; TargetAttributes = { 97C146ED1CF9000F007C117D = { CreatedOnToolsVersion = 7.3.1; }; }; }; buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 97C146E51CF9000F007C117D; productRefGroup = 97C146EF1CF9000F007C117D /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 97C146ED1CF9000F007C117D /* Runner */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 97C146EC1CF9000F007C117D /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, 9740EEB41CF90195004384FC /* Debug.xcconfig in Resources */, 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "Thin Binary"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "Run Script"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 97C146EA1CF9000F007C117D /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */, 97C146F31CF9000F007C117D /* main.m in Sources */, 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ 97C146FA1CF9000F007C117D /* Main.storyboard */ = { isa = PBXVariantGroup; children = ( 97C146FB1CF9000F007C117D /* Base */, ); name = Main.storyboard; sourceTree = ""; }; 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { isa = PBXVariantGroup; children = ( 97C147001CF9000F007C117D /* Base */, ); name = LaunchScreen.storyboard; sourceTree = ""; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ 249021D3217E4FDB00AE95B9 /* Profile */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 8.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; name = Profile; }; 249021D4217E4FDB00AE95B9 /* Profile */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; DEVELOPMENT_TEAM = S8QB4VV633; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; LIBRARY_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); PRODUCT_BUNDLE_IDENTIFIER = com.example.example; PRODUCT_NAME = "$(TARGET_NAME)"; VERSIONING_SYSTEM = "apple-generic"; }; name = Profile; }; 97C147031CF9000F007C117D /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 8.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; }; 97C147041CF9000F007C117D /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 8.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; name = Release; }; 97C147061CF9000F007C117D /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; LIBRARY_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); PRODUCT_BUNDLE_IDENTIFIER = com.example.example; PRODUCT_NAME = "$(TARGET_NAME)"; VERSIONING_SYSTEM = "apple-generic"; }; name = Debug; }; 97C147071CF9000F007C117D /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; LIBRARY_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); PRODUCT_BUNDLE_IDENTIFIER = com.example.example; PRODUCT_NAME = "$(TARGET_NAME)"; VERSIONING_SYSTEM = "apple-generic"; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( 97C147031CF9000F007C117D /* Debug */, 97C147041CF9000F007C117D /* Release */, 249021D3217E4FDB00AE95B9 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( 97C147061CF9000F007C117D /* Debug */, 97C147071CF9000F007C117D /* Release */, 249021D4217E4FDB00AE95B9 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 97C146E61CF9000F007C117D /* Project object */; } ================================================ FILE: example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist ================================================ IDEDidComputeMac32BitWarning ================================================ FILE: example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings ================================================ PreviewsEnabled ================================================ FILE: example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme ================================================ ================================================ FILE: example/ios/Runner.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist ================================================ IDEDidComputeMac32BitWarning ================================================ FILE: example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings ================================================ PreviewsEnabled ================================================ FILE: example/lib/display_posts.dart ================================================ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_wordpress/flutter_wordpress.dart' as wp; import 'post_page.dart'; class PostListPage extends StatelessWidget { final wp.WordPress wordPress; final wp.User user; PostListPage({Key key, @required this.wordPress, this.user}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Posts"), ), body: Center( child: PostsBuilder( wordPress: wordPress, user: user, ), ), ); } } class PostsBuilder extends StatefulWidget { final wp.WordPress wordPress; final wp.User user; PostsBuilder({Key key, @required this.wordPress, this.user}); @override PostsBuilderState createState() => PostsBuilderState(); } class PostsBuilderState extends State { final paddingCardsList = EdgeInsets.symmetric(vertical: 4.0, horizontal: 8.0); final padding_4 = EdgeInsets.all(4.0); final padding_8 = EdgeInsets.all(8.0); final padding_16 = EdgeInsets.all(16.0); Future> posts; @override void initState() { super.initState(); fetchPosts(); } 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'); }); } // yahya Future createUser({@required String email, @required String username, @required String password, @required List 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'); }); } // ===================== // UPDATE START // ===================== Future 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'); }); } Future 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'); }); } Future 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'); }); } // ===================== // UPDATE END // ===================== // ===================== // DELETE START // ===================== Future 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'); }); } Future 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'); }); } Future 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'); }); } // ===================== // DELETE END // ===================== // end yahya 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'); }); } Future fetchPosts() { setState(() { posts = widget.wordPress.fetchPosts( postParams: wp.ParamsPostList(perPage: 1), fetchAuthor: true, fetchFeaturedMedia: true, ); }); return posts; } @override Widget build(BuildContext context) { return FutureBuilder>( future: posts, builder: (context, snapshot) { if (snapshot.hasData) { return RefreshIndicator( child: ListView.builder( itemBuilder: (context, i) { int id = snapshot.data[i].id; String title = snapshot.data[i].title.rendered; String author = snapshot.data[i].author.name; String content = snapshot.data[i].content.rendered; wp.Media featuredMedia = snapshot.data[i].featuredMedia; return Padding( padding: paddingCardsList, child: GestureDetector( onTap: () { openPostPage(snapshot.data[i]); }, child: _buildPostCard( author: author, title: title, content: content, featuredMedia: featuredMedia, id : id, ), ), ); }, itemCount: snapshot.data.length, ), onRefresh: fetchPosts, ); } else if (snapshot.hasError) { return Text( snapshot.error.toString(), style: TextStyle(color: Colors.red), ); } return CircularProgressIndicator( valueColor: AlwaysStoppedAnimation(Colors.blue), ); }, ); } Widget _buildPostCard({ String author, String title, String content, wp.Media featuredMedia, int id, }) { return Card( color: Colors.white, child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0), child: Text( title, style: Theme.of(context).textTheme.headline6, ), ), _buildFeaturedMedia(featuredMedia), featuredMedia == null ? Divider() : SizedBox( width: 0, height: 0, ), Padding( padding: EdgeInsets.symmetric(vertical: 0.0, horizontal: 8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Text( author, style: TextStyle( fontWeight: FontWeight.w200, ), ), ElevatedButton.icon( onPressed: () { createComment(postId: 1, userId: 1); }, icon: Icon(Icons.settings), label: Text( "Create New Comment", ), ), ElevatedButton.icon( onPressed: () { updateComment(user: widget.user, id: 1, postId: 1); }, icon: Icon(Icons.settings), label: Text( "Update Comment with ID #1", ), ), ElevatedButton.icon( onPressed: () { deleteComment(id: 1); }, icon: Icon(Icons.settings), label: Text( "Delete Comment with ID #1", ), ), ElevatedButton.icon( onPressed: () { updatePost(userId: widget.user.id, id: 1); }, icon: Icon(Icons.settings, color: Colors.white), label: Text( "Update Post with ID #1", style: TextStyle(color: Colors.white), ), ), ElevatedButton.icon( onPressed: () { deletePost(id: 1); }, icon: Icon(Icons.delete, color: Colors.white), label: Text( "Delete Post with ID #1", style: TextStyle(color: Colors.white), ), ), ElevatedButton.icon( onPressed: () { createPost(user: widget.user); }, icon: Icon(Icons.add_circle, color: Colors.white,), label: Text( "Create New Post", style: TextStyle(color: Colors.white), ), ), ElevatedButton.icon( onPressed: () { createUser(roles: ["subscriber"], username: "myUserName", password: "123", email: "myEmail@domain.com"); }, icon: Icon(Icons.add_circle, color: Colors.white,), label: Text( "Create New User", style: TextStyle(color: Colors.white), ), ), ElevatedButton.icon( onPressed: () { updateUser(id: 1, email: "newuser@gmaill.com", username: "newuser"); }, icon: Icon(Icons.settings, color: Colors.white,), label: Text( "Update User with ID #1", style: TextStyle(color: Colors.white), ), ), ElevatedButton.icon( onPressed: () { deleteUser(id: 1, reassign: 1); }, icon: Icon(Icons.delete, color: Colors.white,), label: Text( "Delete User with ID #1", style: TextStyle(color: Colors.white), ), ) ], ), ), ], ), ); } Widget _buildFeaturedMedia(wp.Media featuredMedia) { if (featuredMedia == null) { return SizedBox( width: 0.0, height: 0.0, ); } String imgSource = featuredMedia.mediaDetails.sizes.mediumLarge.sourceUrl; imgSource = imgSource.replaceAll('localhost', '192.168.6.165'); return Center( child: Image.network( imgSource, fit: BoxFit.cover, ), ); } void openPostPage(wp.Post post) { print('OnTapped'); Navigator.push( context, MaterialPageRoute(builder: (context) { return SinglePostPage( wordPress: widget.wordPress, post: post, ); }), ); } } ================================================ FILE: example/lib/generated_plugin_registrant.dart ================================================ // // Generated file. Do not edit. // // ignore_for_file: directives_ordering // ignore_for_file: lines_longer_than_80_chars import 'package:video_player_web/video_player_web.dart'; import 'package:wakelock_web/wakelock_web.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; // ignore: public_member_api_docs void registerPlugins(Registrar registrar) { VideoPlayerPlugin.registerWith(registrar); WakelockWeb.registerWith(registrar); registrar.registerMessageHandler(); } ================================================ FILE: example/lib/login.dart ================================================ import 'package:flutter/material.dart'; import 'package:flutter_wordpress/flutter_wordpress.dart' as wp; import 'display_posts.dart'; const PADDING_16 = EdgeInsets.all(16.0); const PADDING_8 = EdgeInsets.all(8.0); class LoginPage extends StatefulWidget { @override LoginPageState createState() => LoginPageState(); } class LoginPageState extends State { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( "Login", style: TextStyle(fontWeight: FontWeight.w300), ), centerTitle: true, ), body: LoginFields(), ); } } class LoginFields extends StatefulWidget { @override LoginFieldsState createState() => LoginFieldsState(); } class LoginFieldsState extends State { String _username; String _password; bool _isDetailValid = true; bool _isValidating = false; @override void initState() { super.initState(); _username = 'YOUR_USERNAME'; _password = 'YOUR_PASSWORD'; } @override Widget build(BuildContext context) { return Center( child: SingleChildScrollView( child: Container( padding: PADDING_16, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Padding( padding: PADDING_8, child: _buildFormField( icon: Icon(Icons.person), labelText: "Username", hintText: "Username", initialText: _username, onChanged: _onUsernameChanged, ), ), Padding( padding: PADDING_8, child: _buildFormField( icon: Icon(Icons.lock), labelText: "Password", hintText: "Password", initialText: _password, obscureText: true, onChanged: _onPasswordChanged, ), ), _isDetailValid ? SizedBox( width: 0.0, height: 0.0, ) : Padding( padding: PADDING_8, child: Text( "Invalid Username / Password", style: TextStyle( color: Colors.red, ), ), ), ElevatedButton( onPressed: _isValidating ? () {} : _validateUser, child: Padding( padding: PADDING_8, child: _isValidating ? CircularProgressIndicator( valueColor: AlwaysStoppedAnimation(Colors.white), ) : Text('Login'), ), ), ], ), ), )); } Widget _buildFormField({ Icon icon, String labelText, String hintText, String initialText, TextInputType inputType = TextInputType.text, bool obscureText = false, onChanged, }) { return TextField( decoration: InputDecoration( icon: icon, labelText: labelText, hintText: hintText, border: OutlineInputBorder( borderRadius: BorderRadius.circular(4.0), ), ), controller: TextEditingController(text: initialText), keyboardType: inputType, obscureText: obscureText, onChanged: onChanged, ); } void _onUsernameChanged(String value) { _username = value; } void _onPasswordChanged(String value) { _password = value; } void _validateUser() { setState(() { _isValidating = true; }); wp.WordPress wordPress = new wp.WordPress( baseUrl: 'YOUR WEBSITE URL', authenticator: wp.WordPressAuthenticator.JWT, adminName: '', adminKey: '', ); final response = wordPress.authenticateUser(username: _username, password: _password); response.then((user) { setState(() { _isDetailValid = true; _isValidating = false; _onValidUser(wordPress, user); }); }).catchError((err) { print(err.toString()); setState(() { _isDetailValid = false; _isValidating = false; }); }); } void _onValidUser(wp.WordPress wordPress, wp.User user) { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => PostListPage( wordPress: wordPress, user: user, ), ), ); } } ================================================ FILE: example/lib/main.dart ================================================ import 'package:flutter/material.dart'; import 'login.dart'; void main() { runApp(WordPressApp()); } class WordPressApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'WordPress Demo', theme: ThemeData.light(), home: LoginPage(), ); } } ================================================ FILE: example/lib/post_page.dart ================================================ import 'package:flutter/material.dart'; import 'package:flutter_html/flutter_html.dart'; import 'package:flutter_wordpress/flutter_wordpress.dart' as wp; class SinglePostPage extends StatelessWidget { final wp.WordPress wordPress; final wp.Post post; SinglePostPage({Key key, @required this.wordPress, @required this.post}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(post.title.rendered), ), body: Padding( padding: EdgeInsets.all(8.0), child: PostWithComments(wordPress: wordPress, post: post), ), ); } } class PostWithComments extends StatefulWidget { final wp.WordPress wordPress; final wp.Post post; PostWithComments({@required this.wordPress, @required this.post}); @override PostWithCommentsState createState() => PostWithCommentsState(); } class PostWithCommentsState extends State { String _content; Future> _comments; @override void initState() { super.initState(); _content = widget.post.content.rendered; _content = _content.replaceAll('localhost', '192.168.6.165'); fetchComments(); } void fetchComments() { setState(() { _comments = widget.wordPress.fetchCommentsAsHierarchy( params: wp.ParamsCommentList( includePostIDs: [widget.post.id], )); }); } @override Widget build(BuildContext context) { return CustomScrollView( slivers: [ SliverList( delegate: SliverChildListDelegate( [ Html( data: _content, // blockSpacing: 0.0, ), Divider(), Row( children: [ Icon(Icons.comment), Text('Comments'), ], ), Divider(), ], ), ), FutureBuilder( future: _comments, builder: (context, snapshot) { return SliverList( delegate: _buildCommentsSection(snapshot), ); }, ), ], ); } SliverChildDelegate _buildCommentsSection( AsyncSnapshot> snapshot) { if (snapshot.hasData) { return _buildComments(snapshot.data); } else if (snapshot.hasError) { return SliverChildListDelegate([ Text( 'Error fetching comments: ${snapshot.error.toString()}', style: TextStyle( color: Colors.red, ), ) ]); } return SliverChildListDelegate( [ Center( child: CircularProgressIndicator( valueColor: AlwaysStoppedAnimation(Colors.blue), ), ), ], ); } SliverChildBuilderDelegate _buildComments( List comments) { return SliverChildBuilderDelegate( (BuildContext context, int i) { if (comments == null || comments.length == 0) { return Center( child: Padding( padding: EdgeInsets.all(8.0), child: Text( 'No comments', style: Theme.of(context).textTheme.bodyText1, ), ), ); } if (i % 2 != 0) { return Divider(); } return _buildCommentTile(comments[(i / 2).ceil()]); }, childCount: comments == null || comments.length == 0 ? 1 : comments.length * 2, ); } Widget _buildCommentTile(wp.CommentHierarchy root) { if (root.children == null) { return Padding( padding: EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Html( data: root.comment.content.rendered, // blockSpacing: 0.0, ), Text( root.comment.authorName, style: TextStyle( color: Colors.grey, fontWeight: FontWeight.w300, ), ), ], ), ); } else { return ExpansionTile( title: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Html( data: root.comment.content.rendered, // blockSpacing: 0.0, ), Text( root.comment.authorName, style: TextStyle( color: Colors.grey, fontWeight: FontWeight.w300, ), ), ], ), children: root.children.map((c) { return Padding( padding: EdgeInsets.only(left: 16.0), child: _buildCommentTile(c), ); }).toList(), ); } } } ================================================ FILE: example/pubspec.yaml ================================================ name: flutter_wordpress_example description: Wordpress API testing example. # The following defines the version and build number for your application. # A version number is three numbers separated by dots, like 1.2.43 # followed by an optional build number separated by a +. # Both the version and the builder number may be overridden in flutter # build by specifying --build-name and --build-number, respectively. # Read more about versioning at semver.org. version: 1.0.0+1 publish_to: none environment: sdk: ">=2.0.0-dev.68.0 <3.0.0" dependencies: flutter_wordpress: path: ../ flutter: sdk: flutter flutter_html: ^2.2.1 # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.4 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: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg # - images/a_dot_ham.jpeg # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.io/assets-and-images/#resolution-aware. # For details regarding adding assets from package dependencies, see # https://flutter.io/assets-and-images/#from-packages # To add custom fonts to your application, 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 from package dependencies, # see https://flutter.io/custom-fonts/#from-packages ================================================ FILE: example/test/widget_test.dart ================================================ // This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_wordpress_example/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(WordPressApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); } ================================================ FILE: flutter_wordpress.iml ================================================ ================================================ FILE: lib/constants.dart ================================================ const URL_JWT_BASE = '/wp-json/jwt-auth/v1'; const URL_WP_BASE = '/wp-json/wp/v2'; const URL_JWT_TOKEN = '$URL_JWT_BASE/token'; const URL_JWT_TOKEN_VALIDATE = '$URL_JWT_BASE/token/validate'; const URL_CATEGORIES = '$URL_WP_BASE/categories'; const URL_COMMENTS = '$URL_WP_BASE/comments'; const URL_MEDIA = '$URL_WP_BASE/media'; const URL_PAGES = '$URL_WP_BASE/pages'; const URL_POSTS = '$URL_WP_BASE/posts'; const URL_TAGS = '$URL_WP_BASE/tags'; const URL_USERS = '$URL_WP_BASE/users'; const URL_USER_ME = '$URL_WP_BASE/users/me'; enum WordPressAuthenticator { JWT, ApplicationPasswords, } enum WordPressContext { view, embed, edit } enum Order { asc, desc, } enum PostOrderBy { author, date, id, include, modified, parent, relevance, slug, title, } enum PostPageStatus { publish, future, draft, pending, private, } enum PostCommentStatus { open, closed, } enum PostPingStatus { open, closed, } enum PostFormat { standard, aside, chat, gallery, link, image, quote, status, video, audio, } enum UserOrderBy { id, include, name, registered_date, slug, email, url, } enum CommentOrderBy { date, date_gmt, id, include, post, parent, type, } enum CommentStatus { all, approve, hold, spam, trash, } enum CommentType { comment, //TODO: Add all comment types } enum CategoryTagOrderBy { id, include, name, slug, term_group, description, count, } enum PageOrderBy { author, date, id, include, modified, parent, relevance, slug, title, menu_order, } enum MediaOrderBy { author, date, id, include, modified, parent, relevance, slug, title, } enum MediaStatus { inherit, publish, future, draft, pending, private, } enum MediaType { image, video, audio, application, } /// Converts an enum string to enum value name. String enumStringToName(String enumString) { return enumString.split('.')[1]; } /// Formats a list of [items] to a comma(,) separated string to pass it as a /// URL parameter. String listToUrlString(List items) { if (items.length == 0) return ''; return items.join(','); } /// Formats a [Map] of parameters to a string of URL friendly parameters. String constructUrlParams(Map params) { StringBuffer p = new StringBuffer('/?'); params.forEach((key, value) { if (value != '') { p.write('$key=$value'); p.write('&'); } }); return p.toString(); } ================================================ FILE: lib/flutter_wordpress.dart ================================================ /// This library uses [WordPress REST API V2](https://developer.wordpress.org/rest-api/) /// to provide a way for your application to interact with your WordPress website. /// /// We use terminologies similar to the [WordPress REST API](https://developer.wordpress.org/rest-api/) /// /// For authentication and usage of administrator level APIs, we have implemented /// two popular authentication plugins: /// /// 1. [Application Passwords](https://wordpress.org/plugins/application-passwords/) /// 2. [JWT Authentication for WP REST API](https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/) library flutter_wordpress; import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; import 'constants.dart'; import 'requests/params_category_list.dart'; import 'requests/params_comment_list.dart'; import 'requests/params_media_list.dart'; import 'requests/params_page_list.dart'; import 'requests/params_post_list.dart'; import 'requests/params_tag_list.dart'; import 'requests/params_user_list.dart'; import 'schemas/category.dart'; import 'schemas/comment.dart'; import 'schemas/comment_hierarchy.dart'; import 'schemas/fetch_user_result.dart'; import 'schemas/jwt_response.dart'; import 'schemas/media.dart'; import 'schemas/page.dart'; import 'schemas/post.dart'; import 'schemas/tag.dart'; import 'schemas/user.dart'; import 'schemas/wordpress_error.dart'; export 'constants.dart'; export 'requests/params_category_list.dart'; export 'requests/params_comment_list.dart'; export 'requests/params_media_list.dart'; export 'requests/params_page_list.dart'; export 'requests/params_post_list.dart'; export 'requests/params_tag_list.dart'; export 'requests/params_user_list.dart'; export 'schemas/avatar_urls.dart'; export 'schemas/category.dart'; export 'schemas/comment.dart'; export 'schemas/comment_hierarchy.dart'; export 'schemas/content.dart'; export 'schemas/excerpt.dart'; export 'schemas/fetch_user_result.dart'; export 'schemas/guid.dart'; export 'schemas/jwt_response.dart'; export 'schemas/labels.dart'; export 'schemas/links.dart'; export 'schemas/media.dart'; export 'schemas/page.dart'; export 'schemas/post.dart'; export 'schemas/settings.dart'; export 'schemas/tag.dart'; export 'schemas/title.dart'; export 'schemas/user.dart'; export 'schemas/wordpress_error.dart'; /// All WordPress related functionality are defined under this class. class WordPress { late String _baseUrl; late WordPressAuthenticator _authenticator; String _token = ""; Map _urlHeader = { 'Authorization': '', }; /// If [WordPressAuthenticator.ApplicationPasswords] is used as an authenticator, /// [adminName] and [adminKey] is necessary for authentication. /// https://wordpress.org/plugins/application-passwords/ WordPress({ required String baseUrl, required WordPressAuthenticator authenticator, String? adminName, String? adminKey, }) { this._baseUrl = baseUrl.endsWith('/') ? baseUrl.substring(0, baseUrl.length - 1) : baseUrl; this._authenticator = authenticator; if (adminName != null && adminKey != null) { switch (this._authenticator) { case WordPressAuthenticator.ApplicationPasswords: String str = '$adminName:$adminKey'; String base64 = base64Encode(utf8.encode(str)); _urlHeader['Authorization'] = 'Basic $base64'; break; case WordPressAuthenticator.JWT: //TODO: Implement JWT Admin authentication break; } } } /// This returns a [User] object when a user with valid [username] and [password] /// has been successfully authenticated. /// /// In case of an error, a [WordPressError] object is thrown. Future authenticateUser({ required username, required password, }) async { if (_authenticator == WordPressAuthenticator.ApplicationPasswords) { return _authenticateViaAP(username, password); } else if (_authenticator == WordPressAuthenticator.JWT) { return _authenticateViaJWT(username, password); } else return fetchUser(username: username); } Future _authenticateViaAP(username, password) async { return fetchUser(username: username); } Future _authenticateViaJWT(String username, String password) async { final body = { 'username': username, 'password': password, }; final response = await http.post( Uri.parse(_baseUrl + URL_JWT_TOKEN), body: body, ); if (response.statusCode >= 200 && response.statusCode < 300) { JWTResponse authResponse = JWTResponse.fromJson( json.decode(response.body), ); _token = authResponse.token!; _urlHeader['Authorization'] = 'Bearer ${authResponse.token}'; return fetchUser(email: authResponse.userEmail); } else { try { throw new WordPressError.fromJson(json.decode(response.body)); } catch (e) { throw new WordPressError(message: response.body); } } } String getToken() { return _token; } Future authenticateViaToken(String token) async { _urlHeader['Authorization'] = 'Bearer ${token}'; final response = await http.post( Uri.parse(_baseUrl + URL_JWT_TOKEN_VALIDATE), headers: _urlHeader, ); if (response.statusCode >= 200 && response.statusCode < 300) { return fetchMeUser(); } else { throw new WordPressError(message: response.body); } } /// This returns a [User] object if the user with [id], [email] or [username] /// exists. Otherwise throws [WordPressError]. /// /// Only one parameter is enough to search for the user. /// /// In case of an error, a [WordPressError] object is thrown. Future fetchUser({ int? id, String? email, String? username, }) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_USERS); final Map params = { 'search': '', }; if (id != null) { params['search'] = '$id'; } else if (email != null) params['search'] = email; else if (username != null) params['search'] = username; url.write(constructUrlParams(params)); final response = await http.get( Uri.parse(url.toString()), headers: _urlHeader, ); if (response.statusCode >= 200 && response.statusCode < 300) { final jsonStr = json.decode(response.body); if (jsonStr.length == 0) throw new WordPressError( code: 'wp_empty_list', message: "No users found"); return User.fromJson(jsonStr[0]); } else { try { WordPressError err = WordPressError.fromJson( json.decode(response.body), ); throw err; } catch (e) { throw new WordPressError(message: response.body); } } } /// This returns the me [User] object with the current token. Otherwise throws [WordPressError]. /// /// In case of an error, a [WordPressError] object is thrown. Future fetchMeUser() async { final response = await http.get( Uri.parse(_baseUrl + URL_USER_ME), headers: _urlHeader, ); if (response.statusCode >= 200 && response.statusCode < 300) { final jsonStr = json.decode(response.body); if (jsonStr.length == 0) throw new WordPressError( code: 'wp_empty_user', message: "No user found"); return User.fromJson(jsonStr); } else { try { WordPressError err = WordPressError.fromJson(json.decode(response.body)); throw err; } catch (e) { throw new WordPressError(message: response.body); } } } /// This returns a list of [Post] based on the filter parameters /// specified through [ParamsPostList] object. By default it returns only /// [ParamsPostList.perPage] number of posts in page [ParamsPostList.pageNum]. /// /// [fetchAuthor], [fetchComments], [fetchCategories], [fetchTags], /// [fetchFeaturedMedia] and [fetchAttachments] will fetch and set [Post.author], /// [Post.comments], [Post.categories], [Post.tags], [Post.featuredMedia] and /// [Post.attachments] respectively. If they are non-existent, their values will /// null. /// /// (**Note:** *Set only those fetch boolean parameters which you need because /// the more information to fetch, the longer it will take to return all Posts*) /// /// [fetchAll] will make as many API requests as is needed to get all posts. /// This may take a while. /// /// In case of an error, a [WordPressError] object is thrown. Future> fetchPosts( {required ParamsPostList postParams, bool fetchAuthor = false, bool fetchComments = false, Order orderComments = Order.desc, CommentOrderBy orderCommentsBy = CommentOrderBy.date, bool fetchCategories = false, bool fetchTags = false, bool fetchFeaturedMedia = false, bool fetchAttachments = false, String postType = "posts", bool fetchAll = false}) async { int bulkBatchNum = 100; if (fetchAll) { postParams = postParams.copyWith(perPage: bulkBatchNum); } Map authorsByID = {}; Map authorIDForPostIDs = {}; Map postsByID = {}; Map> commentsForPostIDs = {}; Map featuredMediaIDForPostIDs = {}; Map featuredMediaByID = {}; Map categoriesByID = {}; Map tagsByID = {}; Map> attachmentsForPostIDs = {}; /// This function fetches post information such as author, comments, categories, /// tags, featuredMedia and attachments. var _postPrep = ({ required Post post, bool setAuthor = false, bool setComments = false, bool setCategories = false, bool setTags = false, bool setFeaturedMedia = false, bool setAttachments = false, }) async { if (setAuthor && post.id != null && post.authorID != null) { authorIDForPostIDs[post.id!] = post.authorID!; } if (setComments && post.id != null) { commentsForPostIDs[post.id!] = []; } if (setCategories) { post.categoryIDs ?.forEach((id) => categoriesByID[id] = Category(id: id)); } if (setTags) { post.tagIDs?.forEach((id) => tagsByID[id] = Tag(id: id)); } if (setFeaturedMedia && post.id != null && post.featuredMediaID != null) { featuredMediaIDForPostIDs[post.id!] = post.featuredMediaID!; } if (setAttachments && post.id != null) { attachmentsForPostIDs[post.id!] = []; } return post; }; final StringBuffer url = new StringBuffer(_baseUrl + URL_WP_BASE + "/" + postType); url.write(postParams.toString()); final response = await http.get(Uri.parse(url.toString()), headers: _urlHeader); if (response.statusCode >= 200 && response.statusCode < 300) { final list = json.decode(response.body); for (final post in list) { var pt = await _postPrep( post: Post.fromJson(post), setAuthor: fetchAuthor, setComments: fetchComments, setFeaturedMedia: fetchFeaturedMedia, setCategories: fetchCategories, setAttachments: fetchAttachments, ); if (pt.id != null) postsByID[pt.id!] = pt; } var pids = postsByID.keys.toList(); //handler to fetch authors var handleGettingAuthors = ({bool setAuthor = false}) async { if (setAuthor) { var aids = authorIDForPostIDs.values.toList(); FetchUsersResult authResult = await fetchUsers(params: ParamsUserList(includeUserIDs: aids)); authorsByID = Map.fromIterable(authResult.users, key: (u) => u.id, value: (u) => u); if (authResult.users.length != authResult.totalUsers && authResult.totalUsers != null) { var stride = authResult.users.length; var numOfCalls = (authResult.totalUsers! / stride) + 1; for (var i = 2; i <= numOfCalls; i++) { FetchUsersResult result = await fetchUsers( params: ParamsUserList( includeUserIDs: aids, pageNum: i, perPage: stride, )); result.users.forEach((u) { if (u.id != null) authorsByID[u.id!] = u; }); } } } }; //handler to fetch comments var handleGettingComments = ({bool setComments = false}) async { if (setComments) { List comments = await this.fetchComments( params: ParamsCommentList( includePostIDs: pids, order: orderComments, orderBy: orderCommentsBy, perPage: bulkBatchNum, pageNum: 1, )); if (comments.length != 0) { comments.forEach((comment) { commentsForPostIDs[comment.post]?.add(comment); }); var i = 2; while (comments.length == bulkBatchNum) { comments = await this.fetchComments( params: ParamsCommentList( includePostIDs: pids, order: orderComments, orderBy: orderCommentsBy, perPage: bulkBatchNum, pageNum: i, )); comments.forEach((comment) { commentsForPostIDs[comment.post]?.add(comment); }); i += 1; } } } }; //handler to fetch categories var handleGettingCategories = ({bool setCategories = false}) async { if (setCategories) { var cids = categoriesByID.keys.toList(); List categories = await this.fetchCategories( params: ParamsCategoryList( includeCategoryIDs: cids, perPage: bulkBatchNum, pageNum: 1, )); if (categories.length != 0) { categories.forEach((cat) { if (cat.id != null) categoriesByID[cat.id!] = cat; }); var i = 2; while (categories.length == bulkBatchNum) { categories = await this.fetchCategories( params: ParamsCategoryList( includeCategoryIDs: cids, perPage: bulkBatchNum, pageNum: i, )); categories.forEach((cat) { if (cat.id != null) categoriesByID[cat.id!] = cat; }); i += 1; } } } }; //handler to fetch tags var handleGettingTags = ({bool setTags = false}) async { var tids = tagsByID.keys.toList(); if (setTags) { List tags = await this.fetchTags( params: ParamsTagList( includeTagIDs: tids, perPage: bulkBatchNum, pageNum: 1, )); if (tags.length != 0) { tags.forEach((tag) { if (tag.id != null) tagsByID[tag.id!] = tag; }); var i = 2; while (tags.length == bulkBatchNum) { tags = await this.fetchTags( params: ParamsTagList( includeTagIDs: tids, perPage: bulkBatchNum, pageNum: i, )); tags.forEach((tag) { if (tag.id != null) tagsByID[tag.id!] = tag; }); i += 1; } } } }; //handler to fetch featured media var handleGettingFeaturedMedia = ({bool setFeaturedMedia = false}) async { if (setFeaturedMedia) { var fids = featuredMediaIDForPostIDs.values.toList(); List media = await this.fetchMediaList( params: ParamsMediaList( includeMediaIDs: fids, perPage: bulkBatchNum, pageNum: 1), ); if (media.length != 0) { media.forEach((fm) { if (fm.id != null) featuredMediaByID[fm.id!] = fm; }); var i = 2; while (media.length == bulkBatchNum) { media = await this.fetchMediaList( params: ParamsMediaList( includeMediaIDs: fids, perPage: bulkBatchNum, pageNum: i, ), ); media.forEach((fm) { if (fm.id != null) featuredMediaByID[fm.id!] = fm; }); i += 1; } } } }; //handler to fetch attachments var handleGettingAttachments = ({bool setAttachments = false}) async { if (setAttachments) { List attachments = await this.fetchMediaList( params: ParamsMediaList( includeParentIDs: pids, perPage: bulkBatchNum, pageNum: 1, ), ); if (attachments.length != 0) { attachments.forEach((attachment) { attachmentsForPostIDs[attachment.post]?.add(attachment); }); var i = 2; while (attachments.length == bulkBatchNum) { attachments = await this.fetchMediaList( params: ParamsMediaList( includeParentIDs: pids, perPage: bulkBatchNum, pageNum: i, ), ); attachments.forEach((attachment) { attachmentsForPostIDs[attachment.post]?.add(attachment); }); i += 1; } } } }; await Future.wait([ handleGettingAuthors(setAuthor: fetchAuthor), handleGettingComments(setComments: fetchComments), handleGettingCategories(setCategories: fetchCategories), handleGettingTags(setTags: fetchTags), handleGettingFeaturedMedia(setFeaturedMedia: fetchFeaturedMedia), handleGettingAttachments(setAttachments: fetchAttachments), ]); //fill posts postsByID.values.forEach((post) { //handle Author if (fetchAuthor) { post.author = authorsByID[post.authorID]; } //handle comments if (fetchComments) { post.comments = commentsForPostIDs[post.id]; post.commentsHierarchy = []; if (post.comments != null) { post.comments?.forEach((comment) { if (comment.parent == 0) post.commentsHierarchy?.add( _commentHierarchyBuilder(post.comments ?? [], comment)); }); } } //handle categories if (fetchCategories) { post.categories = []; post.categoryIDs?.forEach((catid) { if (categoriesByID[catid] != null) post.categories?.add(categoriesByID[catid]!); }); } //handle tags if (fetchTags) { post.tags = []; post.tagIDs?.forEach((id) { if (tagsByID[id] != null) post.tags?.add(tagsByID[id]!); }); } //handle featured media if (fetchFeaturedMedia) { post.featuredMedia = featuredMediaByID[featuredMediaIDForPostIDs[post.id]]; } //handle attachments if (fetchAttachments) { post.attachments = attachmentsForPostIDs[post.id]; } }); if (fetchAll && response.headers["x-wp-totalpages"] != null) { final totalPages = int.parse(response.headers["x-wp-totalpages"]!); for (int i = postParams.pageNum + 1; i <= totalPages; ++i) { (await fetchPosts( postParams: postParams.copyWith(pageNum: i), fetchAuthor: fetchAuthor, fetchComments: fetchComments, orderComments: orderComments, orderCommentsBy: orderCommentsBy, fetchCategories: fetchCategories, fetchTags: fetchTags, fetchFeaturedMedia: fetchFeaturedMedia, fetchAttachments: fetchAttachments, )) .forEach((p) { if (p.id != null) postsByID[p.id!] = p; }); } } return postsByID.values.toList(); } else { try { WordPressError err = WordPressError.fromJson(json.decode(response.body)); throw err; } catch (e) { throw new WordPressError(message: response.body); } } } ///This recursive function builds the hierarchy of comments for the given post ///and comment. Only parent comments (direct comments to post) need to be ///supplied. CommentHierarchy _commentHierarchyBuilder( List commentList, Comment comment, ) { final childComments = commentList.where((ele) => ele.id != comment.id && ele.parent != 0 && ele.parent == comment.id); if (childComments.length == 0) { return new CommentHierarchy(comment: comment); } else { List children = []; childComments.forEach((c) { children.add(_commentHierarchyBuilder(commentList, c)); }); return new CommentHierarchy( comment: comment, children: children, ); } } /// This returns a list of [Page] based on the filter parameters /// specified through [ParamsPageList] object. By default it returns only /// [ParamsPageList.perPage] number of pages in page [ParamsPageList.pageNum]. /// /// In case of an error, a [WordPressError] object is thrown. Future> fetchPages({required ParamsPageList params}) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_PAGES); url.write(params.toString()); final response = await http.get(Uri.parse(url.toString()), headers: _urlHeader); if (response.statusCode >= 200 && response.statusCode < 300) { List pages = []; final list = json.decode(response.body); list.forEach((page) { pages.add(Page.fromJson(page)); }); return pages; } else { try { WordPressError err = WordPressError.fromJson(json.decode(response.body)); throw err; } catch (e) { throw new WordPressError(message: response.body); } } } /// This returns an object FetchUsersResult based on the filter parameters /// specified through [ParamsUserList] object. By default it returns only /// [ParamsUserList.perPage] number of users in page [ParamsUserList.pageNum]. /// /// In case of an error, a [WordPressError] object is thrown. Future fetchUsers({required ParamsUserList params}) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_USERS); url.write(params.toString()); return _doUsersFetch(url); } /// This returns an object FetchUsersResult as defined by the input, based on the filter parameters /// specified through [ParamsUserList] object. The url it fetches to is defined by the input [String] path. By default it returns only /// [ParamsUserList.perPage] number of users in page [ParamsUserList.pageNum]. /// /// In case of an error, a [WordPressError] object is thrown. Future fetchCustomUsers({ required String path, required ParamsUserList params, }) async { final StringBuffer url = new StringBuffer(_baseUrl + path); url.write(params.toString()); return _doUsersFetch(url); } Future _doUsersFetch(StringBuffer url) async { final response = await http.get( Uri.parse(url.toString()), headers: _urlHeader, ); if (response.statusCode >= 200 && response.statusCode < 300) { List users = []; final list = json.decode(response.body); int totalUsers = int.parse(response.headers['x-wp-total']!); list.forEach((user) { users.add(User.fromJson(user)); }); return FetchUsersResult(users, totalUsers); } else { try { WordPressError err = WordPressError.fromJson(json.decode(response.body)); throw err; } catch (e) { throw new WordPressError(message: response.body); } } } /// This returns a list of [Comment] based on the filter parameters /// specified through [ParamsCommentList] object. By default it returns only /// [ParamsCommentList.perPage] number of comments in page [ParamsCommentList.pageNum]. /// /// In case of an error, a [WordPressError] object is thrown. Future> fetchComments({ required ParamsCommentList params, }) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_COMMENTS); url.write(params.toString()); final response = await http.get( Uri.parse(url.toString()), headers: _urlHeader, ); if (response.statusCode >= 200 && response.statusCode < 300) { List comments = []; final list = json.decode(response.body); list.forEach((comment) { comments.add(Comment.fromJson(comment)); }); return comments; } else { try { WordPressError err = WordPressError.fromJson(json.decode(response.body)); throw err; } catch (e) { throw new WordPressError(message: response.body); } } } /// This returns a list of [CommentHierarchy] based on the filter parameters /// specified through [ParamsCommentList] object. The list returned has all /// parent comments (i.e. comments directed towards posts) with /// [CommentHierarchy.children] containing the replies to that comment. /// /// In case of an error, a [WordPressError] object is thrown. Future> fetchCommentsAsHierarchy({ required ParamsCommentList params, }) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_COMMENTS); url.write(params.toString()); final response = await http.get( Uri.parse(url.toString()), headers: _urlHeader, ); if (response.statusCode >= 200 && response.statusCode < 300) { List comments = []; List commentsHierarchy = []; final list = json.decode(response.body); list.forEach((comment) { comments.add(Comment.fromJson(comment)); }); comments.forEach((comment) { if (comment.parent == 0) commentsHierarchy.add(_commentHierarchyBuilder(comments, comment)); }); return commentsHierarchy; } else { try { WordPressError err = WordPressError.fromJson(json.decode(response.body)); throw err; } catch (e) { throw new WordPressError(message: response.body); } } } /// This returns a list of [Category] based on the filter parameters /// specified through [ParamsCategoryList] object. By default it returns only /// [ParamsCategoryList.perPage] number of categories in page [ParamsCategoryList.pageNum]. /// /// In case of an error, a [WordPressError] object is thrown. Future> fetchCategories({ required ParamsCategoryList params, bool fetchAll = false, }) async { if (fetchAll) { params = params.copyWith(perPage: 100); } final StringBuffer url = new StringBuffer(_baseUrl + URL_CATEGORIES); url.write(params.toString()); final response = await http.get( Uri.parse(url.toString()), headers: _urlHeader, ); if (response.statusCode >= 200 && response.statusCode < 300) { List categories = []; final list = json.decode(response.body); list.forEach((category) { categories.add(Category.fromJson(category)); }); if (fetchAll && response.headers["x-wp-totalpages"] != null) { final totalPages = int.parse(response.headers["x-wp-totalpages"]!); for (int i = params.pageNum + 1; i <= totalPages; ++i) { categories.addAll( await fetchCategories(params: params.copyWith(pageNum: i))); } } return categories; } else { try { WordPressError err = WordPressError.fromJson(json.decode(response.body)); throw err; } catch (e) { throw new WordPressError(message: response.body); } } } /// This returns a list of [Tag] based on the filter parameters /// specified through [ParamsTagList] object. By default it returns only /// [ParamsTagList.perPage] number of tags in page [ParamsTagList.pageNum]. /// /// In case of an error, a [WordPressError] object is thrown. Future> fetchTags({required ParamsTagList params}) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_TAGS); url.write(params.toString()); final response = await http.get( Uri.parse(url.toString()), headers: _urlHeader, ); if (response.statusCode >= 200 && response.statusCode < 300) { List tags = []; final list = json.decode(response.body); list.forEach((tag) { tags.add(Tag.fromJson(tag)); }); return tags; } else { try { WordPressError err = WordPressError.fromJson(json.decode(response.body)); throw err; } catch (e) { throw new WordPressError(message: response.body); } } } /// This returns a list of [Media] based on the filter parameters /// specified through [ParamsMediaList] object. By default it returns only /// [ParamsMediaList.perPage] number of tags in page [ParamsMediaList.pageNum]. /// /// In case of an error, a [WordPressError] object is thrown. Future> fetchMediaList({required ParamsMediaList params}) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_MEDIA); url.write(params.toString()); final response = await http.get( Uri.parse(url.toString()), headers: _urlHeader, ); if (response.statusCode >= 200 && response.statusCode < 300) { List media = []; final list = json.decode(response.body); list.forEach((m) { media.add(Media.fromJson(m)); }); return media; } else { try { WordPressError err = WordPressError.fromJson(json.decode(response.body)); throw err; } catch (e) { throw new WordPressError(message: response.body); } } } /// This is used to create a [Post] in the site. Before this method can be called, /// [User] creating the post needs to be authenticated first by calling /// [WordPress.authenticateUser]. On success, the [Post] object is returned containing /// post information. /// /// In case of an error, a [WordPressError] object is thrown. /// /// Future createPost({required Post post}) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_POSTS); final response = await http.post( Uri.parse(url.toString()), headers: _urlHeader, body: post.toJson(), ); if (response.statusCode >= 200 && response.statusCode < 300) { return Post.fromJson(json.decode(response.body)); } else { try { WordPressError err = WordPressError.fromJson(json.decode(response.body)); throw err; } catch (e) { throw new WordPressError(message: response.body); } } } // yahya - @mymakarim Future uploadMedia(File image) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_MEDIA); var file = image.readAsBytesSync(); final response = await http.post( Uri.parse(url.toString()), headers: { "Content-Type": "image/png", "Content-Disposition": "form-data; filename=firstIg.png", "Authorization": "${_urlHeader['Authorization']}" }, body: file, ); if (response.statusCode >= 200 && response.statusCode < 300) { return json.decode(response.body); } else { try { WordPressError err = WordPressError.fromJson(json.decode(response.body)); throw err; } catch (e) { throw new WordPressError(message: response.body); } } } // uploadMedia function added by: @GarvMaggu Future createUser({required User user}) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_USERS); HttpClient httpClient = new HttpClient(); HttpClientRequest request = await httpClient.postUrl(Uri.parse(url.toString())); request.headers .set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8"); request.headers.set(HttpHeaders.acceptHeader, "application/json"); request.headers.set('Authorization', "${_urlHeader['Authorization']}"); request.add(utf8.encode(json.encode(user.toJson()))); HttpClientResponse response = await request.close(); if (response.statusCode >= 200 && response.statusCode < 300) { return true; } else { response.transform(utf8.decoder).listen((contents) { try { WordPressError err = WordPressError.fromJson(json.decode(contents)); throw err; } catch (e) { throw new WordPressError(message: contents); } }); } return false; } // ===================== // UPDATE START // ===================== Future updatePost({required int id, required Post post}) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_POSTS + '/$id'); HttpClient httpClient = new HttpClient(); HttpClientRequest request = await httpClient.postUrl(Uri.parse(url.toString())); request.headers .set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8"); request.headers.set(HttpHeaders.acceptHeader, "application/json"); request.headers.set('Authorization', "${_urlHeader['Authorization']}"); request.add(utf8.encode(json.encode(post.toJson()))); HttpClientResponse response = await request.close(); if (response.statusCode >= 200 && response.statusCode < 300) { return true; } else { response.transform(utf8.decoder).listen((contents) { try { WordPressError err = WordPressError.fromJson(json.decode(contents)); throw err; } catch (e) { throw new WordPressError(message: contents); } }); } return false; } Future updateComment( {required int id, required Comment comment}) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_COMMENTS + '/$id'); HttpClient httpClient = new HttpClient(); HttpClientRequest request = await httpClient.postUrl(Uri.parse(url.toString())); request.headers .set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8"); request.headers.set(HttpHeaders.acceptHeader, "application/json"); request.headers.set('Authorization', "${_urlHeader['Authorization']}"); request.add(utf8.encode(json.encode(comment.toJson()))); HttpClientResponse response = await request.close(); if (response.statusCode >= 200 && response.statusCode < 300) { return true; } else { response.transform(utf8.decoder).listen((contents) { try { WordPressError err = WordPressError.fromJson(json.decode(contents)); throw err; } catch (e) { throw new WordPressError(message: contents); } }); } return false; } Future updateUser({required int id, required User user}) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_USERS + '/$id'); HttpClient httpClient = new HttpClient(); HttpClientRequest request = await httpClient.postUrl(Uri.parse(url.toString())); request.headers .set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8"); request.headers.set(HttpHeaders.acceptHeader, "application/json"); request.headers.set('Authorization', "${_urlHeader['Authorization']}"); request.add(utf8.encode(json.encode(user.toJson()))); HttpClientResponse response = await request.close(); if (response.statusCode >= 200 && response.statusCode < 300) { return true; } else { response.transform(utf8.decoder).listen((contents) { try { WordPressError err = WordPressError.fromJson(json.decode(contents)); throw err; } catch (e) { throw new WordPressError(message: contents); } }); } return false; } // ===================== // UPDATE END // ===================== // ===================== // DELETE START // ===================== Future deletePost({required int id}) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_POSTS + '/$id'); HttpClient httpClient = new HttpClient(); HttpClientRequest request = await httpClient.deleteUrl(Uri.parse(url.toString())); request.headers .set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8"); request.headers.set(HttpHeaders.acceptHeader, "application/json"); request.headers.set('Authorization', "${_urlHeader['Authorization']}"); HttpClientResponse response = await request.close(); if (response.statusCode >= 200 && response.statusCode < 300) { return true; } else { response.transform(utf8.decoder).listen((contents) { try { WordPressError err = WordPressError.fromJson(json.decode(contents)); throw err; } catch (e) { throw new WordPressError(message: contents); } }); } return false; } Future deleteComment({required int id}) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_COMMENTS + '/$id'); HttpClient httpClient = new HttpClient(); HttpClientRequest request = await httpClient.deleteUrl(Uri.parse(url.toString())); request.headers .set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8"); request.headers.set(HttpHeaders.acceptHeader, "application/json"); request.headers.set('Authorization', "${_urlHeader['Authorization']}"); HttpClientResponse response = await request.close(); if (response.statusCode >= 200 && response.statusCode < 300) { return true; } else { response.transform(utf8.decoder).listen((contents) { try { WordPressError err = WordPressError.fromJson(json.decode(contents)); throw err; } catch (e) { throw new WordPressError(message: contents); } }); } return false; } Future deleteUser({ required int id, required int reassign, }) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_USERS + '/$id'); HttpClient httpClient = new HttpClient(); HttpClientRequest request = await httpClient.deleteUrl(Uri.parse(url.toString())); request.headers .set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8"); request.headers.set(HttpHeaders.acceptHeader, "application/json"); request.headers.set('Authorization', "${_urlHeader['Authorization']}"); request .add(utf8.encode(json.encode({"reassign": reassign, "force": true}))); HttpClientResponse response = await request.close(); if (response.statusCode >= 200 && response.statusCode < 300) { return true; } else { response.transform(utf8.decoder).listen((contents) { try { WordPressError err = WordPressError.fromJson(json.decode(contents)); throw err; } catch (e) { throw new WordPressError(message: contents); } }); } return false; } // ===================== // UPDATE END // ===================== // end yahya - @mymakarim /// This is used to create a [Comment] for a [Post]. Before this method can be called, /// [User] writing the comment needs to be authenticated first by calling /// [WordPress.authenticateUser]. On success, the [Comment] object is returned containing /// comment information. /// /// In case of an error, a [WordPressError] object is thrown. Future createComment({required Comment comment}) async { final StringBuffer url = new StringBuffer(_baseUrl + URL_COMMENTS); final response = await http.post( Uri.parse(url.toString()), headers: _urlHeader, body: comment.toJson(), ); if (response.statusCode >= 200 && response.statusCode < 300) { return Comment.fromJson(json.decode(response.body)); } else { try { WordPressError err = WordPressError.fromJson(json.decode(response.body)); throw err; } catch (e) { throw new WordPressError(message: response.body); } } } } ================================================ FILE: lib/requests/params_category_list.dart ================================================ import 'package:flutter_wordpress/constants.dart'; /// This class holds all arguments which can be used to filter Categories when using /// [WordPress.fetchCategories] method. /// /// [List Categories' Arguments](https://developer.wordpress.org/rest-api/reference/categories/#list-categories) class ParamsCategoryList { final WordPressContext context; final int pageNum; final int perPage; final String searchQuery; final List excludeCategoryIDs; final List includeCategoryIDs; final Order order; final CategoryTagOrderBy orderBy; final bool hideEmpty; final int? parent; final int? post; final String slug; ParamsCategoryList({ this.context = WordPressContext.view, this.pageNum = 1, this.perPage = 10, this.searchQuery = '', this.excludeCategoryIDs = const [], this.includeCategoryIDs = const [], this.order = Order.asc, this.orderBy = CategoryTagOrderBy.name, this.hideEmpty = false, this.parent, this.post, this.slug = '', }); Map toMap() { return { 'context': '${enumStringToName(this.context.toString())}', 'page': '${this.pageNum}', 'per_page': '${this.perPage}', 'search': '${this.searchQuery}', 'exclude': '${listToUrlString(this.excludeCategoryIDs)}', 'include': '${listToUrlString(this.includeCategoryIDs)}', 'order': '${enumStringToName(this.order.toString())}', 'orderby': '${enumStringToName(this.orderBy.toString())}', 'hide_empty': '${this.hideEmpty}', 'parent': '${this.parent == null ? '' : this.parent}', 'post': '${this.post == null ? '' : this.post}', 'slug': '${this.slug}', }; } ParamsCategoryList copyWith({ int? pageNum, int? perPage }) { return ParamsCategoryList( context: context, order: order, orderBy: orderBy, pageNum: pageNum ?? this.pageNum, perPage: perPage ?? this.perPage, searchQuery: searchQuery, slug: slug, excludeCategoryIDs: excludeCategoryIDs, hideEmpty: hideEmpty, includeCategoryIDs: includeCategoryIDs, parent: parent, post: post ); } @override String toString() { return constructUrlParams(toMap()); } } ================================================ FILE: lib/requests/params_comment_list.dart ================================================ import 'package:flutter_wordpress/constants.dart'; /// This class holds all arguments which can be used to filter comments when using /// [WordPress.fetchComments] method. /// /// [List Comments' Arguments](https://developer.wordpress.org/rest-api/reference/comments/#list-comments) class ParamsCommentList { final WordPressContext context; final int pageNum; final int perPage; final String searchQuery; final String afterDate; final List includeAuthorIDs; final List excludeAuthorIDs; final String authorEmail; final String beforeDate; final List excludeCommentIDs; final List includeCommentIDs; final int? offset; final Order order; final CommentOrderBy orderBy; final List includeParentIDs; final List excludeParentIDs; final List includePostIDs; final CommentStatus commentStatus; final CommentType commentType; final String postPassword; ParamsCommentList({ this.context = WordPressContext.view, this.pageNum = 1, this.perPage = 10, this.searchQuery = '', this.afterDate = '', this.includeAuthorIDs = const [], this.excludeAuthorIDs = const [], this.authorEmail = '', this.beforeDate = '', this.excludeCommentIDs = const [], this.includeCommentIDs = const [], this.offset, this.order = Order.desc, this.orderBy = CommentOrderBy.date_gmt, this.includeParentIDs = const [], this.excludeParentIDs = const [], this.includePostIDs = const [], this.commentStatus = CommentStatus.approve, this.commentType = CommentType.comment, this.postPassword = '', }); Map toMap() { return { 'context': '${enumStringToName(this.context.toString())}', 'page': '${this.pageNum}', 'per_page': '${this.perPage}', 'search': '${this.searchQuery}', 'after': '${this.afterDate}', 'author': '${listToUrlString(this.includeAuthorIDs)}', 'author_exclude': '${listToUrlString(this.excludeAuthorIDs)}', 'author_email': '${this.authorEmail}', 'before': '${this.beforeDate}', 'exclude': '${listToUrlString(excludeCommentIDs)}', 'include': '${listToUrlString(includeCommentIDs)}', 'offset': '${this.offset == null ? '' : this.offset}', 'order': '${enumStringToName(this.order.toString())}', 'orderby': '${enumStringToName(this.orderBy.toString())}', 'parent': '${listToUrlString(this.includeParentIDs)}', 'parent_exclude': '${listToUrlString(this.excludeParentIDs)}', 'post': '${listToUrlString(this.includePostIDs)}', 'status': '${enumStringToName(this.commentStatus.toString())}', 'type': '${enumStringToName(this.commentType.toString())}', 'password': '${this.postPassword}', }; } @override String toString() { return constructUrlParams(toMap()); } } ================================================ FILE: lib/requests/params_media_list.dart ================================================ import 'package:flutter_wordpress/constants.dart'; /// This class holds all arguments which can be used to filter media when using /// [WordPress.fetchMediaList] method. /// /// [List Media Arguments](https://developer.wordpress.org/rest-api/reference/media/#list-media) class ParamsMediaList { final WordPressContext context; final int pageNum; final int perPage; final String searchQuery; final String afterDate; final List includeAuthorIDs; final List excludeAuthorIDs; final String beforeDate; final List excludeMediaIDs; final List includeMediaIDs; final int? offset; final Order order; final MediaOrderBy orderBy; final List includeParentIDs; final List excludeParentIDs; final String slug; final MediaStatus mediaStatus; final MediaType? mediaType; final String mimeType; ParamsMediaList({ this.context = WordPressContext.view, this.pageNum = 1, this.perPage = 10, this.searchQuery = '', this.afterDate = '', this.includeAuthorIDs = const [], this.excludeAuthorIDs = const [], this.beforeDate = '', this.excludeMediaIDs = const [], this.includeMediaIDs = const [], this.offset, this.order = Order.desc, this.orderBy = MediaOrderBy.date, this.excludeParentIDs = const [], this.includeParentIDs = const [], this.slug = '', this.mediaStatus = MediaStatus.inherit, this.mediaType, this.mimeType = '', }); Map toMap() { return { 'context': '${enumStringToName(this.context.toString())}', 'page': '${this.pageNum}', 'per_page': '${this.perPage}', 'search': '${this.searchQuery}', 'after': '${this.afterDate}', 'author': '${listToUrlString(this.includeAuthorIDs)}', 'author_exclude': '${listToUrlString(this.excludeAuthorIDs)}', 'before': '${this.beforeDate}', 'exclude': '${listToUrlString(excludeMediaIDs)}', 'include': '${listToUrlString(includeMediaIDs)}', 'offset': '${this.offset == null ? '' : this.offset}', 'order': '${enumStringToName(this.order.toString())}', 'orderby': '${enumStringToName(this.orderBy.toString())}', 'parent': '${listToUrlString(includeParentIDs)}', 'parent_exclude': '${listToUrlString(excludeParentIDs)}', 'slug': '${this.slug}', 'status': '${enumStringToName(this.mediaStatus.toString())}', 'media_type': '${this.mediaType == null ? '' : enumStringToName(this.mediaType.toString())}', 'mime_type': '${this.mimeType}', }; } @override String toString() { return constructUrlParams(toMap()); } } ================================================ FILE: lib/requests/params_page_list.dart ================================================ import 'package:flutter_wordpress/constants.dart'; /// This class holds all arguments which can be used to filter pages when using /// [WordPress.fetchPages] method. /// /// [List Pages' Arguments](https://developer.wordpress.org/rest-api/reference/pages/#list-pages) class ParamsPageList { final WordPressContext context; final int pageNum; final int perPage; final String searchQuery; final String afterDate; final List includeAuthorIDs; final List excludeAuthorIDs; final String beforeDate; final List excludePageIDs; final List includePageIDs; final int? menuOrder; final int? offset; final Order order; final PageOrderBy orderBy; final List includeParentIDs; final List excludeParentIDs; final String slug; final PostPageStatus pageStatus; ParamsPageList({ this.context = WordPressContext.view, this.pageNum = 1, this.perPage = 10, this.searchQuery = '', this.afterDate = '', this.includeAuthorIDs = const [], this.excludeAuthorIDs = const [], this.beforeDate = '', this.excludePageIDs = const [], this.includePageIDs = const [], this.menuOrder, this.offset, this.order = Order.desc, this.orderBy = PageOrderBy.date, this.includeParentIDs = const [], this.excludeParentIDs = const [], this.slug = '', this.pageStatus = PostPageStatus.publish, }); Map toMap() { return { 'context': '${enumStringToName(this.context.toString())}', 'page': '${this.pageNum}', 'per_page': '${this.perPage}', 'search': '${this.searchQuery}', 'after': '${this.afterDate}', 'author': '${listToUrlString(this.includeAuthorIDs)}', 'author_exclude': '${listToUrlString(this.excludeAuthorIDs)}', 'before': '${this.beforeDate}', 'exclude': '${listToUrlString(excludePageIDs)}', 'include': '${listToUrlString(includePageIDs)}', 'menu_order': '${this.menuOrder == null ? '' : this.menuOrder}', 'offset': '${this.offset == null ? '' : this.offset}', 'order': '${enumStringToName(this.order.toString())}', 'orderby': '${enumStringToName(this.orderBy.toString())}', 'parent': '${listToUrlString(includeParentIDs)}', 'parent_exclude': '${listToUrlString(excludeParentIDs)}', 'slug': '${this.slug}', 'status': '${enumStringToName(this.pageStatus.toString())}', }; } @override String toString() { return constructUrlParams(toMap()); } } ================================================ FILE: lib/requests/params_post_list.dart ================================================ import 'package:flutter_wordpress/constants.dart'; /// This class holds all arguments which can be used to filter posts when using /// [WordPress.fetchPosts] method. /// /// [List Posts' Arguments](https://developer.wordpress.org/rest-api/reference/posts/#list-posts) class ParamsPostList { final WordPressContext context; final int pageNum; final int perPage; final String searchQuery; final String afterDate; final String beforeDate; final List includeAuthorIDs; final List excludeAuthorIDs; final List includePostIDs; final List excludePostIDs; final int? offset; final Order order; final PostOrderBy orderBy; final String slug; final PostPageStatus postStatus; final List includeCategories; final List excludeCategories; final List includeTags; final List excludeTags; final bool? sticky; ParamsPostList({ this.context = WordPressContext.view, this.pageNum = 1, this.perPage = 10, this.searchQuery = '', this.afterDate = '', this.beforeDate = '', this.includeAuthorIDs = const [], this.excludeAuthorIDs = const [], this.includePostIDs = const [], this.excludePostIDs = const [], this.offset, this.order = Order.desc, this.orderBy = PostOrderBy.date, this.slug = '', this.postStatus = PostPageStatus.publish, this.includeCategories = const [], this.excludeCategories = const [], this.includeTags = const [], this.excludeTags = const [], this.sticky, }); Map toMap() { return { 'context': '${enumStringToName(this.context.toString())}', 'page': '${this.pageNum}', 'per_page': '${this.perPage}', 'search': '${this.searchQuery}', 'after': '${this.afterDate}', 'before': '${this.beforeDate}', 'author': '${listToUrlString(this.includeAuthorIDs)}', 'author_exclude': '${listToUrlString(this.excludeAuthorIDs)}', 'include': '${listToUrlString(includePostIDs)}', 'exclude': '${listToUrlString(excludePostIDs)}', 'offset': '${this.offset == null ? '' : this.offset}', 'order': '${enumStringToName(this.order.toString())}', 'orderby': '${enumStringToName(this.orderBy.toString())}', 'slug': '${this.slug}', 'status': '${enumStringToName(this.postStatus.toString())}', 'categories': '${listToUrlString(includeCategories)}', 'categories_exclude': '${listToUrlString(excludeCategories)}', 'tags': '${listToUrlString(includeTags)}', 'tags_exclude': '${listToUrlString(excludeTags)}', 'sticky': '${this.sticky == null ? '' : this.sticky}', }; } ParamsPostList copyWith({ int? pageNum, int? perPage, }) { return ParamsPostList( afterDate: afterDate, beforeDate: beforeDate, context: context, excludeAuthorIDs: excludeAuthorIDs, excludeCategories: excludeCategories, excludePostIDs: excludePostIDs, excludeTags: excludeTags, includeAuthorIDs: includeAuthorIDs, includeCategories: includeCategories, includePostIDs: includePostIDs, includeTags: includeTags, offset: offset, order: order, orderBy: orderBy, pageNum: pageNum ?? this.pageNum, perPage: perPage ?? this.perPage, postStatus: postStatus, searchQuery: searchQuery, slug: slug, sticky: sticky ); } @override String toString() { return constructUrlParams(toMap()); } } ================================================ FILE: lib/requests/params_tag_list.dart ================================================ import 'package:flutter_wordpress/constants.dart'; /// This class holds all arguments which can be used to filter Tags when using /// [WordPress.fetchTags] method. /// /// [List Tags' Arguments](https://developer.wordpress.org/rest-api/reference/tags/#list-tags) class ParamsTagList { final WordPressContext context; final int pageNum; final int perPage; final String searchQuery; final List excludeTagIDs; final List includeTagIDs; final Order order; final CategoryTagOrderBy orderBy; final bool? hideEmpty; final int? post; final String slug; ParamsTagList({ this.context = WordPressContext.view, this.pageNum = 1, this.perPage = 10, this.searchQuery = '', this.excludeTagIDs = const [], this.includeTagIDs = const [], this.order = Order.asc, this.orderBy = CategoryTagOrderBy.name, this.hideEmpty, this.post, this.slug = '', }); Map toMap() { return { 'context': '${enumStringToName(this.context.toString())}', 'page': '${this.pageNum}', 'per_page': '${this.perPage}', 'search': '${this.searchQuery}', 'exclude': '${listToUrlString(this.excludeTagIDs)}', 'include': '${listToUrlString(this.includeTagIDs)}', 'order': '${enumStringToName(this.order.toString())}', 'orderby': '${enumStringToName(this.orderBy.toString())}', 'hide_empty': '${this.hideEmpty == null ? '' : this.hideEmpty}', 'post': '${this.post == null ? '' : this.post}', 'slug': '${this.slug}', }; } @override String toString() { return constructUrlParams(toMap()); } } ================================================ FILE: lib/requests/params_user_list.dart ================================================ import 'package:flutter_wordpress/constants.dart'; /// This class holds all arguments which can be used to filter users when using /// [WordPress.fetchUsers] method. /// /// [List Users' Arguments](https://developer.wordpress.org/rest-api/reference/users/#list-users) class ParamsUserList { final WordPressContext context; final int pageNum; final int perPage; final String searchQuery; final List includeUserIDs; final List excludeUserIDs; final int? offset; final Order order; final UserOrderBy orderBy; final String slug; final List roles; ParamsUserList({ this.context = WordPressContext.view, this.pageNum = 1, this.perPage = 10, this.searchQuery = '', this.includeUserIDs = const [], this.excludeUserIDs = const [], this.offset, this.order = Order.asc, this.orderBy = UserOrderBy.name, this.slug = '', this.roles = const [], }); Map toMap() { return { 'context': '${enumStringToName(this.context.toString())}', 'page': '${this.pageNum}', 'per_page': '${this.perPage}', 'search': '${this.searchQuery}', 'include': '${listToUrlString(this.includeUserIDs)}', 'exclude': '${listToUrlString(this.excludeUserIDs)}', 'offset': '${this.offset == null ? '' : this.offset}', 'order': '${enumStringToName(this.order.toString())}', 'orderby': '${enumStringToName(this.orderBy.toString())}', 'slug': '${this.slug}', 'roles': '${listToUrlString(this.roles)}', }; } @override String toString() { return constructUrlParams(toMap()); } } ================================================ FILE: lib/schemas/avatar_urls.dart ================================================ class AvatarUrls { String? s24; String? s48; String? s96; AvatarUrls({ this.s24, this.s48, this.s96, }); AvatarUrls.fromJson(Map json) { s24 = json['24']; s48 = json['48']; s96 = json['96']; } Map toJson() { final Map data = new Map(); data['24'] = this.s24; data['48'] = this.s48; data['96'] = this.s96; return data; } } ================================================ FILE: lib/schemas/capabilities.dart ================================================ class Capabilities { String? manageTerms; String? editTerms; String? deleteTerms; String? assignTerms; String? editPost; String? readPost; String? deletePost; String? editPosts; String? editOthersPosts; String? publishPosts; String? readPrivatePosts; String? read; String? deletePosts; String? deletePrivatePosts; String? deletePublishedPosts; String? deleteOthersPosts; String? editPrivatePosts; String? editPublishedPosts; String? createPosts; Capabilities({ this.manageTerms, this.editTerms, this.deleteTerms, this.assignTerms, this.editPost, this.readPost, this.deletePost, this.editPosts, this.editOthersPosts, this.publishPosts, this.readPrivatePosts, this.read, this.deletePosts, this.deletePrivatePosts, this.deletePublishedPosts, this.deleteOthersPosts, this.editPrivatePosts, this.editPublishedPosts, this.createPosts, }); Capabilities.fromJson(Map json) { manageTerms = json['manage_terms']; editTerms = json['edit_terms']; deleteTerms = json['delete_terms']; assignTerms = json['assign_terms']; editPost = json['edit_post']; readPost = json['read_post']; deletePost = json['delete_post']; editPosts = json['edit_posts']; editOthersPosts = json['edit_others_posts']; publishPosts = json['publish_posts']; readPrivatePosts = json['read_private_posts']; read = json['read']; deletePosts = json['delete_posts']; deletePrivatePosts = json['delete_private_posts']; deletePublishedPosts = json['delete_published_posts']; deleteOthersPosts = json['delete_others_posts']; editPrivatePosts = json['edit_private_posts']; editPublishedPosts = json['edit_published_posts']; createPosts = json['create_posts']; } Map toJson() { final Map data = new Map(); data['manage_terms'] = this.manageTerms; data['edit_terms'] = this.editTerms; data['delete_terms'] = this.deleteTerms; data['assign_terms'] = this.assignTerms; data['edit_post'] = this.editPost; data['read_post'] = this.readPost; data['delete_post'] = this.deletePost; data['edit_posts'] = this.editPosts; data['edit_others_posts'] = this.editOthersPosts; data['publish_posts'] = this.publishPosts; data['read_private_posts'] = this.readPrivatePosts; data['read'] = this.read; data['delete_posts'] = this.deletePosts; data['delete_private_posts'] = this.deletePrivatePosts; data['delete_published_posts'] = this.deletePublishedPosts; data['delete_others_posts'] = this.deleteOthersPosts; data['edit_private_posts'] = this.editPrivatePosts; data['edit_published_posts'] = this.editPublishedPosts; data['create_posts'] = this.createPosts; return data; } } ================================================ FILE: lib/schemas/category.dart ================================================ import 'links.dart'; class Category { int? id; int? count; String? description; String? link; String? name; String? slug; String? taxonomy; int? parent; Links? lLinks; Category({ this.id, this.count, this.description, this.link, this.name, this.slug, this.taxonomy, this.parent, this.lLinks, }); Category.fromJson(Map json) { id = json['id']; count = json['count']; description = json['description']; link = json['link']; name = json['name']; slug = json['slug']; taxonomy = json['taxonomy']; parent = json['parent']; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['id'] = this.id; data['count'] = this.count; data['description'] = this.description; data['link'] = this.link; data['name'] = this.name; data['slug'] = this.slug; data['taxonomy'] = this.taxonomy; data['parent'] = this.parent; data['_links'] = this.lLinks?.toJson(); return data; } } ================================================ FILE: lib/schemas/comment.dart ================================================ import 'package:flutter_wordpress/constants.dart'; import 'avatar_urls.dart'; import 'content.dart'; import 'links.dart'; /// A [WordPress Comment](https://developer.wordpress.org/rest-api/reference/comments/) /// /// Refer the above link to see which arguments are set based on different /// context modes ([WordPressContext]). class Comment { /// ID of the comment. int? id; /// ID of the post on which to comment. int? post; /// ID of the parent comment in case of reply. /// This should be 0 in case of a new comment. int? parent; /// ID of the author who is going to comment. int? author; String? authorName; String? authorEmail; String? authorUrl; String? authorIp; String? authorUserAgent; /// The date the comment was written, in the site's timezone. String? date; /// The date the comment was written, in GMT. String? dateGmt; /// Content of the comment. Content? content; String? link; /// This can only be set by an editor/administrator. CommentStatus? status; /// This can only be set by an editor/administrator. CommentType? type; AvatarUrls? authorAvatarUrls; Links? lLinks; Comment({ required this.author, required this.post, required String content, this.authorEmail, this.authorIp, this.authorName, this.authorUrl, this.authorUserAgent, this.date, this.dateGmt, this.parent = 0, this.status, }) : content = new Content(rendered: content); Comment.fromJson(Map json) { id = json['id']; post = json['post']; parent = json['parent']; author = json['author']; authorName = json['author_name']; authorEmail = json['author_email']; authorUrl = json['author_url']; authorIp = json['author_ip']; authorUserAgent = json['author_user_agent']; date = json['date']; dateGmt = json['date_gmt']; content = (json['content'] != null ? new Content.fromJson(json['content']!) : null)!; link = json['link']; if (json['status'] != null) { CommentStatus.values.forEach((val) { if (enumStringToName(val.toString()) == json['status']) { status = val; return; } }); } if (json['type'] != null) { CommentType.values.forEach((val) { if (enumStringToName(val.toString()) == json['type']) { type = val; return; } }); } authorAvatarUrls = json['author_avatar_urls'] != null ? new AvatarUrls.fromJson(json['author_avatar_urls']) : null; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['post'] = this.post; data['parent'] = this.parent; data['author'] = this.author; data['author_name'] = this.authorName; data['author_email'] = this.authorEmail; data['author_url'] = this.authorUrl; data['author_ip'] = this.authorIp; data['author_user_agent'] = this.authorUserAgent; data['date'] = this.date; data['date_gmt'] = this.dateGmt; data['content'] = this.content?.toJson(); data['status'] = enumStringToName(this.status.toString()); return data; } @override String toString() { return 'Comment: {id: $id, author: $authorName, post: $post, parent: $parent}'; } } ================================================ FILE: lib/schemas/comment_hierarchy.dart ================================================ import 'comment.dart'; /// This class is used to store comments as a hierarchy. class CommentHierarchy { /// Parent comment. final Comment comment; /// Replies to the parent comment. final List? children; CommentHierarchy({ required this.comment, this.children, }); @override String toString() { return '$comment, children: [$children]'; } } ================================================ FILE: lib/schemas/content.dart ================================================ class Content { String? raw; String? rendered; bool? protected; int? blockVersion; Content({this.rendered}); Content.fromJson(Map json) { raw = json['raw']; rendered = json['rendered']; protected = json['protected']; blockVersion = json['block_version']; } Map toJson() { final Map data = new Map(); data['raw'] = this.raw; data['rendered'] = this.rendered; data['protected'] = this.protected; data['block_version'] = this.blockVersion; return data; } } ================================================ FILE: lib/schemas/excerpt.dart ================================================ class Excerpt { String? raw; String? rendered; bool? protected; Excerpt({this.rendered}); Excerpt.fromJson(Map json) { raw = json['raw']; rendered = json['rendered']; protected = json['protected']; } Map toJson() { final Map data = new Map(); data['raw'] = this.raw; data['rendered'] = this.rendered; data['protected'] = this.protected; return data; } } ================================================ FILE: lib/schemas/fetch_user_result.dart ================================================ import 'user.dart'; class FetchUsersResult { List users = const []; int? totalUsers; FetchUsersResult(List users, int totalUsers) { this.users = users; this.totalUsers = totalUsers; } } ================================================ FILE: lib/schemas/guid.dart ================================================ class Guid { String? rendered; String? raw; Guid.fromJson(Map json) { rendered = json['rendered']; raw = json['raw']; } Map toJson() { final Map data = new Map(); data['rendered'] = this.rendered; data['raw'] = this.raw; return data; } } ================================================ FILE: lib/schemas/jwt_response.dart ================================================ class JWTResponse { String? token; String? userEmail; String? userNicename; String? userDisplayName; JWTResponse({ this.token, this.userEmail, this.userNicename, this.userDisplayName, }); JWTResponse.fromJson(Map json) { token = json['token']; userEmail = json['user_email']; userNicename = json['user_nicename']; userDisplayName = json['user_display_name']; } Map toJson() { final Map data = new Map(); data['token'] = this.token; data['user_email'] = this.userEmail; data['user_nicename'] = this.userNicename; data['user_display_name'] = this.userDisplayName; return data; } } ================================================ FILE: lib/schemas/labels.dart ================================================ class Labels { String? name; String? singularName; String? searchItems; String? popularItems; String? allItems; String? parentItem; String? parentItemColon; String? addNew; String? addNewItem; String? editItem; String? newItem; String? viewItem; String? viewItems; String? notFound; String? notFoundInTrash; String? archives; String? attributes; String? insertIntoItem; String? uploadedToThisItem; String? featuredImage; String? setFeaturedImage; String? removeFeaturedImage; String? useFeaturedImage; String? filterItemsList; String? itemsListNavigation; String? itemsList; String? itemPublished; String? itemPublishedPrivately; String? itemRevertedToDraft; String? itemScheduled; String? itemUpdated; String? menuName; String? nameAdminBar; String? updateItem; String? newItemName; String? separateItemsWithCommas; String? addOrRemoveItems; String? chooseFromMostUsed; String? noTerms; String? mostUsed; String? backToItems; Labels({ this.name, this.singularName, this.searchItems, this.popularItems, this.allItems, this.parentItem, this.parentItemColon, this.addNew, this.addNewItem, this.editItem, this.newItem, this.viewItem, this.viewItems, this.notFound, this.notFoundInTrash, this.archives, this.attributes, this.insertIntoItem, this.uploadedToThisItem, this.featuredImage, this.setFeaturedImage, this.removeFeaturedImage, this.useFeaturedImage, this.filterItemsList, this.itemsListNavigation, this.itemsList, this.itemPublished, this.itemPublishedPrivately, this.itemRevertedToDraft, this.itemScheduled, this.itemUpdated, this.menuName, this.nameAdminBar, this.updateItem, this.newItemName, this.separateItemsWithCommas, this.addOrRemoveItems, this.chooseFromMostUsed, this.noTerms, this.mostUsed, this.backToItems, }); Labels.fromJson(Map json) { name = json['name']; singularName = json['singular_name']; searchItems = json['search_items']; popularItems = json['popular_items']; allItems = json['all_items']; parentItem = json['parent_item']; parentItemColon = json['parent_item_colon']; addNew = json['add_new']; addNewItem = json['add_new_item']; editItem = json['edit_item']; newItem = json['new_item']; viewItem = json['view_item']; viewItems = json['view_items']; notFound = json['not_found']; notFoundInTrash = json['not_found_in_trash']; archives = json['archives']; attributes = json['attributes']; insertIntoItem = json['insert_into_item']; uploadedToThisItem = json['uploaded_to_this_item']; featuredImage = json['featured_image']; setFeaturedImage = json['set_featured_image']; removeFeaturedImage = json['remove_featured_image']; useFeaturedImage = json['use_featured_image']; filterItemsList = json['filter_items_list']; itemsListNavigation = json['items_list_navigation']; itemsList = json['items_list']; itemPublished = json['item_published']; itemPublishedPrivately = json['item_published_privately']; itemRevertedToDraft = json['item_reverted_to_draft']; itemScheduled = json['item_scheduled']; itemUpdated = json['item_updated']; menuName = json['menu_name']; nameAdminBar = json['name_admin_bar']; updateItem = json['update_item']; newItemName = json['new_item_name']; separateItemsWithCommas = json['separate_items_with_commas']; addOrRemoveItems = json['add_or_remove_items']; chooseFromMostUsed = json['choose_from_most_used']; noTerms = json['no_terms']; mostUsed = json['most_used']; backToItems = json['back_to_items']; } Map toJson() { final Map data = new Map(); data['name'] = this.name; data['singular_name'] = this.singularName; data['search_items'] = this.searchItems; data['popular_items'] = this.popularItems; data['all_items'] = this.allItems; data['parent_item'] = this.parentItem; data['parent_item_colon'] = this.parentItemColon; data['add_new'] = this.addNew; data['add_new_item'] = this.addNewItem; data['edit_item'] = this.editItem; data['new_item'] = this.newItem; data['view_item'] = this.viewItem; data['view_items'] = this.viewItems; data['not_found'] = this.notFound; data['not_found_in_trash'] = this.notFoundInTrash; data['archives'] = this.archives; data['attributes'] = this.attributes; data['insert_into_item'] = this.insertIntoItem; data['uploaded_to_this_item'] = this.uploadedToThisItem; data['featured_image'] = this.featuredImage; data['set_featured_image'] = this.setFeaturedImage; data['remove_featured_image'] = this.removeFeaturedImage; data['use_featured_image'] = this.useFeaturedImage; data['filter_items_list'] = this.filterItemsList; data['items_list_navigation'] = this.itemsListNavigation; data['items_list'] = this.itemsList; data['item_published'] = this.itemPublished; data['item_published_privately'] = this.itemPublishedPrivately; data['item_reverted_to_draft'] = this.itemRevertedToDraft; data['item_scheduled'] = this.itemScheduled; data['item_updated'] = this.itemUpdated; data['menu_name'] = this.menuName; data['name_admin_bar'] = this.nameAdminBar; data['update_item'] = this.updateItem; data['new_item_name'] = this.newItemName; data['separate_items_with_commas'] = this.separateItemsWithCommas; data['add_or_remove_items'] = this.addOrRemoveItems; data['choose_from_most_used'] = this.chooseFromMostUsed; data['no_terms'] = this.noTerms; data['most_used'] = this.mostUsed; data['back_to_items'] = this.backToItems; return data; } } ================================================ FILE: lib/schemas/links.dart ================================================ class Links { List? self; List? collection; List? about; List? author; List? replies; List? archives; List? versionHistory; List? wpPostType; List? predecessorVersion; List? wpFeaturedmedia; List? wpAttachment; List? wpTerm; List? wpActionPublish; List? wpActionUnfilteredHtml; List? wpActionSticky; List? wpActionAssignAuthor; List? wpActionCreateCategories; List? wpActionAssignCategories; List? wpActionCreateTags; List? wpActionAssignTags; List? wpItems; List? up; List? inReplyTo; List? children; List? curies; Links.fromJson(Map json) { if (json['self'] != null) { self = []; json['self'].forEach((v) { self?.add(new Self.fromJson(v)); }); } if (json['collection'] != null) { collection = []; json['collection'].forEach((v) { collection?.add(new Collection.fromJson(v)); }); } if (json['about'] != null) { about = []; json['about'].forEach((v) { about?.add(new About.fromJson(v)); }); } if (json['author'] != null) { author = []; json['author'].forEach((v) { author?.add(new Author.fromJson(v)); }); } if (json['replies'] != null) { replies = []; json['replies'].forEach((v) { replies?.add(new Replies.fromJson(v)); }); } if (json['archives'] != null) { archives = []; json['archives'].forEach((v) { archives?.add(new Archives.fromJson(v)); }); } if (json['version-history'] != null) { versionHistory = []; json['version-history'].forEach((v) { versionHistory?.add(new VersionHistory.fromJson(v)); }); } if (json['wp:post_type'] != null) { wpPostType = []; json['wp:post_type'].forEach((v) { wpPostType?.add(new WpPostType.fromJson(v)); }); } if (json['predecessor-version'] != null) { predecessorVersion = []; json['predecessor-version'].forEach((v) { predecessorVersion?.add(new PredecessorVersion.fromJson(v)); }); } if (json['wp:featuredmedia'] != null) { wpFeaturedmedia = []; json['wp:featuredmedia'].forEach((v) { wpFeaturedmedia?.add(new WpFeaturedmedia.fromJson(v)); }); } if (json['wp:attachment'] != null) { wpAttachment = []; json['wp:attachment'].forEach((v) { wpAttachment?.add(new WpAttachment.fromJson(v)); }); } if (json['wp:term'] != null) { wpTerm = []; json['wp:term'].forEach((v) { wpTerm?.add(new WpTerm.fromJson(v)); }); } if (json['wp:action-publish'] != null) { wpActionPublish = []; json['wp:action-publish'].forEach((v) { wpActionPublish?.add(new WpActionPublish.fromJson(v)); }); } if (json['wp:action-unfiltered-html'] != null) { wpActionUnfilteredHtml = []; json['wp:action-unfiltered-html'].forEach((v) { wpActionUnfilteredHtml?.add(new WpActionUnfilteredHtml.fromJson(v)); }); } if (json['wp:action-sticky'] != null) { wpActionSticky = []; json['wp:action-sticky'].forEach((v) { wpActionSticky?.add(new WpActionSticky.fromJson(v)); }); } if (json['wp:action-assign-author'] != null) { wpActionAssignAuthor = []; json['wp:action-assign-author'].forEach((v) { wpActionAssignAuthor?.add(new WpActionAssignAuthor.fromJson(v)); }); } if (json['wp:action-create-categories'] != null) { wpActionCreateCategories = []; json['wp:action-create-categories'].forEach((v) { wpActionCreateCategories?.add(new WpActionCreateCategories.fromJson(v)); }); } if (json['wp:action-assign-categories'] != null) { wpActionAssignCategories = []; json['wp:action-assign-categories'].forEach((v) { wpActionAssignCategories?.add(new WpActionAssignCategories.fromJson(v)); }); } if (json['wp:action-create-tags'] != null) { wpActionCreateTags = []; json['wp:action-create-tags'].forEach((v) { wpActionCreateTags?.add(new WpActionCreateTags.fromJson(v)); }); } if (json['wp:action-assign-tags'] != null) { wpActionAssignTags = []; json['wp:action-assign-tags'].forEach((v) { wpActionAssignTags?.add(new WpActionAssignTags.fromJson(v)); }); } if (json['wp:items'] != null) { wpItems = []; json['wp:items'].forEach((v) { wpItems?.add(new WpItems.fromJson(v)); }); } if (json['up'] != null) { up = []; json['up'].forEach((v) { up?.add(new Up.fromJson(v)); }); } if (json['in-reply-to'] != null) { inReplyTo = []; json['in-reply-to'].forEach((v) { inReplyTo?.add(new InReplyTo.fromJson(v)); }); } if (json['children'] != null) { children = []; json['children'].forEach((v) { children?.add(new Children.fromJson(v)); }); } if (json['curies'] != null) { curies = []; json['curies'].forEach((v) { curies?.add(new Curies.fromJson(v)); }); } } Map toJson() { final Map data = new Map(); data['self'] = this.self?.map((v) => v.toJson()).toList(); data['collection'] = this.collection?.map((v) => v.toJson()).toList(); data['about'] = this.about?.map((v) => v.toJson()).toList(); data['author'] = this.author?.map((v) => v.toJson()).toList(); data['replies'] = this.replies?.map((v) => v.toJson()).toList(); data['archives'] = this.archives?.map((v) => v.toJson()).toList(); data['version-history'] = this.versionHistory?.map((v) => v.toJson()).toList(); data['wp:post_type'] = this.wpPostType?.map((v) => v.toJson()).toList(); data['predecessor-version'] = this.predecessorVersion?.map((v) => v.toJson()).toList(); data['wp:featuredmedia'] = this.wpFeaturedmedia?.map((v) => v.toJson()).toList(); data['wp:attachment'] = this.wpAttachment?.map((v) => v.toJson()).toList(); data['wp:term'] = this.wpTerm?.map((v) => v.toJson()).toList(); data['wp:action-publish'] = this.wpActionPublish?.map((v) => v.toJson()).toList(); data['wp:action-unfiltered-html'] = this.wpActionUnfilteredHtml?.map((v) => v.toJson()).toList(); data['wp:action-sticky'] = this.wpActionSticky?.map((v) => v.toJson()).toList(); data['wp:action-assign-author'] = this.wpActionAssignAuthor?.map((v) => v.toJson()).toList(); data['wp:action-create-categories'] = this.wpActionCreateCategories?.map((v) => v.toJson()).toList(); data['wp:action-assign-categories'] = this.wpActionAssignCategories?.map((v) => v.toJson()).toList(); data['wp:action-create-tags'] = this.wpActionCreateTags?.map((v) => v.toJson()).toList(); data['wp:action-assign-tags'] = this.wpActionAssignTags?.map((v) => v.toJson()).toList(); data['wp:items'] = this.wpItems?.map((v) => v.toJson()).toList(); data['up'] = this.up?.map((v) => v.toJson()).toList(); data['in-reply-to'] = this.inReplyTo?.map((v) => v.toJson()).toList(); data['children'] = this.children?.map((v) => v.toJson()).toList(); data['curies'] = this.curies?.map((v) => v.toJson()).toList(); return data; } } class Self { String? href; Self({this.href}); Self.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class Collection { String? href; Collection({this.href}); Collection.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class About { String? href; About({this.href}); About.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class Author { bool? embeddable; String? href; Author({ this.embeddable, this.href, }); Author.fromJson(Map json) { embeddable = json['embeddable']; href = json['href']; } Map toJson() { final Map data = new Map(); if (this.embeddable != null) { data['embeddable'] = this.embeddable; } if (this.href != null) { data['href'] = this.href; } return data; } } class Replies { bool? embeddable; String? href; Replies({ this.embeddable, this.href, }); Replies.fromJson(Map json) { embeddable = json['embeddable']; href = json['href']; } Map toJson() { final Map data = new Map(); if (this.embeddable != null) { data['embeddable'] = this.embeddable; } if (this.href != null) { data['href'] = this.href; } return data; } } class Archives { String? href; Archives({this.href}); Archives.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class VersionHistory { int? count; String? href; VersionHistory({ this.count, this.href, }); VersionHistory.fromJson(Map json) { count = json['count']; href = json['href']; } Map toJson() { final Map data = new Map(); if (this.count != null) { data['count'] = this.count; } if (this.href != null) { data['href'] = this.href; } return data; } } class WpPostType { String? href; WpPostType({this.href}); WpPostType.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class PredecessorVersion { int? id; String? href; PredecessorVersion({ this.id, this.href, }); PredecessorVersion.fromJson(Map json) { id = json['id']; href = json['href']; } Map toJson() { final Map data = new Map(); if (this.id != null) { data['id'] = this.id; } if (this.href != null) { data['href'] = this.href; } return data; } } class WpFeaturedmedia { bool? embeddable; String? href; WpFeaturedmedia({ this.embeddable, this.href, }); WpFeaturedmedia.fromJson(Map json) { embeddable = json['embeddable']; href = json['href']; } Map toJson() { final Map data = new Map(); if (this.embeddable != null) { data['embeddable'] = this.embeddable; } if (this.href != null) { data['href'] = this.href; } return data; } } class WpAttachment { String? href; WpAttachment({this.href}); WpAttachment.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class WpTerm { String? taxonomy; bool? embeddable; String? href; WpTerm({ this.taxonomy, this.embeddable, this.href, }); WpTerm.fromJson(Map json) { taxonomy = json['taxonomy']; embeddable = json['embeddable']; href = json['href']; } Map toJson() { final Map data = new Map(); if (this.taxonomy != null) { data['taxonomy'] = this.taxonomy; } if (this.embeddable != null) { data['embeddable'] = this.embeddable; } if (this.href != null) { data['href'] = this.href; } return data; } } class WpActionPublish { String? href; WpActionPublish({this.href}); WpActionPublish.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class WpActionUnfilteredHtml { String? href; WpActionUnfilteredHtml({this.href}); WpActionUnfilteredHtml.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class WpActionSticky { String? href; WpActionSticky({this.href}); WpActionSticky.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class WpActionAssignAuthor { String? href; WpActionAssignAuthor({this.href}); WpActionAssignAuthor.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class WpActionCreateCategories { String? href; WpActionCreateCategories({this.href}); WpActionCreateCategories.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class WpActionAssignCategories { String? href; WpActionAssignCategories({this.href}); WpActionAssignCategories.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class WpActionCreateTags { String? href; WpActionCreateTags({this.href}); WpActionCreateTags.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class WpActionAssignTags { String? href; WpActionAssignTags({this.href}); WpActionAssignTags.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class WpItems { String? href; WpItems({this.href}); WpItems.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class Up { bool? embeddable; String? postType; String? href; Up({ this.embeddable, this.postType, this.href, }); Up.fromJson(Map json) { embeddable = json['embeddable']; postType = json['post_type']; href = json['href']; } Map toJson() { final Map data = new Map(); if (this.embeddable != null) { data['embeddable'] = this.embeddable; } if (this.postType != null) { data['post_type'] = this.postType; } if (this.href != null) { data['href'] = this.href; } return data; } } class InReplyTo { bool? embeddable; String? href; InReplyTo({ this.embeddable, this.href, }); InReplyTo.fromJson(Map json) { embeddable = json['embeddable']; href = json['href']; } Map toJson() { final Map data = new Map(); if (this.embeddable != null) { data['embeddable'] = this.embeddable; } if (this.href != null) { data['href'] = this.href; } return data; } } class Children { String? href; Children({this.href}); Children.fromJson(Map json) { href = json['href']; } Map toJson() { final Map data = new Map(); if (this.href != null) { data['href'] = this.href; } return data; } } class Curies { String? name; String? href; bool? templated; Curies({ this.name, this.href, this.templated, }); Curies.fromJson(Map json) { name = json['name']; href = json['href']; templated = json['templated']; } Map toJson() { final Map data = new Map(); if (this.name != null) { data['name'] = this.name; } if (this.href != null) { data['href'] = this.href; } if (this.templated != null) { data['templated'] = this.templated; } return data; } } ================================================ FILE: lib/schemas/media.dart ================================================ import 'guid.dart'; import 'links.dart'; import 'title.dart'; class Media { int? id; String? date; String? dateGmt; Guid? guid; String? modified; String? modifiedGmt; String? slug; String? status; String? type; String? link; Title? title; int? author; String? commentStatus; String? pingStatus; String? template; String? permalinkTemplate; String? generatedSlug; Description? description; Caption? caption; String? altText; String? mediaType; String? mimeType; MediaDetails? mediaDetails; int? post; String? sourceUrl; Links? lLinks; Media({ this.id, this.date, this.dateGmt, this.guid, this.modified, this.modifiedGmt, this.slug, this.status, this.type, this.link, this.title, this.author, this.commentStatus, this.pingStatus, this.template, this.permalinkTemplate, this.generatedSlug, this.description, this.caption, this.altText, this.mediaType, this.mimeType, this.mediaDetails, this.post, this.sourceUrl, this.lLinks, }); Media.fromJson(Map json) { id = json['id']; date = json['date']; dateGmt = json['date_gmt']; guid = json['guid'] != null ? new Guid.fromJson(json['guid']) : null; modified = json['modified']; modifiedGmt = json['modified_gmt']; slug = json['slug']; status = json['status']; type = json['type']; link = json['link']; title = json['title'] != null ? new Title.fromJson(json['title']) : null; author = json['author']; commentStatus = json['comment_status']; pingStatus = json['ping_status']; template = json['template']; permalinkTemplate = json['permalink_template']; generatedSlug = json['generated_slug']; description = json['description'] != null ? new Description.fromJson(json['description']) : null; caption = json['caption'] != null ? new Caption.fromJson(json['caption']) : null; altText = json['alt_text']; mediaType = json['media_type']; mimeType = json['mime_type']; mediaDetails = json['media_details'] != null ? new MediaDetails.fromJson(json['media_details']) : null; post = json['post']; sourceUrl = json['source_url']; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['id'] = this.id; data['date'] = this.date; data['date_gmt'] = this.dateGmt; data['guid'] = this.guid?.toJson(); data['modified'] = this.modified; data['modified_gmt'] = this.modifiedGmt; data['slug'] = this.slug; data['status'] = this.status; data['type'] = this.type; data['link'] = this.link; data['title'] = this.title?.toJson(); data['author'] = this.author; data['comment_status'] = this.commentStatus; data['ping_status'] = this.pingStatus; data['template'] = this.template; data['permalink_template'] = this.permalinkTemplate; data['generated_slug'] = this.generatedSlug; data['description'] = this.description?.toJson(); data['caption'] = this.caption?.toJson(); data['alt_text'] = this.altText; data['media_type'] = this.mediaType; data['mime_type'] = this.mimeType; data['media_details'] = this.mediaDetails?.toJson(); data['post'] = this.post; data['source_url'] = this.sourceUrl; data['_links'] = this.lLinks?.toJson(); return data; } } class Description { String? raw; String? rendered; Description({ this.raw, this.rendered, }); Description.fromJson(Map json) { raw = json['raw']; rendered = json['rendered']; } Map toJson() { final Map data = new Map(); data['raw'] = this.raw; data['rendered'] = this.rendered; return data; } } class Caption { String? raw; String? rendered; Caption({ this.raw, this.rendered, }); Caption.fromJson(Map json) { raw = json['raw']; rendered = json['rendered']; } Map toJson() { final Map data = new Map(); data['raw'] = this.raw; data['rendered'] = this.rendered; return data; } } class MediaDetails { int? width; int? height; String? file; Sizes? sizes; ImageMeta? imageMeta; MediaDetails({ this.width, this.height, this.file, this.sizes, this.imageMeta, }); MediaDetails.fromJson(Map json) { width = json['width']; height = json['height']; file = json['file']; sizes = json['sizes'] != null ? new Sizes.fromJson(json['sizes']) : null; imageMeta = json['image_meta'] != null ? new ImageMeta.fromJson(json['image_meta']) : null; } Map toJson() { final Map data = new Map(); data['width'] = this.width; data['height'] = this.height; data['file'] = this.file; data['sizes'] = this.sizes?.toJson(); data['image_meta'] = this.imageMeta?.toJson(); return data; } } class Sizes { Thumbnail? thumbnail; Medium? medium; MediumLarge? mediumLarge; Large? large; PostThumbnail? postThumbnail; Full? full; Sizes({ this.thumbnail, this.medium, this.mediumLarge, this.postThumbnail, this.large, this.full, }); Sizes.fromJson(Map json) { thumbnail = json['thumbnail'] != null ? new Thumbnail.fromJson(json['thumbnail']) : null; medium = json['medium'] != null ? new Medium.fromJson(json['medium']) : null; mediumLarge = json['medium_large'] != null ? new MediumLarge.fromJson(json['medium_large']) : null; large = json['large'] != null ? new Large.fromJson(json['large']) : null; postThumbnail = json['post-thumbnail'] != null ? new PostThumbnail.fromJson(json['post-thumbnail']) : null; full = json['full'] != null ? new Full.fromJson(json['full']) : null; } Map toJson() { final Map data = new Map(); data['thumbnail'] = this.thumbnail?.toJson(); data['medium'] = this.medium?.toJson(); data['medium_large'] = this.mediumLarge?.toJson(); data['large'] = this.large?.toJson(); data['post-thumbnail'] = this.postThumbnail?.toJson(); data['full'] = this.full?.toJson(); return data; } } class Thumbnail { String? file; int? width; int? height; String? mimeType; String? sourceUrl; Thumbnail({ this.file, this.width, this.height, this.mimeType, this.sourceUrl, }); Thumbnail.fromJson(Map json) { file = json['file']; width = json['width']; height = json['height']; mimeType = json['mime_type']; sourceUrl = json['source_url']; } Map toJson() { final Map data = new Map(); data['file'] = this.file; data['width'] = this.width; data['height'] = this.height; data['mime_type'] = this.mimeType; data['source_url'] = this.sourceUrl; return data; } } class Medium { String? file; int? width; int? height; String? mimeType; String? sourceUrl; Medium({ this.file, this.width, this.height, this.mimeType, this.sourceUrl, }); Medium.fromJson(Map json) { file = json['file']; width = json['width']; height = json['height']; mimeType = json['mime_type']; sourceUrl = json['source_url']; } Map toJson() { final Map data = new Map(); data['file'] = this.file; data['width'] = this.width; data['height'] = this.height; data['mime_type'] = this.mimeType; data['source_url'] = this.sourceUrl; return data; } } class MediumLarge { String? file; int? width; int? height; String? mimeType; String? sourceUrl; MediumLarge({ this.file, this.width, this.height, this.mimeType, this.sourceUrl, }); MediumLarge.fromJson(Map json) { file = json['file']; width = json['width']; height = json['height']; mimeType = json['mime_type']; sourceUrl = json['source_url']; } Map toJson() { final Map data = new Map(); data['file'] = this.file; data['width'] = this.width; data['height'] = this.height; data['mime_type'] = this.mimeType; data['source_url'] = this.sourceUrl; return data; } } class Large { String? file; int? width; int? height; String? mimeType; String? sourceUrl; Large({ this.file, this.width, this.height, this.mimeType, this.sourceUrl, }); Large.fromJson(Map json) { file = json['file']; width = json['width']; height = json['height']; mimeType = json['mime_type']; sourceUrl = json['source_url']; } Map toJson() { final Map data = new Map(); data['file'] = this.file; data['width'] = this.width; data['height'] = this.height; data['mime_type'] = this.mimeType; data['source_url'] = this.sourceUrl; return data; } } class PostThumbnail { String? file; int? width; int? height; String? mimeType; String? sourceUrl; PostThumbnail({ this.file, this.width, this.height, this.mimeType, this.sourceUrl, }); PostThumbnail.fromJson(Map json) { file = json['file']; width = json['width']; height = json['height']; mimeType = json['mime_type']; sourceUrl = json['source_url']; } Map toJson() { final Map data = new Map(); data['file'] = this.file; data['width'] = this.width; data['height'] = this.height; data['mime_type'] = this.mimeType; data['source_url'] = this.sourceUrl; return data; } } class Full { String? file; int? width; int? height; String? mimeType; String? sourceUrl; Full({ this.file, this.width, this.height, this.mimeType, this.sourceUrl, }); Full.fromJson(Map json) { file = json['file']; width = json['width']; height = json['height']; mimeType = json['mime_type']; sourceUrl = json['source_url']; } Map toJson() { final Map data = new Map(); data['file'] = this.file; data['width'] = this.width; data['height'] = this.height; data['mime_type'] = this.mimeType; data['source_url'] = this.sourceUrl; return data; } } class ImageMeta { String? aperture; String? credit; String? camera; String? caption; String? createdTimestamp; String? copyright; String? focalLength; String? iso; String? shutterSpeed; String? title; String? orientation; ImageMeta({ this.aperture, this.credit, this.camera, this.caption, this.createdTimestamp, this.copyright, this.focalLength, this.iso, this.shutterSpeed, this.title, this.orientation, }); ImageMeta.fromJson(Map json) { aperture = json['aperture']; credit = json['credit']; camera = json['camera']; caption = json['caption']; createdTimestamp = json['created_timestamp']; copyright = json['copyright']; focalLength = json['focal_length']; iso = json['iso']; shutterSpeed = json['shutter_speed']; title = json['title']; orientation = json['orientation'].toString(); } Map toJson() { final Map data = new Map(); data['aperture'] = this.aperture; data['credit'] = this.credit; data['camera'] = this.camera; data['caption'] = this.caption; data['created_timestamp'] = this.createdTimestamp; data['copyright'] = this.copyright; data['focal_length'] = this.focalLength; data['iso'] = this.iso; data['shutter_speed'] = this.shutterSpeed; data['title'] = this.title; data['orientation'] = this.orientation; return data; } } ================================================ FILE: lib/schemas/page.dart ================================================ import 'content.dart'; import 'excerpt.dart'; import 'guid.dart'; import 'links.dart'; import 'title.dart'; class Page { int? id; String? date; String? dateGmt; Guid? guid; String? modified; String? modifiedGmt; String? password; String? slug; String? status; String? type; String? link; Title? title; Content? content; Excerpt? excerpt; int? author; int? featuredMedia; int? parent; int? menuOrder; String? commentStatus; String? pingStatus; String? template; String? permalinkTemplate; String? generatedSlug; Links? lLinks; Page({ this.id, this.date, this.dateGmt, this.guid, this.modified, this.modifiedGmt, this.password, this.slug, this.status, this.type, this.link, this.title, this.content, this.excerpt, this.author, this.featuredMedia, this.parent, this.menuOrder, this.commentStatus, this.pingStatus, this.template, this.permalinkTemplate, this.generatedSlug, this.lLinks, }); Page.fromJson(Map json) { id = json['id']; date = json['date']; dateGmt = json['date_gmt']; guid = json['guid'] != null ? new Guid.fromJson(json['guid']) : null; modified = json['modified']; modifiedGmt = json['modified_gmt']; password = json['password']; slug = json['slug']; status = json['status']; type = json['type']; link = json['link']; title = json['title'] != null ? new Title.fromJson(json['title']) : null; content = json['content'] != null ? new Content.fromJson(json['content']) : null; excerpt = json['excerpt'] != null ? new Excerpt.fromJson(json['excerpt']) : null; author = json['author']; featuredMedia = json['featured_media']; parent = json['parent']; menuOrder = json['menu_order']; commentStatus = json['comment_status']; pingStatus = json['ping_status']; template = json['template']; permalinkTemplate = json['permalink_template']; generatedSlug = json['generated_slug']; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['id'] = this.id; data['date'] = this.date; data['date_gmt'] = this.dateGmt; data['guid'] = this.guid?.toJson(); data['modified'] = this.modified; data['modified_gmt'] = this.modifiedGmt; data['password'] = this.password; data['slug'] = this.slug; data['status'] = this.status; data['type'] = this.type; data['link'] = this.link; data['title'] = this.title?.toJson(); data['content'] = this.content?.toJson(); data['excerpt'] = this.excerpt?.toJson(); data['author'] = this.author; data['featured_media'] = this.featuredMedia; data['parent'] = this.parent; data['menu_order'] = this.menuOrder; data['comment_status'] = this.commentStatus; data['ping_status'] = this.pingStatus; data['template'] = this.template; data['permalink_template'] = this.permalinkTemplate; data['generated_slug'] = this.generatedSlug; data['_links'] = this.lLinks?.toJson(); return data; } } ================================================ FILE: lib/schemas/post.dart ================================================ import 'package:flutter_wordpress/constants.dart'; import 'category.dart'; import 'comment.dart'; import 'comment_hierarchy.dart'; import 'content.dart'; import 'excerpt.dart'; import 'guid.dart'; import 'links.dart'; import 'media.dart'; import 'tag.dart'; import 'title.dart'; import 'user.dart'; /// A [WordPress Post](https://developer.wordpress.org/rest-api/reference/posts/) /// /// Refer the above link to see which arguments are set based on different context modes. /// ([WordPressContext]). class Post { /// ID of the post int? id; /// The date the post was published, in the site's Timezone. String? date; /// The date the post was published, in GMT. String? dateGmt; Guid? guid; String? modified; String? modifiedGmt; /// Password for the post in case it needs to be password protected. String? password; /// An alphanumeric identifier unique to each post. String? slug; /// The state in which the post should be created (draft, publish etc.) PostPageStatus? status; String? type; String? link; /// Post title Title? title; /// Post content Content? content; /// Post excerpt Excerpt? excerpt; /// ID of the post author. Refer [User]. int? authorID; int? featuredMediaID; /// Whether the post allows commenting. PostCommentStatus? commentStatus; /// Whether the post can be pinged. PostPingStatus? pingStatus; /// Whether the post needs to sticky i.e. a Featured post. bool? sticky; String? template; /// The format of the post. PostFormat? format; /// List of IDs of categories this post belongs to. List? categoryIDs; /// List of IDs of tags this post should have. List? tagIDs; String? permalinkTemplate; String? generatedSlug; Links? lLinks; /// The [User] object denoting the author of the post. User? author; /// A list of comments for the post. List? comments; /// A list of comments for the post, where each /// [CommentHierarchy] object is a direct comment to the post, with /// [CommentHierarchy.children] containing replies to that comment. List? commentsHierarchy; /// A list of categories assigned to the post. List? categories; /// A list of tags assigned to the post. List? tags; /// A list of attachments contained in the post. List? attachments; /// The featured Media of the post. Media? featuredMedia; Post({ this.date, this.dateGmt, this.password, this.slug, this.status = PostPageStatus.publish, required String title, required String content, required String excerpt, required this.authorID, String? featuredMedia, this.featuredMediaID, this.commentStatus = PostCommentStatus.open, this.pingStatus = PostPingStatus.open, this.sticky, this.template, this.format = PostFormat.standard, this.categoryIDs, this.tagIDs, }) : this.title = new Title(rendered: title), this.featuredMedia = new Media(sourceUrl: featuredMedia), this.content = new Content(rendered: content), this.excerpt = new Excerpt(rendered: excerpt); Post.fromJson(Map json) { id = json['id']; date = json['date']; dateGmt = json['date_gmt']; guid = json['guid'] != null ? new Guid.fromJson(json['guid']) : null; modified = json['modified']; modifiedGmt = json['modified_gmt']; password = json['password']; slug = json['slug']; if (json['status'] != null) { PostPageStatus.values.forEach((val) { if (enumStringToName(val.toString()) == json['status']) { status = val; return; } }); } type = json['type']; link = json['link']; title = json['title'] != null ? new Title.fromJson(json['title']) : null; content = json['content'] != null ? new Content.fromJson(json['content']) : null; excerpt = json['excerpt'] != null ? new Excerpt.fromJson(json['excerpt']) : null; authorID = json['author']; featuredMediaID = json['featured_media']; if (json['comment_status'] != null) { PostCommentStatus.values.forEach((val) { if (enumStringToName(val.toString()) == json['comment_status']) { commentStatus = val; return; } }); } if (json['ping_status'] != null) { PostPingStatus.values.forEach((val) { if (enumStringToName(val.toString()) == json['ping_status']) { pingStatus = val; return; } }); } sticky = json['sticky']; template = json['template']; if (json['format'] != null) { PostFormat.values.forEach((val) { if (enumStringToName(val.toString()) == json['format']) { format = val; return; } }); } categoryIDs = json['categories'] != null ? json['categories'].cast() : null; tagIDs = json['tags'] != null ? json['tags'].cast() : null; permalinkTemplate = json['permalink_template']; generatedSlug = json['generated_slug']; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['date'] = this.date; data['date_gmt'] = this.dateGmt; data['password'] = this.password; data['slug'] = this.slug; data['status'] = enumStringToName(this.status.toString()); data['title'] = this.title?.toJson(); data['content'] = this.content?.toJson(); data['excerpt'] = this.excerpt?.toJson(); data['author'] = this.authorID; data['featured_media'] = this.featuredMediaID; data['comment_status'] = enumStringToName(this.commentStatus.toString()); data['ping_status'] = enumStringToName(this.pingStatus.toString()); data['sticky'] = this.sticky; data['template'] = this.template; data['format'] = enumStringToName(this.format.toString()); data['categories'] = listToUrlString(this.categoryIDs ?? []); data['tags'] = listToUrlString(this.tagIDs ?? []); return data; } @override String toString() { return 'Post: { id: $id, title: ${title?.rendered}, ' 'author: {id: $authorID, name: ${author?.name}}}'; } } ================================================ FILE: lib/schemas/post_statuses.dart ================================================ import 'links.dart'; class PostStatuses { Publish? publish; Future? future; Draft? draft; Pending? pending; Private? private; Trash? trash; PostStatuses({ this.publish, this.future, this.draft, this.pending, this.private, this.trash, }); PostStatuses.fromJson(Map json) { publish = json['publish'] != null ? new Publish.fromJson(json['publish']) : null; future = json['future'] != null ? new Future.fromJson(json['future']) : null; draft = json['draft'] != null ? new Draft.fromJson(json['draft']) : null; pending = json['pending'] != null ? new Pending.fromJson(json['pending']) : null; private = json['private'] != null ? new Private.fromJson(json['private']) : null; trash = json['trash'] != null ? new Trash.fromJson(json['trash']) : null; } Map toJson() { final Map data = new Map(); data['publish'] = this.publish?.toJson(); data['future'] = this.future?.toJson(); data['draft'] = this.draft?.toJson(); data['pending'] = this.pending?.toJson(); data['private'] = this.private?.toJson(); data['trash'] = this.trash?.toJson(); return data; } } class Publish { String? name; bool? private; bool? protected; bool? public; bool? queryable; bool? showInList; String? slug; Links? lLinks; Publish({ this.name, this.private, this.protected, this.public, this.queryable, this.showInList, this.slug, this.lLinks, }); Publish.fromJson(Map json) { name = json['name']; private = json['private']; protected = json['protected']; public = json['public']; queryable = json['queryable']; showInList = json['show_in_list']; slug = json['slug']; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['name'] = this.name; data['private'] = this.private; data['protected'] = this.protected; data['public'] = this.public; data['queryable'] = this.queryable; data['show_in_list'] = this.showInList; data['slug'] = this.slug; data['_links'] = this.lLinks?.toJson(); return data; } } class Future { String? name; bool? private; bool? protected; bool? public; bool? queryable; bool? showInList; String? slug; Links? lLinks; Future({ this.name, this.private, this.protected, this.public, this.queryable, this.showInList, this.slug, this.lLinks, }); Future.fromJson(Map json) { name = json['name']; private = json['private']; protected = json['protected']; public = json['public']; queryable = json['queryable']; showInList = json['show_in_list']; slug = json['slug']; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['name'] = this.name; data['private'] = this.private; data['protected'] = this.protected; data['public'] = this.public; data['queryable'] = this.queryable; data['show_in_list'] = this.showInList; data['slug'] = this.slug; data['_links'] = this.lLinks?.toJson(); return data; } } class Draft { String? name; bool? private; bool? protected; bool? public; bool? queryable; bool? showInList; String? slug; Links? lLinks; Draft({ this.name, this.private, this.protected, this.public, this.queryable, this.showInList, this.slug, this.lLinks, }); Draft.fromJson(Map json) { name = json['name']; private = json['private']; protected = json['protected']; public = json['public']; queryable = json['queryable']; showInList = json['show_in_list']; slug = json['slug']; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['name'] = this.name; data['private'] = this.private; data['protected'] = this.protected; data['public'] = this.public; data['queryable'] = this.queryable; data['show_in_list'] = this.showInList; data['slug'] = this.slug; data['_links'] = this.lLinks?.toJson(); return data; } } class Pending { String? name; bool? private; bool? protected; bool? public; bool? queryable; bool? showInList; String? slug; Links? lLinks; Pending({ this.name, this.private, this.protected, this.public, this.queryable, this.showInList, this.slug, this.lLinks, }); Pending.fromJson(Map json) { name = json['name']; private = json['private']; protected = json['protected']; public = json['public']; queryable = json['queryable']; showInList = json['show_in_list']; slug = json['slug']; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['name'] = this.name; data['private'] = this.private; data['protected'] = this.protected; data['public'] = this.public; data['queryable'] = this.queryable; data['show_in_list'] = this.showInList; data['slug'] = this.slug; data['_links'] = this.lLinks?.toJson(); return data; } } class Private { String? name; bool? private; bool? protected; bool? public; bool? queryable; bool? showInList; String? slug; Links? lLinks; Private({ this.name, this.private, this.protected, this.public, this.queryable, this.showInList, this.slug, this.lLinks, }); Private.fromJson(Map json) { name = json['name']; private = json['private']; protected = json['protected']; public = json['public']; queryable = json['queryable']; showInList = json['show_in_list']; slug = json['slug']; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['name'] = this.name; data['private'] = this.private; data['protected'] = this.protected; data['public'] = this.public; data['queryable'] = this.queryable; data['show_in_list'] = this.showInList; data['slug'] = this.slug; data['_links'] = this.lLinks?.toJson(); return data; } } class Trash { String? name; bool? private; bool? protected; bool? public; bool? queryable; bool? showInList; String? slug; Links? lLinks; Trash({ this.name, this.private, this.protected, this.public, this.queryable, this.showInList, this.slug, this.lLinks, }); Trash.fromJson(Map json) { name = json['name']; private = json['private']; protected = json['protected']; public = json['public']; queryable = json['queryable']; showInList = json['show_in_list']; slug = json['slug']; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['name'] = this.name; data['private'] = this.private; data['protected'] = this.protected; data['public'] = this.public; data['queryable'] = this.queryable; data['show_in_list'] = this.showInList; data['slug'] = this.slug; data['_links'] = this.lLinks?.toJson(); return data; } } ================================================ FILE: lib/schemas/post_types.dart ================================================ import 'capabilities.dart'; import 'labels.dart'; import 'links.dart'; class PostTypes { PostTypePost? post; PostTypePage? page; Attachment? attachment; WpBlock? wpBlock; PostTypes({ this.post, this.page, this.attachment, this.wpBlock, }); PostTypes.fromJson(Map json) { post = json['post'] != null ? new PostTypePost.fromJson(json['post']) : null; page = json['page'] != null ? new PostTypePage.fromJson(json['page']) : null; attachment = json['attachment'] != null ? new Attachment.fromJson(json['attachment']) : null; wpBlock = json['wp_block'] != null ? new WpBlock.fromJson(json['wp_block']) : null; } Map toJson() { final Map data = new Map(); data['post'] = this.post?.toJson(); data['page'] = this.page?.toJson(); data['attachment'] = this.attachment?.toJson(); data['wp_block'] = this.wpBlock?.toJson(); return data; } } class PostTypePost { Capabilities? capabilities; String? description; bool? hierarchical; bool? viewable; Labels? labels; String? name; String? slug; Supports? supports; List? taxonomies; String? restBase; Links? lLinks; PostTypePost({ this.capabilities, this.description, this.hierarchical, this.viewable, this.labels, this.name, this.slug, this.supports, this.taxonomies, this.restBase, this.lLinks, }); PostTypePost.fromJson(Map json) { capabilities = json['capabilities'] != null ? new Capabilities.fromJson(json['capabilities']) : null; description = json['description']; hierarchical = json['hierarchical']; viewable = json['viewable']; labels = json['labels'] != null ? new Labels.fromJson(json['labels']) : null; name = json['name']; slug = json['slug']; supports = json['supports'] != null ? new Supports.fromJson(json['supports']) : null; taxonomies = json['taxonomies'].cast(); restBase = json['rest_base']; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['capabilities'] = this.capabilities?.toJson(); data['description'] = this.description; data['hierarchical'] = this.hierarchical; data['viewable'] = this.viewable; data['labels'] = this.labels?.toJson(); data['name'] = this.name; data['slug'] = this.slug; data['supports'] = this.supports?.toJson(); data['taxonomies'] = this.taxonomies; data['rest_base'] = this.restBase; data['_links'] = this.lLinks?.toJson(); return data; } } class Supports { bool? title; bool? editor; bool? author; bool? thumbnail; bool? excerpt; bool? trackbacks; bool? customFields; bool? comments; bool? revisions; bool? postFormats; Supports({ this.title, this.editor, this.author, this.thumbnail, this.excerpt, this.trackbacks, this.customFields, this.comments, this.revisions, this.postFormats, }); Supports.fromJson(Map json) { title = json['title']; editor = json['editor']; author = json['author']; thumbnail = json['thumbnail']; excerpt = json['excerpt']; trackbacks = json['trackbacks']; customFields = json['custom-fields']; comments = json['comments']; revisions = json['revisions']; postFormats = json['post-formats']; } Map toJson() { final Map data = new Map(); data['title'] = this.title; data['editor'] = this.editor; data['author'] = this.author; data['thumbnail'] = this.thumbnail; data['excerpt'] = this.excerpt; data['trackbacks'] = this.trackbacks; data['custom-fields'] = this.customFields; data['comments'] = this.comments; data['revisions'] = this.revisions; data['post-formats'] = this.postFormats; return data; } } class PostTypePage { Capabilities? capabilities; String? description; bool? hierarchical; bool? viewable; Labels? labels; String? name; String? slug; Supports? supports; List? taxonomies; String? restBase; Links? lLinks; PostTypePage({ this.capabilities, this.description, this.hierarchical, this.viewable, this.labels, this.name, this.slug, this.supports, this.taxonomies, this.restBase, this.lLinks, }); PostTypePage.fromJson(Map json) { capabilities = json['capabilities'] != null ? new Capabilities.fromJson(json['capabilities']) : null; description = json['description']; hierarchical = json['hierarchical']; viewable = json['viewable']; labels = json['labels'] != null ? new Labels.fromJson(json['labels']) : null; name = json['name']; slug = json['slug']; supports = json['supports'] != null ? new Supports.fromJson(json['supports']) : null; taxonomies = json['taxonomies'].cast(); restBase = json['rest_base']; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['capabilities'] = this.capabilities?.toJson(); data['description'] = this.description; data['hierarchical'] = this.hierarchical; data['viewable'] = this.viewable; data['labels'] = this.labels?.toJson(); data['name'] = this.name; data['slug'] = this.slug; data['supports'] = this.supports?.toJson(); data['taxonomies'] = this.taxonomies; data['rest_base'] = this.restBase; data['_links'] = this.lLinks?.toJson(); return data; } } class Attachment { Capabilities? capabilities; String? description; bool? hierarchical; bool? viewable; Labels? labels; String? name; String? slug; Supports? supports; List? taxonomies; String? restBase; Links? lLinks; Attachment({ this.capabilities, this.description, this.hierarchical, this.viewable, this.labels, this.name, this.slug, this.supports, this.taxonomies, this.restBase, this.lLinks, }); Attachment.fromJson(Map json) { capabilities = json['capabilities'] != null ? new Capabilities.fromJson(json['capabilities']) : null; description = json['description']; hierarchical = json['hierarchical']; viewable = json['viewable']; labels = json['labels'] != null ? new Labels.fromJson(json['labels']) : null; name = json['name']; slug = json['slug']; supports = json['supports'] != null ? new Supports.fromJson(json['supports']) : null; taxonomies = json['taxonomies'].cast(); restBase = json['rest_base']; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['capabilities'] = this.capabilities?.toJson(); data['description'] = this.description; data['hierarchical'] = this.hierarchical; data['viewable'] = this.viewable; data['labels'] = this.labels?.toJson(); data['name'] = this.name; data['slug'] = this.slug; data['supports'] = this.supports?.toJson(); data['taxonomies'] = this.taxonomies; data['rest_base'] = this.restBase; data['_links'] = this.lLinks?.toJson(); return data; } } class WpBlock { Capabilities? capabilities; String? description; bool? hierarchical; bool? viewable; Labels? labels; String? name; String? slug; Supports? supports; List? taxonomies; String? restBase; Links? lLinks; WpBlock({ this.capabilities, this.description, this.hierarchical, this.viewable, this.labels, this.name, this.slug, this.supports, this.taxonomies, this.restBase, this.lLinks, }); WpBlock.fromJson(Map json) { capabilities = json['capabilities'] != null ? new Capabilities.fromJson(json['capabilities']) : null; description = json['description']; hierarchical = json['hierarchical']; viewable = json['viewable']; labels = json['labels'] != null ? new Labels.fromJson(json['labels']) : null; name = json['name']; slug = json['slug']; supports = json['supports'] != null ? new Supports.fromJson(json['supports']) : null; taxonomies = json['taxonomies'].cast(); restBase = json['rest_base']; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['capabilities'] = this.capabilities?.toJson(); data['description'] = this.description; data['hierarchical'] = this.hierarchical; data['viewable'] = this.viewable; data['labels'] = this.labels?.toJson(); data['name'] = this.name; data['slug'] = this.slug; data['supports'] = this.supports?.toJson(); data['taxonomies'] = this.taxonomies; data['rest_base'] = this.restBase; data['_links'] = this.lLinks?.toJson(); return data; } } ================================================ FILE: lib/schemas/settings.dart ================================================ class Settings { String? title; String? description; String? url; String? email; String? timezone; String? dateFormat; String? timeFormat; int? startOfWeek; String? language; bool? useSmilies; int? defaultCategory; String? defaultPostFormat; int? postsPerPage; String? defaultPingStatus; String? defaultCommentStatus; Settings({ this.title, this.description, this.url, this.email, this.timezone, this.dateFormat, this.timeFormat, this.startOfWeek, this.language, this.useSmilies, this.defaultCategory, this.defaultPostFormat, this.postsPerPage, this.defaultPingStatus, this.defaultCommentStatus, }); Settings.fromJson(Map json) { title = json['title']; description = json['description']; url = json['url']; email = json['email']; timezone = json['timezone']; dateFormat = json['date_format']; timeFormat = json['time_format']; startOfWeek = json['start_of_week']; language = json['language']; useSmilies = json['use_smilies']; defaultCategory = json['default_category']; defaultPostFormat = json['default_post_format']; postsPerPage = json['posts_per_page']; defaultPingStatus = json['default_ping_status']; defaultCommentStatus = json['default_comment_status']; } Map toJson() { final Map data = new Map(); data['title'] = this.title; data['description'] = this.description; data['url'] = this.url; data['email'] = this.email; data['timezone'] = this.timezone; data['date_format'] = this.dateFormat; data['time_format'] = this.timeFormat; data['start_of_week'] = this.startOfWeek; data['language'] = this.language; data['use_smilies'] = this.useSmilies; data['default_category'] = this.defaultCategory; data['default_post_format'] = this.defaultPostFormat; data['posts_per_page'] = this.postsPerPage; data['default_ping_status'] = this.defaultPingStatus; data['default_comment_status'] = this.defaultCommentStatus; return data; } } ================================================ FILE: lib/schemas/tag.dart ================================================ import 'links.dart'; class Tag { int? id; int? count; String? description; String? link; String? name; String? slug; String? taxonomy; Links? lLinks; Tag({ this.id, this.count, this.description, this.link, this.name, this.slug, this.taxonomy, this.lLinks, }); Tag.fromJson(Map json) { id = json['id']; count = json['count']; description = json['description']; link = json['link']; name = json['name']; slug = json['slug']; taxonomy = json['taxonomy']; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['id'] = this.id; data['count'] = this.count; data['description'] = this.description; data['link'] = this.link; data['name'] = this.name; data['slug'] = this.slug; data['taxonomy'] = this.taxonomy; data['_links'] = this.lLinks?.toJson(); return data; } } ================================================ FILE: lib/schemas/taxonomies.dart ================================================ import 'capabilities.dart'; import 'labels.dart'; import 'links.dart'; class Taxonomies { TaxonomyCategory? category; TaxonomyPostTag? postTag; Taxonomies({ this.category, this.postTag, }); Taxonomies.fromJson(Map json) { category = json['category'] != null ? new TaxonomyCategory.fromJson(json['category']) : null; postTag = json['post_tag'] != null ? new TaxonomyPostTag.fromJson(json['post_tag']) : null; } Map toJson() { final Map data = new Map(); data['category'] = this.category?.toJson(); data['post_tag'] = this.postTag?.toJson(); return data; } } class TaxonomyCategory { String? name; String? slug; Capabilities? capabilities; String? description; Labels? labels; List? types; bool? showCloud; bool? hierarchical; String? restBase; Visibility? visibility; Links? lLinks; TaxonomyCategory({ this.name, this.slug, this.capabilities, this.description, this.labels, this.types, this.showCloud, this.hierarchical, this.restBase, this.visibility, this.lLinks, }); TaxonomyCategory.fromJson(Map json) { name = json['name']; slug = json['slug']; capabilities = json['capabilities'] != null ? new Capabilities.fromJson(json['capabilities']) : null; description = json['description']; labels = json['labels'] != null ? new Labels.fromJson(json['labels']) : null; types = json['types'].cast(); showCloud = json['show_cloud']; hierarchical = json['hierarchical']; restBase = json['rest_base']; visibility = json['visibility'] != null ? new Visibility.fromJson(json['visibility']) : null; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['name'] = this.name; data['slug'] = this.slug; data['capabilities'] = this.capabilities?.toJson(); data['description'] = this.description; data['labels'] = this.labels?.toJson(); data['types'] = this.types; data['show_cloud'] = this.showCloud; data['hierarchical'] = this.hierarchical; data['rest_base'] = this.restBase; data['visibility'] = this.visibility?.toJson(); data['_links'] = this.lLinks?.toJson(); return data; } } class Visibility { bool? public; bool? publiclyQueryable; bool? showAdminColumn; bool? showInNavMenus; bool? showInQuickEdit; bool? showUi; Visibility({ this.public, this.publiclyQueryable, this.showAdminColumn, this.showInNavMenus, this.showInQuickEdit, this.showUi, }); Visibility.fromJson(Map json) { public = json['public']; publiclyQueryable = json['publicly_queryable']; showAdminColumn = json['show_admin_column']; showInNavMenus = json['show_in_nav_menus']; showInQuickEdit = json['show_in_quick_edit']; showUi = json['show_ui']; } Map toJson() { final Map data = new Map(); data['public'] = this.public; data['publicly_queryable'] = this.publiclyQueryable; data['show_admin_column'] = this.showAdminColumn; data['show_in_nav_menus'] = this.showInNavMenus; data['show_in_quick_edit'] = this.showInQuickEdit; data['show_ui'] = this.showUi; return data; } } class TaxonomyPostTag { String? name; String? slug; Capabilities? capabilities; String? description; Labels? labels; List? types; bool? showCloud; bool? hierarchical; String? restBase; Visibility? visibility; Links? lLinks; TaxonomyPostTag({ this.name, this.slug, this.capabilities, this.description, this.labels, this.types, this.showCloud, this.hierarchical, this.restBase, this.visibility, this.lLinks, }); TaxonomyPostTag.fromJson(Map json) { name = json['name']; slug = json['slug']; capabilities = json['capabilities'] != null ? new Capabilities.fromJson(json['capabilities']) : null; description = json['description']; labels = json['labels'] != null ? new Labels.fromJson(json['labels']) : null; types = json['types'].cast(); showCloud = json['show_cloud']; hierarchical = json['hierarchical']; restBase = json['rest_base']; visibility = json['visibility'] != null ? new Visibility.fromJson(json['visibility']) : null; lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['name'] = this.name; data['slug'] = this.slug; data['capabilities'] = this.capabilities?.toJson(); data['labels'] = this.labels?.toJson(); data['description'] = this.description; data['types'] = this.types; data['show_cloud'] = this.showCloud; data['hierarchical'] = this.hierarchical; data['rest_base'] = this.restBase; data['visibility'] = this.visibility?.toJson(); data['_links'] = this.lLinks?.toJson(); return data; } } ================================================ FILE: lib/schemas/title.dart ================================================ class Title { String? raw; String? rendered; Title({this.rendered}); Title.fromJson(Map json) { raw = json['raw']; rendered = json['rendered']; } Map toJson() { final Map data = new Map(); data['raw'] = this.raw; data['rendered'] = this.rendered; return data; } } ================================================ FILE: lib/schemas/user.dart ================================================ import 'avatar_urls.dart'; import 'links.dart'; class User { int? id; String? username; String? name; String? firstName; String? lastName; String? email; String? url; String? description; String? link; String? locale; String? nickname; String? slug; List? roles; String? registeredDate; UserCapabilities? capabilities; UserExtraCapabilities? extraCapabilities; AvatarUrls? avatarUrls; Map? meta; Links? lLinks; // yahya - @mymakarim String? password; // end yahya - @mymakarim User({ this.id, this.username, this.name, this.firstName, this.lastName, this.email, this.url, this.description, this.link, this.locale, this.nickname, this.slug, this.roles, this.registeredDate, this.capabilities, this.extraCapabilities, this.avatarUrls, this.meta, this.lLinks, this.password, }); User.fromJson(Map json) { id = json['id']; username = json['username']; name = json['name']; firstName = json['first_name']; lastName = json['last_name']; email = json['email']; url = json['url']; description = json['description']; link = json['link']; locale = json['locale']; nickname = json['nickname']; slug = json['slug']; if (json['roles'] != null) roles = json['roles'].cast(); registeredDate = json['registered_date']; capabilities = json['capabilities'] != null ? new UserCapabilities.fromJson(json['capabilities']) : null; extraCapabilities = json['extra_capabilities'] != null ? new UserExtraCapabilities.fromJson(json['extra_capabilities']) : null; avatarUrls = json['avatar_urls'] != null ? new AvatarUrls.fromJson(json['avatar_urls']) : null; if (json['meta'] != null && json['meta'].length > 0) { meta = new Map(); json['meta'].forEach((k, v) { meta![k] = v; }); } lLinks = json['_links'] != null ? new Links.fromJson(json['_links']) : null; } Map toJson() { final Map data = new Map(); data['id'] = this.id; data['username'] = this.username; data['name'] = this.name; data['first_name'] = this.firstName; data['last_name'] = this.lastName; data['email'] = this.email; data['url'] = this.url; data['description'] = this.description; data['link'] = this.link; data['locale'] = this.locale; data['nickname'] = this.nickname; data['slug'] = this.slug; data['roles'] = this.roles; data['registered_date'] = this.registeredDate; data['capabilities'] = this.capabilities?.toJson(); data['extra_capabilities'] = this.extraCapabilities?.toJson(); data['avatar_urls'] = this.avatarUrls?.toJson(); data['meta'] = this.meta; data['_links'] = this.lLinks?.toJson(); data['password'] = this.password; return data; } @override String toString() { return 'id: $id, name: $name'; } } class UserCapabilities { bool? switchThemes; bool? editThemes; bool? activatePlugins; bool? editPlugins; bool? editUsers; bool? editFiles; bool? manageOptions; bool? moderateComments; bool? manageCategories; bool? manageLinks; bool? uploadFiles; bool? import; bool? unfilteredHtml; bool? editPosts; bool? editOthersPosts; bool? editPublishedPosts; bool? publishPosts; bool? editPages; bool? read; bool? level10; bool? level9; bool? level8; bool? level7; bool? level6; bool? level5; bool? level4; bool? level3; bool? level2; bool? level1; bool? level0; bool? editOthersPages; bool? editPublishedPages; bool? publishPages; bool? deletePages; bool? deleteOthersPages; bool? deletePublishedPages; bool? deletePosts; bool? deleteOthersPosts; bool? deletePublishedPosts; bool? deletePrivatePosts; bool? editPrivatePosts; bool? readPrivatePosts; bool? deletePrivatePages; bool? editPrivatePages; bool? readPrivatePages; bool? deleteUsers; bool? createUsers; bool? unfilteredUpload; bool? editDashboard; bool? updatePlugins; bool? deletePlugins; bool? installPlugins; bool? updateThemes; bool? installThemes; bool? updateCore; bool? listUsers; bool? removeUsers; bool? promoteUsers; bool? editThemeOptions; bool? deleteThemes; bool? export; bool? administrator; UserCapabilities({ this.switchThemes, this.editThemes, this.activatePlugins, this.editPlugins, this.editUsers, this.editFiles, this.manageOptions, this.moderateComments, this.manageCategories, this.manageLinks, this.uploadFiles, this.import, this.unfilteredHtml, this.editPosts, this.editOthersPosts, this.editPublishedPosts, this.publishPosts, this.editPages, this.read, this.level10, this.level9, this.level8, this.level7, this.level6, this.level5, this.level4, this.level3, this.level2, this.level1, this.level0, this.editOthersPages, this.editPublishedPages, this.publishPages, this.deletePages, this.deleteOthersPages, this.deletePublishedPages, this.deletePosts, this.deleteOthersPosts, this.deletePublishedPosts, this.deletePrivatePosts, this.editPrivatePosts, this.readPrivatePosts, this.deletePrivatePages, this.editPrivatePages, this.readPrivatePages, this.deleteUsers, this.createUsers, this.unfilteredUpload, this.editDashboard, this.updatePlugins, this.deletePlugins, this.installPlugins, this.updateThemes, this.installThemes, this.updateCore, this.listUsers, this.removeUsers, this.promoteUsers, this.editThemeOptions, this.deleteThemes, this.export, this.administrator, }); UserCapabilities.fromJson(Map json) { switchThemes = json['switch_themes']; editThemes = json['edit_themes']; activatePlugins = json['activate_plugins']; editPlugins = json['edit_plugins']; editUsers = json['edit_users']; editFiles = json['edit_files']; manageOptions = json['manage_options']; moderateComments = json['moderate_comments']; manageCategories = json['manage_categories']; manageLinks = json['manage_links']; uploadFiles = json['upload_files']; import = json['import']; unfilteredHtml = json['unfiltered_html']; editPosts = json['edit_posts']; editOthersPosts = json['edit_others_posts']; editPublishedPosts = json['edit_published_posts']; publishPosts = json['publish_posts']; editPages = json['edit_pages']; read = json['read']; level10 = json['level_10']; level9 = json['level_9']; level8 = json['level_8']; level7 = json['level_7']; level6 = json['level_6']; level5 = json['level_5']; level4 = json['level_4']; level3 = json['level_3']; level2 = json['level_2']; level1 = json['level_1']; level0 = json['level_0']; editOthersPages = json['edit_others_pages']; editPublishedPages = json['edit_published_pages']; publishPages = json['publish_pages']; deletePages = json['delete_pages']; deleteOthersPages = json['delete_others_pages']; deletePublishedPages = json['delete_published_pages']; deletePosts = json['delete_posts']; deleteOthersPosts = json['delete_others_posts']; deletePublishedPosts = json['delete_published_posts']; deletePrivatePosts = json['delete_private_posts']; editPrivatePosts = json['edit_private_posts']; readPrivatePosts = json['read_private_posts']; deletePrivatePages = json['delete_private_pages']; editPrivatePages = json['edit_private_pages']; readPrivatePages = json['read_private_pages']; deleteUsers = json['delete_users']; createUsers = json['create_users']; unfilteredUpload = json['unfiltered_upload']; editDashboard = json['edit_dashboard']; updatePlugins = json['update_plugins']; deletePlugins = json['delete_plugins']; installPlugins = json['install_plugins']; updateThemes = json['update_themes']; installThemes = json['install_themes']; updateCore = json['update_core']; listUsers = json['list_users']; removeUsers = json['remove_users']; promoteUsers = json['promote_users']; editThemeOptions = json['edit_theme_options']; deleteThemes = json['delete_themes']; export = json['export']; administrator = json['administrator']; } Map toJson() { final Map data = new Map(); data['switch_themes'] = this.switchThemes; data['edit_themes'] = this.editThemes; data['activate_plugins'] = this.activatePlugins; data['edit_plugins'] = this.editPlugins; data['edit_users'] = this.editUsers; data['edit_files'] = this.editFiles; data['manage_options'] = this.manageOptions; data['moderate_comments'] = this.moderateComments; data['manage_categories'] = this.manageCategories; data['manage_links'] = this.manageLinks; data['upload_files'] = this.uploadFiles; data['import'] = this.import; data['unfiltered_html'] = this.unfilteredHtml; data['edit_posts'] = this.editPosts; data['edit_others_posts'] = this.editOthersPosts; data['edit_published_posts'] = this.editPublishedPosts; data['publish_posts'] = this.publishPosts; data['edit_pages'] = this.editPages; data['read'] = this.read; data['level_10'] = this.level10; data['level_9'] = this.level9; data['level_8'] = this.level8; data['level_7'] = this.level7; data['level_6'] = this.level6; data['level_5'] = this.level5; data['level_4'] = this.level4; data['level_3'] = this.level3; data['level_2'] = this.level2; data['level_1'] = this.level1; data['level_0'] = this.level0; data['edit_others_pages'] = this.editOthersPages; data['edit_published_pages'] = this.editPublishedPages; data['publish_pages'] = this.publishPages; data['delete_pages'] = this.deletePages; data['delete_others_pages'] = this.deleteOthersPages; data['delete_published_pages'] = this.deletePublishedPages; data['delete_posts'] = this.deletePosts; data['delete_others_posts'] = this.deleteOthersPosts; data['delete_published_posts'] = this.deletePublishedPosts; data['delete_private_posts'] = this.deletePrivatePosts; data['edit_private_posts'] = this.editPrivatePosts; data['read_private_posts'] = this.readPrivatePosts; data['delete_private_pages'] = this.deletePrivatePages; data['edit_private_pages'] = this.editPrivatePages; data['read_private_pages'] = this.readPrivatePages; data['delete_users'] = this.deleteUsers; data['create_users'] = this.createUsers; data['unfiltered_upload'] = this.unfilteredUpload; data['edit_dashboard'] = this.editDashboard; data['update_plugins'] = this.updatePlugins; data['delete_plugins'] = this.deletePlugins; data['install_plugins'] = this.installPlugins; data['update_themes'] = this.updateThemes; data['install_themes'] = this.installThemes; data['update_core'] = this.updateCore; data['list_users'] = this.listUsers; data['remove_users'] = this.removeUsers; data['promote_users'] = this.promoteUsers; data['edit_theme_options'] = this.editThemeOptions; data['delete_themes'] = this.deleteThemes; data['export'] = this.export; data['administrator'] = this.administrator; return data; } } class UserExtraCapabilities { bool? administrator; UserExtraCapabilities({this.administrator}); UserExtraCapabilities.fromJson(Map json) { administrator = json['administrator']; } Map toJson() { final Map data = new Map(); data['administrator'] = this.administrator; return data; } } ================================================ FILE: lib/schemas/wordpress_error.dart ================================================ /// All API related errors are thrown as an object of this class. class WordPressError { String? code; String? message; Data? data; WordPressError({ this.code, this.message, this.data, }); WordPressError.fromJson(Map json) { code = json['code']; message = json['message']; data = json['data'] != null ? new Data.fromJson(json['data']) : null; } Map toJson() { final Map data = new Map(); data['code'] = this.code; data['message'] = this.message; data['data'] = this.data?.toJson(); return data; } @override String toString() { return 'WordPress Error! code: $code, message: $message, status: ${data == null ? null : data?.status}'; } } class Data { int? status; Data({this.status}); Data.fromJson(Map json) { status = json['status']; } Map toJson() { final Map data = new Map(); data['status'] = this.status; return data; } } ================================================ FILE: pubspec.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.3.0-nullsafety.0 authors: - Sachin Ganesh - Suraj Shettigar - Harm-Jan Roskam - Yahya Makarim - Oladapo Adeola Omonayajo homepage: https://github.com/dreamsoftin/flutter_wordpress environment: sdk: '>=2.12.0-29.7.beta <3.0.0' dependencies: http: ^0.13.4