Create a wordpress App using Flutter part-3 - Robert's Blog

Create a wordpress App using Flutter part-3

By Robby 0 Comment July 9, 2020

In this we can show the pages available in WordPress and open it in the WebView inside the Flutter App.

Initialize the list page

  List pages;

Call the API to get page details

  Future<String> getPages() async {
    var pageres = await http.get(Uri.encodeFull(apiUrl + "pages"),
        headers: {"Accept": "application/json"});

    setState(() {
      var resPageBody = json.decode(pageres.body);
      pages = resPageBody;
    });
    return "Success!";
  }

Initialize in the initState

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

Create an App drawer using drawer function

 Drawer(
          child: pages == null
              ? CircularProgressIndicator()
              : ListView.builder(
                  itemCount: pages == null ? 0 : pages.length,
                  itemBuilder: (BuildContext context, int index) {
                    return ListTile(
                      title: Text(
                        pages[index]["title"]["rendered"],
                        style: new TextStyle(
                            fontSize: 18.0, fontWeight: FontWeight.w400),
                      ),
                      onTap: () {
                        Navigator.push(
                          context,
                          new MaterialPageRoute(
                            builder: (context) =>
                                new PageScreen(url: pages[index]),
                          ),
                        );
                      },
                    );
                  }),
        ),

For WebView in Flutter we need to install webview_flutter in pubspec.yaml

webview_flutter: ^0.3.22+1

Create a new page to show the pages in WebView.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class PageScreen extends StatefulWidget {
  var url;
  PageScreen({Key key, @required var this.url}) : super(key: key);

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

class _PageScreenState extends State<PageScreen> {
  final Completer<WebViewController> _controller =
      Completer<WebViewController>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.url['title']['rendered']),
      ),
      body: WebView(
        initialUrl: widget.url['link'],
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController webViewController) {
          _controller.complete(webViewController);
        },
      ),
    );
  }
}

The full Source Code is in Github https://github.com/Robertrobinson777/flutterblog

Add Comment

Your email address will not be published.