Build Android application using Flutter and WordPress API

I know Flutter framework is still in beta but it doesn’t mean it’s too early to learn some basics. This is first part of tutorial series in which I’ll show you guys how to build Android application using Flutter and WordPress API. As developer you will be working with many clients which already have WordPress website. Only thing they are missing is Android or iOS application. They want to have access to latest news from their website in their mobile application. This is easy thing to do with WordPress API and Flutter framework.



According to W3Techs, WordPress powers 30.0% of all the websites on the Internet, including those without a content management system (CMS) or with a custom-coded CMS. And if you limit the data set to only websites with a known CMS, WordPress’ market share gets even more dominant. In that case, WordPress holds a 60.2% market share for content management systems on websites with a known CMS.

Inclusion of WordPress API to core WordPress package marks major point for WordPress and it turns it to real application platform. There are four core reasons why the REST API is an absolute game changer: removes WordPress’s reliance on PHP, raises the possibility of true mobile integration, untethers the front end, opens the door for a reimagining of the back end.

In this tutorial I will demonstrate second reason, mobile integration. Virtuooza.com is also powered by WordPress and I will use our API to show you guys how to build Android application using Flutter and WordPress API.

Part 1

Application structure

State is information that can be read synchronously when the widget is built and might change during the lifetime of the widget. It is the responsibility of the widget implementer to ensure that the State is promptly notified when such state changes, using State.setState.

I’m using Statefull widget for our VirtuoozaHome page so I can update it’s state when new posts are fetched from WordPress API. I also set apiUrl (WordPress API URL) which will be called to get results from our api. I added empty posts List which will contain all our posts when they are fetched from API.

main.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() {
  runApp(MaterialApp(
      home: VirtuoozaHome()
  ));
}

class VirtuoozaHome extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => VirtuoozaHomeState();
}

class VirtuoozaHomeState extends State<VirtuoozaHome> {

  // Base URL for our wordpress API
  final String apiUrl = "https://virtuooza.com/wp-json/wp/v2/";
  // Empty list for our posts
  List posts;
}
Fetch posts

I defined function getPosts() which will trigger our GET http request to API and return response. We need to decode response body with json.decode(res.body), add response objects in our posts List and update it’s state.

main.dart -> class VirtuoozaHomeState
 // Function to fetch list of posts
   Future<String> getPosts() async {

    var res = await http.get(Uri.encodeFull(apiUrl + "posts?_embed"), headers: {"Accept": "application/json"});

    // fill our posts list with results and update state
    setState(() {
      var resBody = json.decode(res.body);
      posts = resBody;
    });

    return "Success!";
  }

To trigger our getPosts() function when our application starts we will add initState override in our VirtuoozaHomeState class.

main.dart -> class VirtuoozaHomeState
  @override
  void initState() {
    super.initState();
    this.getPosts();
  }
Build application view

Now when I have function to fetch posts from API and my posts in List I want to show them in ListView and nice post Cards.

main.dart -> class VirtuoozaHomeState
@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Virtuooza"),
        backgroundColor: Colors.blueAccent
      ),
      body: ListView.builder(
        itemCount: posts == null ? 0 : posts.length,
        itemBuilder: (BuildContext context, int index) {
          return Column(
            children: <Widget>[
              Card(
                child: Column(
                  children: <Widget>[
                    new Image.network(posts[index]["_embedded"]["wp:featuredmedia"][0]["source_url"]),
                    new Padding(
                      padding: EdgeInsets.all(10.0),
                      child: new ListTile(
                        title: new Padding(
                             padding: EdgeInsets.symmetric(vertical: 10.0), 
                             child: new Text(posts[index]["title"]["rendered"])),
                        subtitle: new Text(
                           posts[index]["excerpt"]["rendered"].replaceAll(new RegExp(r'<[^>]*>'), '')
                       ),
                      ),
                    )
                  ],
                ),
              )
            ],
          );
        },
      ),
    );
   }

preview

In ListView.builder I check if posts are null (not fetched) and if they are null I set

itemCount to 0. If posts are fetched I set itemCount to posts.length.

To show our posts featured image in our Card widget I’m using Image.network(posts[index][“_embedded”][“wp:featuredmedia”][0][“source_url”]) and passing it image url fetched from WordPress API.

If you worked with WordPress API before then you know that API response for title, content or excerpt contains html tags. I removed tags from string by using posts[index][“excerpt”][“rendered”].replaceAll(new RegExp(r'<[^>]*>’), ”), not sure if this is the best way but it worked for me.

Now you can run your application in android emulator or your phone and test it. You should see list of posts displayed in nice Card widgets similar to my screenshot here.

Ok guys this is all for the first part of this build android application using flutter and wordpress api tutorial. I hope you guys learned how to send http get call to WordPress API, fetch posts and display them in nice Cards. Please check full code bellow and ask for help if you need it.

main.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() {
  runApp(MaterialApp(
      home: VirtuoozaHome()
  ));
}

class VirtuoozaHome extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => VirtuoozaHomeState();
}

class VirtuoozaHomeState extends State<VirtuoozaHome> {

  // Base URL for our wordpress API
  final String apiUrl = "https://virtuooza.com/wp-json/wp/v2/";
  // Empty list for our posts
  List posts;

  // Function to fetch list of posts
   Future<String> getPosts() async {

    var res = await http.get(Uri.encodeFull(apiUrl + "posts?_embed"), headers: {"Accept": "application/json"});

    // fill our posts list with results and update state
    setState(() {
      var resBody = json.decode(res.body);
      posts = resBody;
    });

    return "Success!";
  }

  @override
  void initState() {
    super.initState();
    this.getPosts();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Virtuooza"),
        backgroundColor: Colors.blueAccent
      ),
      body: ListView.builder(
        itemCount: posts == null ? 0 : posts.length,
        itemBuilder: (BuildContext context, int index) {
          return Column(
            children: <Widget>[
              Card(
                child: Column(
                  children: <Widget>[
                    new Image.network(posts[index]["_embedded"]["wp:featuredmedia"][0]["source_url"]),
                    new Padding(
                      padding: EdgeInsets.all(10.0),
                      child: new ListTile(
                        title: new Padding(
                             padding: EdgeInsets.symmetric(vertical: 10.0), 
                             child: new Text(posts[index]["title"]["rendered"])),
                        subtitle: new Text(
                           posts[index]["excerpt"]["rendered"].replaceAll(new RegExp(r'<[^>]*>'), '')
                       ),
                      ),
                    )
                  ],
                ),
              )
            ],
          );
        },
      ),
    );
  }
}
Continue reading

Build Android Application using Flutter and WordPress API Part 2

Share with your friends