Create a Wear OS app using Flutter

Create a Wear OS app using Flutter

In this article, you'll learn how to build a Wear OS (Android Wear) app using Flutter

Setup

To build a Wear OS app, we also have to do a lot to modifications as well as additions to the android part of the Flutter app, which is really a very tedious process, so bear with me.

I am again stating the setup process below (not recommended):

App Gradle File

Change the min SDK version to API 23:

minSdkVersion 23

App Gradle File

Then, add the following dependencies to the Android Gradle file for the app:

dependencies {
 // Wear libraries
 implementation 'com.android.support:wear:27.1.1'
 implementation 'com.google.android.support:wearable:2.3.0'
 compileOnly 'com.google.android.wearable:wearable:2.3.0'
}

App Gradle File

Manifest File

Add the following to your AndroidManifest.xml file:

<!-- Required for ambient mode support -->
<uses-permission android:name="android.permission.WAKE_LOCK" />

<!-- Flags the app as a Wear app -->
<uses-feature android:name="android.hardware.type.watch" />

<!-- Flags that the app doesn't require a companion phone app -->
<application>
<meta-data
    android:name="com.google.android.wearable.standalone"
    android:value="true" />
</application>

AndroidManifest.xml

Update Android’s MainActivity

The ambient mode widget needs some initialization in Android’s MainActivity code. Update your code as follows:

class MainActivity: FlutterActivity(), AmbientMode.AmbientCallbackProvider {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    GeneratedPluginRegistrant.registerWith(this)

    // Wire up the activity for ambient callbacks
    AmbientMode.attachAmbientSupport(this)
  }

  override fun getAmbientCallback(): AmbientMode.AmbientCallback {
    return FlutterAmbientCallback(getChannel(flutterView))
  }
}

Android’s MainActivity

So, after the setup is complete let’s dive into the best part that is coding.

Implementation

Before diving into the real coding part, let’s see what are the plugins required and also import the assets required in this project.

Plugins:

The plugins used for this project are:

  1. wear (for using the Wear OS optimized widgets)
  2. audioplayers (to use audio playback in the app)
dependencies:
  audioplayers: ^0.7.8
  wear: ^0.0.3

Assets:

The images, icons, audio files, as well as the system material icons, are included in the assets folder, which you can download by going to the Google Drive

I will tell you in a minute why I have included the system material icons in the assets folder by downloading them from the Material Design Website, although as you might know all of the material design icons are integrated with Flutter for direct use.

Don’t forget to import these in your “pubspec.yaml” file.

Coding Part

main.dart

First of all, import the packages that are required in the “main.dart” file.

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

The wear plugin gives three types of widgets:

  • WatchShape: determines whether the watch is square or round.
  • InheritedShape: an InheritedWidget that can be used to pass the shape of the watch down the widget tree.
  • AmbientMode: builder that provides what mode the watch is in. The widget will rebuild whenever the watch changes mode.

We will require all these widgets in the “main.dart” file.

The Wear OS has two modes:

  1. Normal Mode
  2. Ambient Mode

So, when the Wear OS is in the normal mode we will show the real content of the app and when it is in the ambient mode we will show a screen with a dark background, which will help to save battery.

After adding all these, our “main.dart” file will look like this:

import 'package:flutter/material.dart';
import 'package:flutter_os/screens/ambient_screen.dart';
import 'package:flutter_os/screens/start_screen.dart';
import 'package:wear/wear.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) => MaterialApp(
        title: 'Flutter Wear App',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: WatchScreen(),
        debugShowCheckedModeBanner: false,
      );
}

class WatchScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) => WatchShape(
        builder: (context, shape) => InheritedShape(
              shape: shape,
              child: AmbientMode(
                builder: (context, mode) =>
                    mode == Mode.active ? StartScreen() : AmbientWatchFace(),
              ),
            ),
      );
}

ambient_screen.dart

Next, we will design the UI of the ambient screen of the watch.

The final Ambient screen will look like this:

Ambient Screen

As you can tell from the screenshot that we have to add a Scaffold (set the background color to black) with a Column containing two widgets:

  1. Text widget (set text color to blue)
  2. FlutterLogo widget

So, the completed ambient screen code will look like this:

import 'package:flutter/material.dart';

class AmbientWatchFace extends StatelessWidget {
  @override
  Widget build(BuildContext context) => Scaffold(
        backgroundColor: Colors.black,
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                'FlutterOS',
                style: TextStyle(color: Colors.blue[600], fontSize: 30),
              ),
              SizedBox(height: 15),
              const FlutterLogo(size: 60.0),
            ],
          ),
        ),
      );
}

start_screen.dart

In this file, we have to determine the screen size of the watch so that all the components properly fit within the screen. To determine the size and shape of the watch face we have to use the “WatchShape” widget which we get from the wear plugin.

We can determine the screen height and screen width by following this:

WatchShape(
        builder: (context, shape) {
          var screenSize = MediaQuery.of(context).size;
          final shape = InheritedShape.of(context).shape;
          if (shape == Shape.round) {
            // boxInsetLength requires radius, so divide by 2
            screenSize = Size(boxInsetLength(screenSize.width / 2),
                boxInsetLength(screenSize.height / 2));
          }
          var screenHeight = screenSize.height;
          var screenWidth = screenSize.width;

          ......

        },
),

Now, we can build the UI using the screen size which will look like this:

Start Screen

It again contains a Column with two widgets:

  1. FlutterLogo
  2. RaisedButton (Inside which we have to define a route, which will take us to the next screen, i.e., “name_screen.dart”)

I had to wrap the Column widget with a Container and specified its height and width so that the contents of the column fits perfectly onto the screen.

The code for the start_screen is given below:

import 'package:flutter/material.dart';
import 'package:flutter_os/screens/name_screen.dart';
import 'package:flutter_os/utils.dart';
import 'package:wear/wear.dart';

class StartScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: WatchShape(
        builder: (context, shape) {
          var screenSize = MediaQuery.of(context).size;
          final shape = InheritedShape.of(context).shape;
          if (shape == Shape.round) {
            // boxInsetLength requires radius, so divide by 2
            screenSize = Size(boxInsetLength(screenSize.width / 2),
                boxInsetLength(screenSize.height / 2));
          }
          var screenHeight = screenSize.height;
          var screenWidth = screenSize.width;

          return Center(
            child: Container(
              color: Colors.white,
              height: screenSize.height,
              width: screenSize.width,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[
                  FlutterLogo(size: 90),
                  SizedBox(height: 20),
                  RaisedButton(
                    highlightColor: Colors.blue[900],
                    elevation: 6.0,
                    child: Text(
                      'START',
                      style: TextStyle(color: Colors.white, fontSize: 20),
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                    color: Colors.blue[400],
                    onPressed: () {
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return NameScreen(screenHeight, screenWidth);
                      }));
                    },
                  )
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

In the above code snippet, you can see that I have used a method “boxInsetLength” (in line number 17 &18). Actually, it is defined inside the “utils.dart” file, that’s why we had to import “utils.dart” (in line number 3). This method measures the screen size when the watch face is round by taking the radius as the input.

double boxInsetLength(double radius) => radius * 1.4142;

name_screen.dart

We have passed the screen height and screen width to the “name_screen.dart” file, so that we do not need to calculate the screen size again.

The final “name_screen.dart” file looks like this:

Name Screen

I don’t have to elaborate on anything in this file. The code for building this UI is given below:

import 'package:flutter/material.dart';
import 'package:flutter_os/screens/ambient_screen.dart';
import 'package:flutter_os/screens/relax_menu.dart';
import 'package:wear/wear.dart';

class NameScreen extends StatelessWidget {
  final screenHeight;
  final screenWidth;
  NameScreen(this.screenHeight, this.screenWidth);

  @override
  Widget build(BuildContext context) {
    return AmbientMode(
      builder: (context, mode) => mode == Mode.active
          ? NameScreenUI(screenHeight, screenWidth)
          : AmbientWatchFace(),
    );
  }
}

class NameScreenUI extends StatelessWidget {
  final screenHeight;
  final screenWidth;
  NameScreenUI(this.screenHeight, this.screenWidth);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          height: screenHeight,
          width: screenWidth,
          child: Column(
            children: <Widget>[
              InkWell(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Image.asset('assets/outline_arrow.png',scale: 1.8,),
                    SizedBox(width: 5),
                    Text('Back', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w300),)
                  ],
                ),
                onTap: () {
                  Navigator.of(context).pop();
                },
              ),
              SizedBox(height: 20),
              Text(
                'Welcome to',
                style: TextStyle(
                  fontSize: 18,
                ),
              ),
              SizedBox(height: 5),
              Text(
                'FlutterOS',
                style: TextStyle(
                  fontSize: 30,
                  color: Colors.blue[700],
                ),
              ),
              SizedBox(height: 5),
              RaisedButton(
                highlightColor: Colors.blue[900],
                elevation: 6.0,
                child: Text(
                  'NEXT',
                  style: TextStyle(color: Colors.white, fontSize: 20),
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10),
                ),
                color: Colors.blue[400],
                onPressed: () {
                  Navigator.of(context)
                      .push(MaterialPageRoute(builder: (context) {
                    return RelaxView(screenHeight, screenWidth);
                  }));
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}

One thing that I want you to notice is that in line number 39 I have used the image of a material arrow icon by importing it from the assets, but we know that all the material icons are integrated with Flutter.

Why have I imported the material icons externally?

I used the Icons integrated with Flutter during the initial build of the UI, but these icons were not displaying on the screen rather they were replaced by a Placeholder icon. So, I had to import them externally from the Material Design Website.

For the rest of my app, I have tried to use as much of the original code of the “Relax” app as I could. But to properly use the small screen real estate of the watch I had to tweak the code.

relax_menu.dart

In this screen, I have used a Column with SingleChildScrollView to show the list of different relax sound screens.

The final screen looks like this:

Relax Menu

The code for building this UI is given below:

import 'package:flutter/material.dart';
import 'package:flutter_os/screens/ambient_screen.dart';
import 'package:flutter_os/screens/sound_screen.dart';
import 'package:wear/wear.dart';

const img = 'assets/images/';
List<String> screens = ['rain', 'forest', 'sunset', 'ocean'];

class RelaxView extends StatelessWidget {
  final screenHeight;
  final screenWidth;
  RelaxView(this.screenHeight, this.screenWidth);

  @override
  Widget build(BuildContext context) {
    return AmbientMode(
      builder: (context, mode) =>
          mode == Mode.active ? HomeRoute() : AmbientWatchFace(),
    );
  }
}

class HomeRoute extends StatelessWidget {
  soundBtn(sound, context) {
    return GestureDetector(
      onTap: () {
        Navigator.push(context,
            MaterialPageRoute(builder: (context) => PlayRoute(sound: sound)));
      },
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.only(top: 8.0),
            child: Image.asset(
              'assets/icons/$sound.png',
              scale: 1.2,
            ),
          ),
          Text(sound.toUpperCase(),
              style: TextStyle(
                  color: Colors.white, fontSize: 16, letterSpacing: 3.0))
        ],
      ),
    );
  }

  @override
  build(BuildContext context) {
    var width = MediaQuery.of(context).size.width;
    return Scaffold(
      body: Stack(
        children: [
          Positioned(
            top: 0,
            left: 0,
            child: Image.asset(
              img + 'bkgnd_2.jpg',
              fit: BoxFit.fill,
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: InkWell(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset(
                    'assets/outline_arrow.png',
                    scale: 1.8,
                  ),
                  SizedBox(width: 5),
                  Text(
                    'Back',
                    style: TextStyle(fontSize: 20, fontWeight: FontWeight.w300),
                  )
                ],
              ),
              onTap: () {
                Navigator.of(context).pop();
              },
            ),
          ),
          Positioned(
            top: 40,
            width: width,
            child: Padding(
              padding: const EdgeInsets.only(top: 8.0),
              child: Center(
                child: Text(
                  'RELAX',
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                      letterSpacing: 13.0,
                      fontWeight: FontWeight.w600),
                ),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 70.0),
            child: Center(
              child: SingleChildScrollView(
                physics: BouncingScrollPhysics(),
                child: Column(
                  children: [
                    soundBtn('rain', context),
                    soundBtn('forest', context),
                    soundBtn('sunset', context),
                    soundBtn('ocean', context),
                    SizedBox(
                      height: 40,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

sound_screen.dart

In this screen, mostly the audio playback is handled by using the plugin “audioplayers” and a beautiful background animation is added, which transitions between two images for each screen.

Erin Morrissey has handled the audio playback and the background animation perfectly in this screen.

The only thing that I had to do is to properly fit the contents in such a small screen. I have used “BoxFit.fill” with the background images and I have centered the Column containing two widgets:

  1. Text widget (Heading of the screen)
  2. Play/Pause icon button

The final screens look like this:

Sound Screens

The code used for building this UI is given below:

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';

const img = 'assets/images/';

class PlayRoute extends StatefulWidget {
  final String sound;
  const PlayRoute({Key key, this.sound}) : super(key: key);
  @override
  _PlayRouteState createState() => _PlayRouteState();
}

class _PlayRouteState extends State<PlayRoute> {
  AudioPlayer player;
  AudioCache cache;
  bool initialPlay = true;
  bool playing;

  @override
  initState() {
    super.initState();
    player = new AudioPlayer();
    cache = new AudioCache(fixedPlayer: player);
  }

  @override
  dispose() {
    super.dispose();
    player.stop();
  }

  playPause(sound) {
    if (initialPlay) {
      cache.play('audio/$sound.mp3');
      playing = true;
      initialPlay = false;
    }
    return InkWell(
      onTap: () {
        setState(() {
          if (playing) {
            playing = false;
            player.pause();
          } else {
            playing = true;
            player.resume();
          }
        });
      },
      child: playing
          ? Image.asset('assets/pause_circle_filled.png', scale: 1.2)
          : Image.asset('assets/play_circle_filled.png', scale: 1.2),
    );
  }

  @override
  build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Positioned(
            top: 0,
            left: 0,
            child: Background(sound: widget.sound),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: InkWell(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset(
                    'assets/outline_arrow_back_white.png',
                    scale: 1.8,
                  ),
                  SizedBox(width: 5),
                  Text(
                    'Back',
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                        fontWeight: FontWeight.w300),
                  )
                ],
              ),
              onTap: () {
                Navigator.of(context).pop();
              },
            ),
          ),
          Center(
            child: Column(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  widget.sound.toUpperCase(),
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                      letterSpacing: 10.0,
                      fontWeight: FontWeight.w600),
                ),
                playPause(widget.sound)
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class Background extends StatefulWidget {
  final String sound;
  const Background({Key key, this.sound}) : super(key: key);
  @override
  _BackgroundState createState() => _BackgroundState();
}

class _BackgroundState extends State<Background> {
  Timer timer;
  bool _visible = false;

  @override
  dispose() {
    timer.cancel();
    super.dispose();
  }

  swap() {
    if (mounted) {
      setState(() {
        _visible = !_visible;
      });
    }
  }

  @override
  build(BuildContext context) {
    timer = Timer(Duration(seconds: 6), swap);
    return Stack(
      children: [
        Image.asset(img + widget.sound + '_1.jpg', fit: BoxFit.fill),
        AnimatedOpacity(
            child: Image.asset(
              img + widget.sound + '_2.jpg',
              fit: BoxFit.fill,
            ),
            duration: Duration(seconds: 2),
            opacity: _visible ? 1.0 : 0.0)
      ],
    );
  }
}

So finally, we have completed our Wear OS project, rather you can call it as a FlutterOS.

Conclusion

After creating this project, I admit that Flutter is not optimized for Wear OS devices till now as many of the simple things are not working on Wear OS like all material Icons which are included in Flutter are not displaying on Wear OS devices.

You can find the GitHub repo for this project in the following

flutter mobile-apps

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

How To Succeed In Mobile App Wireframe Design?

This article covers everything about mobile app wireframe design: what to do and what not, tools used in designing a mobile or web app wireframe, and more.

Mobile App Development North Carolina

Mobile App Development North Carolina In the era of globalization, technology has forced the businesses and industries to jump into the space of competition. Technology has both tangible and intangible benefits that help businesses from different ind...

Top 7 Mobile App Development Companies in Delhi NCR

Looking for a Mobile app development company in Delhi NCR? Here it a list of top mobile app development companies in Delhi for Android & iOS app Development.

ECommerce Mobile App Development | Ecommerce Mobile App Development Services

We are leading ecommerce mobile application development company. Hire our ecommerce mobile app developer for your custom Ecommerce project at competitive rates. **Know about [Top ECommerce Mobile App Development...

Top Mobile App Development Company in Columbia | Mobile App Developers

WebClues is full-service mobile app development agency offering mobile app development services at best price. Get scalable mobile app solutions from industry experts.