So I wanted to make an app for our website and well, it turns out it was easier than I thought.
Step 1: Download & Activate Plugin For Wordpress Blog
Link: https://wordpress.org/plugins/easily-generate-rest-api-url/
Step 2: In the Wordpress dashboard
Go to settings (hover over it) > (Click on) Generate Rest API Url, scroll to the bottom you will have an api url. You can modify it if you want.
Step 3: Create a Flutter Project
If you didn't already, install and setup Flutter from flutter.dev
I used vs code but you can use Android studio as well. It will work just the same.
Step 4: Create functions to fetch posts and post image url
Create a file named wp-api.dart and then add http package, and add this function:
Future<List> fetchWpPosts() async {
final response = await http.get(
"https://flutternerd.com/index.php/wp-json/wp/v2/posts",
headers: {"Accept": "application/json"});
var convertDatatoJson = jsonDecode(response.body);
return convertDatatoJson;
}
Step 5: Create frontend and use this function by importing the file
import 'package:flutter/material.dart';
import 'package:nativewordpress/views/PostPage.dart';
import 'package:nativewordpress/wp-api.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
String removeAllHtmlTags(String htmlText) {
RegExp exp = RegExp(r"<[^>]*>", multiLine: true, caseSensitive: true);
return htmlText.replaceAll(exp, '');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("FlutterNerd"),
),
body: Container(
padding: EdgeInsets.only(top: 24),
child: FutureBuilder(
future: fetchWpPosts(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
Map wppost = snapshot.data[index];
return PostTile(
imageApiUrl: wppost['_links']["wp:featuredmedia"][0]
["href"],
excerpt: removeAllHtmlTags(wppost['excerpt']['rendered']
.replaceAll("’", "")),
desc: wppost['content']['rendered'],
title: wppost['title']['rendered']
.replaceAll("#038;", ""));
});
}
return Center(child: CircularProgressIndicator());
},
),
),
);
}
}
class PostTile extends StatefulWidget {
final String imageApiUrl, title, desc, excerpt;
PostTile({this.imageApiUrl, this.title, this.desc, this.excerpt});
@override
_PostTileState createState() => _PostTileState();
}
class _PostTileState extends State<PostTile> {
String imageUrl = "";
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
if (imageUrl != "") {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PostPage(
title: widget.title,
imageUrl: imageUrl,
desc: widget.desc,
)));
}
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FutureBuilder(
future: fetchWpPostImageUrl(widget.imageApiUrl),
builder: (context, snapshot) {
if (snapshot.hasData) {
imageUrl = snapshot.data["guid"]["rendered"];
return Image.network(imageUrl);
}
return Center(child: CircularProgressIndicator());
}),
SizedBox(height: 8),
Text(
widget.title,
style: TextStyle(fontSize: 16),
),
SizedBox(height: 5),
Text(widget.excerpt)
],
),
),
);
}
}
Step 6: We will need to create a separate function to get the image url of each post
fetchWpPostImageUrl(url) async {
final response = await http.get(url, headers: {"Accept": "application/json"});
var convertDatatoJson = jsonDecode(response.body);
return convertDatatoJson;
}
Step 7: Now let’s create a post page
We need to add flutter_html_view package then
import 'package:flutter/material.dart';
import 'package:flutter_html_view/flutter_html_view.dart';
class PostPage extends StatefulWidget {
final String imageUrl, title, desc;
PostPage({this.title, this.desc, this.imageUrl});
@override
_PostPageState createState() => _PostPageState();
}
class _PostPageState extends State<PostPage> {
Widget postContent(htmlContent) {
return HtmlView(
data: htmlContent, // optional, type String
onLaunchFail: (url) {
// optional, type Function
print("launch $url failed");
},
scrollable: false,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
widget.imageUrl != null
? Image.network(widget.imageUrl)
: Container(),
SizedBox(height: 8),
Text(
widget.title,
style: TextStyle(fontSize: 18),
),
SizedBox(height: 6),
postContent(
widget.desc,
)
],
),
),
),
);
}
}
That's it!
And that is how we can build an android and ios app for your WordPress blog. If you face any problems feel free to comment down below.
Originally published at FlutterNerd.com