Warning: Trying to access array offset on value of type null in /home/customer/www/mozartec.com/public_html/wp-content/plugins/pressapps-login-access/includes/skelet/path.php on line 408
Flutter Fetch Posts From WordPress (Part 1) - Mozartec
Mozart Al Khateeb

Full Stack

Mobile

.Net Developer

ERP Developer

Mozart Al Khateeb

Full Stack

Mobile

.Net Developer

ERP Developer

Blog Post

Flutter Fetch Posts From WordPress (Part 1)

Flutter Fetch Posts From WordPress (Part 1)

In this post I will apply what I’ve learned about flutter so far by creating a simple app that display posts from WordPress rest API. You can find out more about this API by visiting this Link

I’ve chosen WordPress API because I already have a blog but you can use any open API you want like Hacker News API or simply create your own API.

Create a flutter project

flutter create mozartec_flutter_wordpress 
code . //to open project in vs code

We are going to use a StatefulWidget instead of a
StatelessWidget in order to maintain the State of the App and be able to render the posts once we receive them from the API.

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: MyHomePage()));
} //App Entry Point

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Mozartec'),
        backgroundColor: Colors.blueAccent,
      ),
      body: Text('Posts go here'),
    );
  }
}

Fetch Posts

I’m going to use flutter_wordpress which is a nice plugin that make access to the rest API simpler, find your pubspec.yaml in the root of your project and add the flutter_wordpress: ^0.1.4 under cupertino_icons: ^0.1.2 , then add the following imports at the top of the file and replace _root with your site URL.

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

final _root = 'https://mozartec.com'; //replace with your site url
final wp.WordPress wordPress = wp.WordPress(baseUrl: _root);
  List<wp.Post> posts;
  Future<List<wp.Post>> fetchPosts() async {
    var posts = wordPress.fetchPosts(
      postParams: wp.ParamsPostList(
        context: wp.WordPressContext.view,
        postStatus: wp.PostPageStatus.publish,
        orderBy: wp.PostOrderBy.date,
        order: wp.Order.desc,
      ),
      fetchAuthor: true,
      fetchFeaturedMedia: true,
      fetchComments: true,
      fetchCategories: true,
      fetchTags: true,
    );
    return posts;
  }

Load posts on the initState method

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

  Future<String> getPosts() async {
    var res = await fetchPosts();
    setState(() {
      posts = res;
    });
    return "Success!";
  }

Building List Widget

  Widget buildPost(int index) {
    return Column(
      children: <Widget>[
        Card(
          child: Column(
            children: <Widget>[
              buildImage(index),
              Padding(
                padding: EdgeInsets.all(10.0),
                child: ListTile(
                  title: Padding(
                      padding: EdgeInsets.symmetric(vertical: 10.0),
                      child: Text(posts[index].title.rendered)),
                  subtitle: Text(posts[index].excerpt.rendered),
                ),
              )
            ],
          ),
        )
      ],
    );
  }

  Widget buildImage(int index) {
    if (posts[index].featuredMedia == null) {
      return Image.network(
        'https://mozartec.com/wp-content/uploads/2019/04/asp-dot-net-core.jpg',
      );
    }
    return Image.network(
      posts[index].featuredMedia.mediaDetails.sizes.medium.sourceUrl,
    );
  }

Replace Text(‘Posts go here’) with ListView.builder

      body: ListView.builder(
        itemCount: posts == null ? 0 : posts.length,
        itemBuilder: (BuildContext context, int index) {
          return buildPost(index);//Building the posts list view
        },

And that’s it, hope you find this post useful. you can find the code for this post on GitHub

Taggs:
4 Comments
  • Kar Kar 4:18 am August 23, 2020 Reply

    where is part 2 ? && then NExt post

    • Mozart Al Khateeb 7:14 pm October 18, 2020 Reply

      Hello I’ve created part 2 adding the filter by category option. do you have something specific that you’d like me to implement ?

  • ARUSHI GOYAL 6:28 am September 1, 2020 Reply

    How we fetch the category?

    • Mozart Al Khateeb 7:12 pm October 18, 2020 Reply

      Hello I’ve created part 2 adding the filter by category option.

Write a comment