Tutorial Membuat Aplikasi Blog Flutter Backend WordPress API

Artikel kali ini akan membahas bagaimana membuat aplikasi blog sederhana menggunakan flutter dengan menggunakan wordpress sebagai API-nya, studi kasus kali ini menggunakan backend https://belajarflutter.com/,

flutter create blogwp

createflutterproject
create flutter project

main.dart

Ubah bagian main.dart pada folder lib

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  
  const MyHomePage({ Key? key,  }) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('belajarflutterapp'),
      ),
    );
  }
}

Add Dependency

lalu kita siapkan package yang dibutuhkan dengan menggunakan shortcut ctrl + shift + P, tampilannya akan seperti di bawah ini :

httppackage
Dart :add dependency

Function Get

Selanjutnya kita akan membuat function / fungsi yang berfungsi untuk mengirimkan permintaan ke aplikasi mobile yang ingin kita buat.

Future<List> getPosts() async {
    var response = await http.get(
      Uri.parse("https://belajarflutter.com/wp-json/wp/v2/posts?_embed"),
      headers: {
        "Accept": "application/json",
      },
    );

    return jsonDecode(response.body);
  }

initstate

lalu tambahkan function getPosts ke dalam void initstate

void initState() {
    getPosts();
    super.initState();
  }

Untuk full code nya di atas ada di bawah ini :

import 'dart:convert';

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future<List> getPosts() async {
    var response = await http.get(
      Uri.parse("https://belajarflutter.com/wp-json/wp/v2/posts?_embed"),
      headers: {
        "Accept": "application/json",
      },
    );

    return jsonDecode(response.body);
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'BelajarFlutterApps',
        ),
      ),
      body: FutureBuilder(
        future: getPosts(),
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, index) {
                Map posts = snapshot.data[index];
                return Text(posts['title']['rendered']);
             
            });
          }
          return CircularProgressIndicator();
        },
      ),
    );
  }
}

Output Sementara

outputsementara
output sementara

Next Step

langkah selanjutnya kita akan tampung datanya di dalam column dan sedikit merapikan user interfacenya

Column

import 'dart:convert';

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future<List> getPosts() async {
    var response = await http.get(
      Uri.parse("https://belajarflutter.com/wp-json/wp/v2/posts?_embed"),
      headers: {
        "Accept": "application/json",
      },
    );

    return jsonDecode(response.body);
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'BelajarFlutterApps',
        ),
      ),
      body: FutureBuilder(
        future: getPosts(),
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {
                  Map posts = snapshot.data[index];
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        posts['title']['rendered'],
                        style: TextStyle(
                          fontSize: 20.0,
                          color: Colors.blueAccent,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  );
                });
          }
          return CircularProgressIndicator();
        },
      ),
    );
  }
}
2

Card dan Padding

tambahkan card dan padding pada desain yang kita buat

cardandpadding
import 'dart:convert';

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future<List> getPosts() async {
    var response = await http.get(
      Uri.parse("https://belajarflutter.com/wp-json/wp/v2/posts?_embed"),
      headers: {
        "Accept": "application/json",
      },
    );

    return jsonDecode(response.body);
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'BelajarFlutterApps',
        ),
      ),
      body: FutureBuilder(
        future: getPosts(),
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {
                  Map posts = snapshot.data[index];
                  return Card(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            posts['title']['rendered'],
                            style: TextStyle(
                              fontSize: 20.0,
                              color: Colors.blueAccent,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                });
          }
          return CircularProgressIndicator();
        },
      ),
    );
  }
}
screenshot 2021 12 24 14.35.04.458
output code yang kita ubah

Tampilkan Gambar

return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {
                  Map posts = snapshot.data[index];
                  return Card(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Image.network(
                            posts['_embedded']['wp:featuredmedia'][0]
                                ['source_url'],
                          ),
                          Text(
                            posts['title']['rendered'],
                            style: TextStyle(
                              fontSize: 20.0,
                              color: Colors.blueAccent,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                });

Output finalnya adalah seperti di bawah ini :

outputdone

Full Code

import 'dart:convert';

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future<List> getPosts() async {
    var response = await http.get(
      Uri.parse("https://belajarflutter.com/wp-json/wp/v2/posts?_embed"),
      headers: {
        "Accept": "application/json",
      },
    );

    return jsonDecode(response.body);
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'BelajarFlutterApps',
        ),
      ),
      body: FutureBuilder(
        future: getPosts(),
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {
                  Map posts = snapshot.data[index];
                  return Card(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Image.network(
                            posts['_embedded']['wp:featuredmedia'][0]
                                ['source_url'],
                          ),
                          Text(
                            posts['title']['rendered'],
                            style: TextStyle(
                              fontSize: 20.0,
                              color: Colors.blueAccent,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                });
          }
          return CircularProgressIndicator();
        },
      ),
    );
  }
}

Sumber

https://belajarflutter.com/http-request-cara-get-data-api-di-flutter/

Default image
Herry Prasetyo
Today a reader Tomorrow a Leader
Articles: 23

Leave a Reply