# Example App: Flutter

Let's gooooooooo

# 1. Introduction

Follow this tutorial to learn how to embed the Inkey microwallet as a WebView in a simple Flutter mobile app! We will be setting up Javascript channels to interact with the microwallet.

Let’s get started!

# 2. Set up your Flutter environment

For this tutorial, you’ll need an environment setup that supports Flutter development. Feel free to reference the official Flutter documentation to get started. Make sure you have any of the following prerequisites:

  • A physical Android or iOS device connected to your computer
  • iOS simulator (via Xcode tools)
  • Android emulator (via Android Studio)

You can confirm that your desired emulator or device is connected by verifying it is listed in the result of running flutter devices in your terminal.

# 3. Create the starter Flutter app

Start by creating a starter Flutter app called hello_inkey.

$ flutter create hello_inkey
$ cd hello_inkey

Using your choice code editor, replace the code from lib/main.dart with the following code-block to display “Hello Inkey!” in the center of your screen:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
 
void main() {
 runApp(const InkeyDemo());
}
 
class InkeyDemo extends StatelessWidget {
 const InkeyDemo({Key? key}) : super(key: key);
 
 // This widget is the root of your application.
 @override
 Widget build(BuildContext context) {
   return const CupertinoApp(
     title: 'Flutter meets Inkey',
     theme: CupertinoThemeData(
       primaryColor: Colors.blueGrey,
     ),
     home: HomePage(title: 'Flutter meets Inkey'),
   );
 }
}
 
class HomePage extends StatefulWidget {
 const HomePage({Key? key, required this.title}) : super(key: key);
 
 final String title;
 
 @override
 State<HomePage> createState() => _HomePageState();
}
 
class _HomePageState extends State<HomePage> {
 @override
 Widget build(BuildContext context) {
   return CupertinoPageScaffold(
       navigationBar: CupertinoNavigationBar(middle: Text(widget.title)),
       child: Center(
         child: Column(
           mainAxisAlignment: MainAxisAlignment.center,
           children: const <Widget>[
             Text(
               "Hello Inkey!",
             )
           ],
         ),
       ));
 }
}

You can run your app on your desired device or emulator by the following command in your terminal: flutter run -d {id of desired device or emulator}

# 4. Inkey as a WebView

We will be utilizing the webview_flutter Flutter plugin, which will allow us to embed the Inkey microwallet webpage. The WebView widget allows developers to create Javascript channels, which we will use to directly communicate with the Inkey microwallet.

First, install the webview_flutter Flutter package: flutter pub add webview_flutter

Next, download this example web_view_stack.dart file and place it into your /lib folder.

Also, download the inkey_builders.dart file that defines helpful builder methods to create messages that we can send to the Inkey microwallet. This file uses the uuid package, which can be installed with this command: flutter pub add uuid

Take a closer look at the web_view_stack.dart file and notice that we are creating a Javascript channel called inkey. This specifies a message channel between our Flutter app and the Inkey microwallet webpage we are displaying within the WebView widget.

  Set<JavascriptChannel> _createJavascriptChannels(BuildContext context) {
    return {
      JavascriptChannel(
        name: 'inkey',
        onMessageReceived: (message) async {
        ...
        },
      ),
    };
  }

In the build() function of web_view_stack.dart, notice that we are adding an event listener which listens for messages from the Inkey microwallet origin and posts them to the inkey Javascript channel that we created above.

  @override
  Widget build(BuildContext context) {
    return WebView(
    ...
      onPageFinished: (url) async {
        debugPrint("Page load finished: $url");
        final completedController = await widget.controller.future;
        completedController
            .runJavascript('''window.addEventListener('message', (event) => {
      if (event.origin !== "https://hippoz.web.app") return;
      inkey.postMessage(JSON.stringify(event.data));
    }, false);

    let data = {};''');
    ...
    );
  }

We are also sending a set-app message to the window to set the microwallet's appCode, which looks like this in JSON form:

{
    "source": 'ncc-inkey-client', 
    "async": true,
    "type": 'set-app',
    "uuid": 'random uuid here',
    "payload": {
        "appCode": 'app code here'
    }
}
  @override
  Widget build(BuildContext context) {
    return WebView(
    ...
      onPageFinished: (url) async {
    ...

        String appCode = "inkey-demo"; // appCode can be any string
        String data = InkeyBuilders.buildSetAppMessage(appCode);
        completedController.runJavascript('''data = $data
window.postMessage(data, "https://hippoz.web.app");''');
        debugPrint("Ran initial javascript on completed controller");
      },
      javascriptMode: JavascriptMode.unrestricted,
      javascriptChannels: _createJavascriptChannels(context),
    );
  }

# Embedding Inkey into your app

Let's now integrate our WebViewStack widget into our Flutter app. Simply initialize a WebViewController, define the url of the Inkey microwallet, and instantiate our WebViewStack component as an additional widget in our Flutter app's home page scaffold.

class _HomePageState extends State<HomePage> {
  final controller = Completer<WebViewController>();
  final url = "https://hippoz.web.app";

...

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
...
        child: Center(
            child: SafeArea(
                child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              "Hello Inkey!",
            ),
            Expanded(child: WebViewStack(controller: controller, url: url))
          ],
        ))));
  }
}

To run the app

  • Build the application bundle for iOS: flutter build ios
  • Run the app on your desired device or emulator: flutter run -d {device-id}
  • If you use the flutter run command, Ctrl+R is available for hot reloading

Refer to the source code of our simple Inkey + Flutter integration: https://github.com/thencc/inkey-flutter-demo

# 5. Next steps

Congratulations!

You have completed an introduction of embedding the Inkey microwallet to a mobile Flutter app! Stay tuned for further extensions of Inkey. In the meantime, if you find issues we can improve, head over here to file an issue.