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 if 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:
Write a comment