subscribe via RSS

How to build a native cross platform project with Flutter

How to build a native cross platform project with Flutter

You can find the final project here.

Up to now you have been able to create projects with Flutter that run on iOS/Android, Web and Desktop but only sharing pure dart plugins. Flutter launched Flutter for web at Google I/O and was a temporary fork that required you to change imports from import 'package:flutter/material.dart'; to import 'package:flutter_web/material.dart';. As you can image this was really difficult for a code base as you had to create a fork and change the imports. This also meant that you could not import any package that needed on a path or depended on flutter. The time as come and the merge is complete. Now you no longer need to change the imports!

icon

You can use any plugin now, have a debugger, create new flutter projects with the web folder added, web plugins, and so much more..

Disclaimer

You will need to be on the latest flutter for this to work.

1. Install Flutter

Download Flutter

flutter

2. Create new Flutter Project

If you are pretty new to Flutter you can check out this useful guide on how to create a new project step by step.

cross-platform

Create a new project named flutter_x and it should look like this:

flutter

You can also down the starter project here.

Your code should look like this:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

3. Run your project

Just to make sure everything is working go ahead and run the project on iOS/Android.

flutter

You should have the counter application running and working correctly. Now quit and run on Chrome. It should be listed as a device. You can also run from the command line flutter run -d chrome.

flutter

You do not get hot reload yet on web so be aware of that.

4. Set up project structure

This is optional but I use this structure in all my apps

/lib
    /ui
        /common
        /screen
    /data
        /classes
        /models
        /blocs
        /abstract
        /services
        /database
        /utils
    /plugins

flutter

Your project should now look like this.

5. Import Plugins

Open your pubspec.yaml and import the following packages.

universal_html:
url_launcher:

You can also remove the comments generated in the pubspec.yaml

Your pubspec.yaml will now read like this:

name: flutter_x
description: A new Flutter project.

version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2
  universal_html: ^1.1.0
  url_launcher: ^5.1.2

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:

  uses-material-design: true

6. Setup the plugin implementation

By default if you were to check if the device was mobile or web you will get an error at compile time when trying to import a plugin that is not meant for the platform. To get around this we will use dynamic imports.

flutter

Create a url_launcher folder and file url_launcher.dart, mobile.dart, web.dart, unsupported.dart inside the plugins folder.

7: Dynamic Imports

In the file url_launcher.dart add the following:

export 'unsupported.dart'
    if (dart.library.html) 'web.dart'
    if (dart.library.io) 'mobile.dart';

This will pick the correct file at runtime and give a fallback if it is not supported.

8: Fallback for Plugin

To protect against edge cases you will need to set up a fallback for the import. In unsupported.dart add the following:

class UrlUtils {
  UrlUtils._();

  static void open(String url, {String name}) {
    throw 'Platform Not Supported';
  }
}

The class UrlUtils and the public methods have to match all three files for this to work correctly. Always set up the unsupported first then copy the file into mobile.dart and web.dart to ensure no typos.

You should now have 3 files with the above code in each class.

9: Mobile Side

In mobile.dart add the following:

import 'package:url_launcher/url_launcher.dart';

class UrlUtils {
  UrlUtils._();

  static void open(String url, {String name}) async {
    if (await canLaunch(url)) {
      await launch(url);
    }
  }
}

This will open the link in safari view controller or android’s default browser respectively.

10: Web Side

In web.dart add the following:

import 'package:universal_html/prefer_universal/html.dart' as html;

class UrlUtils {
  UrlUtils._();

  static void open(String url, {String name}) {
    html.window.open(url, name);
  }
}

This will open up a new window in the browser with the specified link.

11: Connect the UI

Add a button to the center of the screen. The ui/home/screen.dart should read the following:

import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
          child: RaisedButton(
        child: Text('Open Flutter.dev'),
        onPressed: () {},
      )),
    );
  }
}

Update the onPressed to the following:

onPressed: () {
    try {
        UrlUtils.open('https://flutter.dev');
    } catch (e) {
        print('Error -> $e');
    }
},

Now when you go to import the UrlUtils it is important to import the correct URI.

flutter

Make sure to import import 'package:flutter_x/plugins/url_launcher/url_launcher.dart'; only.

You can use the relative import if you wish.

12: Double Check

You UI code will now read the following:

import 'package:flutter/material.dart';

import '../../plugins/url_launcher/url_launcher.dart';

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
          child: RaisedButton(
        child: Text('Open Flutter.dev'),
        onPressed: () {
          try {
            UrlUtils.open('https://flutter.dev');
          } catch (e) {
            print('Error -> $e');
          }
        },
      )),
    );
  }
}

13: Run Your App

Your app on the web should look like this:

flutter

And when you tap the button..

flutter

And when you run it on iOS/Android it should look like this:

flutter

And when you tap the button..

flutter

Conclusion

Congratulations! You made it :)

flutter

Here is the final project located here.

Please reach out if you have any questions!

Automate Flutter App Releases

Automate Flutter App Releases

TLDR

You can find the script here.

Make your life easier and automate your builds to beta and production!

What you need

Initial Setup

  • Download this file
  • Put it at the root level of your flutter project
  • Open the terminal and navigate to your project location
  • Enter this command: chmod +x release.sh

Usage

Now you can call this script!

  • For beta: ./release.sh beta
  • For production: ./release.sh release

Overview

  • Bump the version numbers if you are using the version in the pubspec.yaml
  • Release the apps with Fastlane
  • Format all Dart Files
  • Clean Project
  • Rebuild classes
  • Add commit messages
  • Updates Cocoa Pods

Building A Piano with Flutter

Building A Piano with Flutter

TLDR

You can find the final source code here.

This piano uses only 5032 bytes of Dart Code!

Winner of the Flutter Create Contest and you can see the certificate here!

What you will learn

  • Working with Dark Mode
  • Forcing app to be in landscape
  • Working with custom files bundled with the app
  • Working with midi and sounds in flutter
  • Working with StatefulWidget
  • Using SafeArea and Semantics
  • Building an app with minimal code

What you need

  • Flutter SDK Installed (More Info)
  • A .sf2 SoundFont File like this one
  • Physical iOS device (iOS Simulator does not work with this plugin for playing the sounds) or Android Emulator/Device

Setting Up

You can either create a new project with Android Studio or VSCode using the GUI or navigate to the location you want your project and using this command in the terminal: lutter create -i swift -a kotlin flutter_piano. Make sure to include Swift and Kotlin Support!

Now that you have your project created it should look like this.

app-icon

Let’s start by adding some dependencies to our `pubspec.yaml’

dependencies:
  flutter:
    sdk: flutter
  tonic: ^0.2.3
  flutter_midi: ^0.1.1+3
  cupertino_icons: ^0.1.2

and add the .sf2 file

 assets:
   - assets/sounds/Piano.sf2

If you haven’t already create a new folder at the top of your project call assets and a subfolder called sounds and place the .sf2 file there and make sure it is named Piano.sf2

Because our app will only work in landscape we need to update those settings as well.

navigate to the /android/app/src/main/AndroidManifest.xml and add this line inside <activity in the <application:

android:screenOrientation="landscape"

Example:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.appleeducate.flutter_piano">

    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="flutter_piano"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:screenOrientation="landscape"
            android:windowSoftInputMode="adjustResize">
            <!-- This keeps the window background of the activity showing
                 until Flutter renders its first frame. It can be removed if
                 there is no splash screen (such as the default splash screen
                 defined in @style/LaunchTheme). -->
            <meta-data
                android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
                android:value="true" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

navigate to /ios/Runner/info.plist and change:

<key>UISupportedInterfaceOrientations</key>
<array>
    <string>UIInterfaceOrientationLandscapeLeft</string>
    <string>UIInterfaceOrientationLandscapeRight</string>
</array>

Now we can start with the UI! When you run the application now it should start in landscape!

landscape

Step 1

To make it eaiser to read lets remove the comments. Use “find and replace” and search for \/\/.*

comments

choose the “select all occurrances” button and hit backspace to delete.

select all

Hit save and you should see the code format for you.

The ‘main.dart’ file should look like this:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Step 2

Delete the MyHomePage widget so you are left with this.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

You should get an error and thats ok, we will fix that next.

Replace MyHomePage(title: 'Flutter Demo Home Page') with a Scaffold()

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(),
    );
  }
}

Step 3

Change MyApp to a StatefulWidget. You can do this quickly by selecting MyApp and choose “Convert to StatefulWidget” with the helper.

convert

It should look like this now:

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(),
    );
  }
}

Step 4

Change the theme to dark. You can do this by setting the ThemeData in MaterialApp

change:

theme: ThemeData(
        primarySwatch: Colors.blue,
      ),

to this

theme: ThemeData.dark(),

Add and AppBar to the Scaffold

appBar: AppBar(title: Text("Flutter Piano")),

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData.dark(),
      home: Scaffold(
        appBar: AppBar(title: Text("Flutter Piano")),
      ),
    );
  }
}

Now build and run your app, it should look like this.

dark-mode

Step 5

We need to add some imports to the top:

import 'package:flutter/services.dart';
import 'package:flutter_midi/flutter_midi.dart';

If you get an error make sure they are added in the pubspec.yaml from earlier, then restart the app. Be sure to run flutter packages get everytime you add a dependency.

Now we can add out initState() to our app.

 @override
 initState() {
   FlutterMidi.unmute();
   rootBundle.load("assets/sounds/Piano.sf2").then((sf2) {
     FlutterMidi.prepare(sf2: sf2, name: "Piano.sf2");
   });
   super.initState();
 }

Run the app and make sure you do not get any errors. If you are running this on the iOS Simulator you will get the following error:

Could Not Load Midi on this Device. (Cannot run on simulator), have you included the sound font?

It is ok for developing the UI but once we start with the midi you will need to plug in a real device.

Your code so far should look like this:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_midi/flutter_midi.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  initState() {
    FlutterMidi.unmute();
    rootBundle.load("assets/sounds/Piano.sf2").then((sf2) {
      FlutterMidi.prepare(sf2: sf2, name: "Piano.sf2");
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData.dark(),
      home: Scaffold(
        appBar: AppBar(title: Text("Flutter Piano")),
      ),
    );
  }
}

Step 6

To make Flutter development faster we start with containers and colors so we can make sure everything is the right size.

Lets start by adding a Drawer with a ListView to our Scaffold.

 home: Scaffold(
        appBar: AppBar(title: Text("Flutter Piano")),
        drawer: Drawer(child: SafeArea(child: ListView(children: <Widget>[]))),
      ),

You should now get a menu icon that when you press looks like this.

menu

Now lets add a ListView that scrolls Horizontially to the body of the Scaffold

 body: ListView.builder(
            itemCount: 7,
            scrollDirection: Axis.horizontal,
            itemBuilder: (BuildContext context, int index) {
              return Container();
            },
          )

We need 7 itemCount for 7 octaves on the Piano.

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_midi/flutter_midi.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  initState() {
    FlutterMidi.unmute();
    rootBundle.load("assets/sounds/Piano.sf2").then((sf2) {
      FlutterMidi.prepare(sf2: sf2, name: "Piano.sf2");
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData.dark(),
      home: Scaffold(
          appBar: AppBar(title: Text("Flutter Piano")),
          drawer:
              Drawer(child: SafeArea(child: ListView(children: <Widget>[]))),
          body: ListView.builder(
            itemCount: 7,
            scrollDirection: Axis.horizontal,
            itemBuilder: (BuildContext context, int index) {
              return Container();
            },
          )),
    );
  }
}

Step 7

Now we need to build the octave section that will be repeated. Since every octave is identical we can repeat the octaves with minor adjustments.

Lets add some parameters for use to define for our UI. Add these underneath the initState function.

double get keyWidth => 80 + (80 * _widthRatio);
double _widthRatio = 0.0;
bool _showLabels = true;

We will use these to dynamily update the keys.

Under the itemBuilder lets define which octave we are working with by adding: final int i = index * 12;

Our code should look like this now:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_midi/flutter_midi.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  initState() {
    FlutterMidi.unmute();
    rootBundle.load("assets/sounds/Piano.sf2").then((sf2) {
      FlutterMidi.prepare(sf2: sf2, name: "Piano.sf2");
    });
    super.initState();
  }
  
  double get keyWidth => 80 + (80 * _widthRatio);
  double _widthRatio = 0.0;
  bool _showLabels = true;
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData.dark(),
      home: Scaffold(
          appBar: AppBar(title: Text("Flutter Piano")),
          drawer:
              Drawer(child: SafeArea(child: ListView(children: <Widget>[]))),
          body: ListView.builder(
            itemCount: 7,
            scrollDirection: Axis.horizontal,
            itemBuilder: (BuildContext context, int index) {
              final int i = index * 12;
              return Container();
            },
          )),
    );
  }
}

Step 8

Now we need to add a Stack for our octave:

 return SafeArea(
               child: Stack(children: <Widget>[
                 Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
                   _buildKey(24 + i, false),
                   _buildKey(26 + i, false),
                   _buildKey(28 + i, false),
                   _buildKey(29 + i, false),
                   _buildKey(31 + i, false),
                   _buildKey(33 + i, false),
                   _buildKey(35 + i, false),
                 ]),
                 Positioned(
                     left: 0.0,
                     right: 0.0,
                     bottom: 100,
                     top: 0.0,
                     child: Row(
                         mainAxisAlignment: MainAxisAlignment.spaceBetween,
                         mainAxisSize: MainAxisSize.min,
                         children: <Widget>[
                           Container(width: keyWidth * .5),
                           _buildKey(25 + i, true),
                           _buildKey(27 + i, true),
                           Container(width: keyWidth),
                           _buildKey(30 + i, true),
                           _buildKey(32 + i, true),
                           _buildKey(34 + i, true),
                           Container(width: keyWidth * .5),
                         ])),
               ]),
             );

Here we have defined which midi notes are played for each octave.

Now add the function _buildKey underneath our build function.

 Widget _buildKey(int midi, bool accidental) {
     if (accidental) {
      return Container(
          width: keyWidth,
          color: Colors.black,
          margin: EdgeInsets.symmetric(horizontal: 2.0),
          padding: EdgeInsets.symmetric(horizontal: keyWidth * .1),
          child: Material(
            elevation: 6.0,
            borderRadius: borderRadius,
            shadowColor: Color(0x802196F3),
          ));
    }
    return Container(
        width: keyWidth,
        color: Colors.white,
        margin: EdgeInsets.symmetric(horizontal: 2.0));
  }

Also add borderRadius to the bottom of main.dart

const BorderRadiusGeometry borderRadius = BorderRadius.only(
    bottomLeft: Radius.circular(10.0), bottomRight: Radius.circular(10.0));

Your app should look like this:

keys

Your code should look like this:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_midi/flutter_midi.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  initState() {
    FlutterMidi.unmute();
    rootBundle.load("assets/sounds/Piano.sf2").then((sf2) {
      FlutterMidi.prepare(sf2: sf2, name: "Piano.sf2");
    });
    super.initState();
  }

  double get keyWidth => 80 + (80 * _widthRatio);
  double _widthRatio = 0.0;
  bool _showLabels = true;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData.dark(),
      home: Scaffold(
          appBar: AppBar(title: Text("Flutter Piano")),
          drawer:
              Drawer(child: SafeArea(child: ListView(children: <Widget>[]))),
          body: ListView.builder(
            itemCount: 7,
            scrollDirection: Axis.horizontal,
            itemBuilder: (BuildContext context, int index) {
              final int i = index * 12;
              return SafeArea(
                child: Stack(children: <Widget>[
                  Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
                    _buildKey(24 + i, false),
                    _buildKey(26 + i, false),
                    _buildKey(28 + i, false),
                    _buildKey(29 + i, false),
                    _buildKey(31 + i, false),
                    _buildKey(33 + i, false),
                    _buildKey(35 + i, false),
                  ]),
                  Positioned(
                      left: 0.0,
                      right: 0.0,
                      bottom: 100,
                      top: 0.0,
                      child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            Container(width: keyWidth * .5),
                            _buildKey(25 + i, true),
                            _buildKey(27 + i, true),
                            Container(width: keyWidth),
                            _buildKey(30 + i, true),
                            _buildKey(32 + i, true),
                            _buildKey(34 + i, true),
                            Container(width: keyWidth * .5),
                          ])),
                ]),
              );
            },
          )),
    );
  }

  Widget _buildKey(int midi, bool accidental) {
    if (accidental) {
      return Container(
          width: keyWidth,
          color: Colors.black,
          margin: EdgeInsets.symmetric(horizontal: 2.0),
          padding: EdgeInsets.symmetric(horizontal: keyWidth * .1),
          child: Material(
            elevation: 6.0,
            borderRadius: borderRadius,
            shadowColor: Color(0x802196F3),
          ));
    }
    return Container(
        width: keyWidth,
        color: Colors.white,
        margin: EdgeInsets.symmetric(horizontal: 2.0));
  }
}

const BorderRadiusGeometry borderRadius = BorderRadius.only(
    bottomLeft: Radius.circular(10.0), bottomRight: Radius.circular(10.0));

Step 9

Time to add midi by adding the following import to the top of the file:

import 'package:tonic/tonic.dart';

In the -buildKey function you can add this line:

 final pitchName = Pitch.fromMidiNumber(midi).toString();

We can also create the piano key itself underneath it:

 final pianoKey = Stack(
     children: <Widget>[
       Semantics(
           button: true,
           hint: pitchName,
           child: Material(
               borderRadius: borderRadius,
               color: accidental ? Colors.black : Colors.white,
               child: InkWell(
                 borderRadius: borderRadius,
                 highlightColor: Colors.grey,
                 onTap: () {},
                 onTapDown: (_) => FlutterMidi.playMidiNote(midi: midi),
               ))),
       Positioned(
           left: 0.0,
           right: 0.0,
           bottom: 20.0,
           child: _showLabels
               ? Text(pitchName,
                   textAlign: TextAlign.center,
                   style: TextStyle(
                       color: !accidental ? Colors.black : Colors.white))
               : Container()),
     ],
   );

Remove the color from the container and replace it with child: pianoKey,

 if (accidental) {
     return Container(
         width: keyWidth,
         margin: EdgeInsets.symmetric(horizontal: 2.0),
         padding: EdgeInsets.symmetric(horizontal: keyWidth * .1),
         child: Material(
             elevation: 6.0,
             borderRadius: borderRadius,
             shadowColor: Color(0x802196F3),
             child: pianoKey));
   }
   return Container(
       width: keyWidth,
       child: pianoKey,
       margin: EdgeInsets.symmetric(horizontal: 2.0));

The complete function should look like this:

 Widget _buildKey(int midi, bool accidental) {
   final pitchName = Pitch.fromMidiNumber(midi).toString();
   final pianoKey = Stack(
     children: <Widget>[
       Semantics(
           button: true,
           hint: pitchName,
           child: Material(
               borderRadius: borderRadius,
               color: accidental ? Colors.black : Colors.white,
               child: InkWell(
                 borderRadius: borderRadius,
                 highlightColor: Colors.grey,
                 onTap: () {},
                 onTapDown: (_) => FlutterMidi.playMidiNote(midi: midi),
               ))),
       Positioned(
           left: 0.0,
           right: 0.0,
           bottom: 20.0,
           child: _showLabels
               ? Text(pitchName,
                   textAlign: TextAlign.center,
                   style: TextStyle(
                       color: !accidental ? Colors.black : Colors.white))
               : Container()),
     ],
   );
   if (accidental) {
     return Container(
         width: keyWidth,
         margin: EdgeInsets.symmetric(horizontal: 2.0),
         padding: EdgeInsets.symmetric(horizontal: keyWidth * .1),
         child: Material(
             elevation: 6.0,
             borderRadius: borderRadius,
             shadowColor: Color(0x802196F3),
             child: pianoKey));
   }
   return Container(
       width: keyWidth,
       child: pianoKey,
       margin: EdgeInsets.symmetric(horizontal: 2.0));
 }

Now when you run the app it should look like this:

labels

Almost there! Now let’s give our user some control.

Step 10

Add these settings to the Drawer

Container(height: 20.0),
ListTile(title: Text("Change Width")),
Slider(
    activeColor: Colors.redAccent,
    inactiveColor: Colors.white,
    min: 0.0,
    max: 1.0,
    value: _widthRatio,
    onChanged: (double value) =>
        setState(() => _widthRatio = value)),
Divider(),
ListTile(
    title: Text("Show Labels"),
    trailing: Switch(
    value: _showLabels,
    onChanged: (bool value) =>
        setState(() => _showLabels = value))),
Divider(),

Now you should see this:

settings

Step 11

To start with Middle C lets add an inital scroll offset to the ListView

controller: ScrollController(initialScrollOffset: 1500.0),

Now when we start the app it should co to C4.

The final App should look like this:

final

The final code should look like this:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_midi/flutter_midi.dart';
import 'package:tonic/tonic.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  initState() {
    FlutterMidi.unmute();
    rootBundle.load("assets/sounds/Piano.sf2").then((sf2) {
      FlutterMidi.prepare(sf2: sf2, name: "Piano.sf2");
    });
    super.initState();
  }

  double get keyWidth => 80 + (80 * _widthRatio);
  double _widthRatio = 0.0;
  bool _showLabels = true;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData.dark(),
      home: Scaffold(
          appBar: AppBar(title: Text("Flutter Piano")),
          drawer: Drawer(
              child: SafeArea(
                  child: ListView(children: <Widget>[
            Container(height: 20.0),
            ListTile(title: Text("Change Width")),
            Slider(
                activeColor: Colors.redAccent,
                inactiveColor: Colors.white,
                min: 0.0,
                max: 1.0,
                value: _widthRatio,
                onChanged: (double value) =>
                    setState(() => _widthRatio = value)),
            Divider(),
            ListTile(
                title: Text("Show Labels"),
                trailing: Switch(
                    value: _showLabels,
                    onChanged: (bool value) =>
                        setState(() => _showLabels = value))),
            Divider(),
          ]))),
          body: ListView.builder(
            itemCount: 7,
            scrollDirection: Axis.horizontal,
            controller: ScrollController(initialScrollOffset: 1500.0),
            itemBuilder: (BuildContext context, int index) {
              final int i = index * 12;
              return SafeArea(
                child: Stack(children: <Widget>[
                  Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
                    _buildKey(24 + i, false),
                    _buildKey(26 + i, false),
                    _buildKey(28 + i, false),
                    _buildKey(29 + i, false),
                    _buildKey(31 + i, false),
                    _buildKey(33 + i, false),
                    _buildKey(35 + i, false),
                  ]),
                  Positioned(
                      left: 0.0,
                      right: 0.0,
                      bottom: 100,
                      top: 0.0,
                      child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            Container(width: keyWidth * .5),
                            _buildKey(25 + i, true),
                            _buildKey(27 + i, true),
                            Container(width: keyWidth),
                            _buildKey(30 + i, true),
                            _buildKey(32 + i, true),
                            _buildKey(34 + i, true),
                            Container(width: keyWidth * .5),
                          ])),
                ]),
              );
            },
          )),
    );
  }

  Widget _buildKey(int midi, bool accidental) {
    final pitchName = Pitch.fromMidiNumber(midi).toString();
    final pianoKey = Stack(
      children: <Widget>[
        Semantics(
            button: true,
            hint: pitchName,
            child: Material(
                borderRadius: borderRadius,
                color: accidental ? Colors.black : Colors.white,
                child: InkWell(
                  borderRadius: borderRadius,
                  highlightColor: Colors.grey,
                  onTap: () {},
                  onTapDown: (_) => FlutterMidi.playMidiNote(midi: midi),
                ))),
        Positioned(
            left: 0.0,
            right: 0.0,
            bottom: 20.0,
            child: _showLabels
                ? Text(pitchName,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        color: !accidental ? Colors.black : Colors.white))
                : Container()),
      ],
    );
    if (accidental) {
      return Container(
          width: keyWidth,
          margin: EdgeInsets.symmetric(horizontal: 2.0),
          padding: EdgeInsets.symmetric(horizontal: keyWidth * .1),
          child: Material(
              elevation: 6.0,
              borderRadius: borderRadius,
              shadowColor: Color(0x802196F3),
              child: pianoKey));
    }
    return Container(
        width: keyWidth,
        child: pianoKey,
        margin: EdgeInsets.symmetric(horizontal: 2.0));
  }
}

const BorderRadiusGeometry borderRadius = BorderRadius.only(
    bottomLeft: Radius.circular(10.0), bottomRight: Radius.circular(10.0));

Conclusion

If you delete tests/ and run find . -name "*.dart" | xargs cat | wc -c you will see that the dart code only uses 5032 bytes of space!

Now we have a fully functional piano that you can play with and enjoy on iOS and Android.

I was really inspired when creating this for the Flutter Create contest.

Hope you learned something, if you have any questions you can always read out to me. This is an open source piano and would love PRs on the main project here and an online demo!

Flutter + Fastlane (One Click Beta)

Flutter + Fastlane (One Click Beta)

1. Install Flutter

Download Flutter

flutter

2. Create new Flutter Project

If you are pretty new to Flutter you can check out this useful guide on how to create a new project step by step.

cross-platform

3. Create App in iTunes Connect

If you are not familiar with iTunes Connect, check out this article for getting started and setting up your first app for the App Store.

4. Create App in Google Play

Setting up an app in the Google Play Console can be tricky, make sure to check out the official reference and this guide if you are having trouble.

fastlane

5. Navigate to Project > ios and Setup Fastlane

Reference

6. Navigate to Project > android and Setup Fastlane

Reference

7. Update Fastlane Fastfiles for iOS and Android and Change accordingly for each platform

  • Make sure to change to the path to your project in Finder.

  • Only copy the correct platform code for each Fastfile. For example, default_platform(:ios) for iOS and `default_platform(:android)1st for Android.

update_fastlane

default_platform(:ios)

platform :ios do
  desc "Push a new beta build to TestFlight"
  lane :beta do
    increment_build_number(xcodeproj: "Runner.xcodeproj")
    build_app(workspace: "Runner.xcworkspace", scheme: "Runner")
    upload_to_testflight(skip_waiting_for_build_processing: true)
  end
  desc "Push a new release build to the App Store"
  lane :release do  
    increment_build_number(xcodeproj: "Runner.xcodeproj")
    build_app(workspace: "Runner.xcworkspace", scheme: "Runner")
    upload_to_app_store(submit_for_review: true,
                            automatic_release: true,
                            skip_screenshots: true,
                            force: true,
                            skip_waiting_for_build_processing: true)
  end
end


  
//<YOUR PROJECT PATH> > android > fastlane > Fastfile
default_platform(:android)

platform :android do
  desc "Runs all the tests"
  lane :test do
    gradle(task: "test")
  end

  desc "Submit a new Build to Beta"
  lane :beta do
    gradle(task: 'clean')
    increment_version_code
    sh "cd <YOUR PROJECT PATH> && flutter build apk"
    upload_to_play_store(
      track: 'beta',
      apk: '../build/app/outputs/apk/release/app-release.apk',
      skip_upload_screenshots: true,
      skip_upload_images: true
    )
    # crashlytics
  end

  desc "Deploy a new version to the Google Play"
  lane :deploy do
    gradle(task: 'clean')
    increment_version_code
    sh "cd <YOUR PROJECT PATH> && flutter build apk"
    upload_to_play_store(
      track: 'production',
      apk: '../build/app/outputs/apk/release/app-release.apk',
      skip_upload_screenshots: true,
      skip_upload_images: true
    )
  end
end
  • For Android increment_version_code install here.

Sometimes it will fail and you will need to run:

bundle exec fastlane add_plugin increment_version_code

  • For iOS increment_build_number set up Generic Versioning by enabling the agvtool.

version-bump

Source

8. Metadata (Optional)

  • For iOS you can have Fastlane download all your apps existing metadata including screenshots from iTunes Connect. In terminal navigate to the project and run.

fastlane deliver download_metadata && fastlane deliver download_screenshots

9. Open Automator

Right now everything is working just by the command line. If you navigate to your project in terminal by adding “cd “ and dragging in the project folder and hitting Enter, you can type “cd ios && fastlane beta” or “cd android && fastlane beta” and both will run fastlane.

terminal

If you want to be able to submit your app to Google Play and the App Store with one click we will be using Automator. Create a new Automator Application. And Search for “Ask for Confirmation” and “Run AppleScript” and drag in.

fastlane

Here is the Script for beta and release. You will need to create a Automator Application for both Beta and Release for each app you want automated. Save it where ever you want and create an Alias to be but on the Desktop.

  • Make sure to change to the path to your project in Finder

Hint: I have my automator application save in the Github Repo of my project for versioning and easy access for different projects.

//Beta
on run {input, parameters}
	tell application "Terminal"
		activate
		do script "cd <YOUR PROJECT PATH>/android && fastlane beta && cd <YOUR PROJECT PATH>/ios && fastlane beta"
	end tell
	tell application "System Events"
		try
			set visible of application process "Terminal" to false
		end try
	end tell
end run

//Release
on run {input, parameters}
	tell application "Terminal"
		activate
		do script "cd <YOUR PROJECT PATH>/android && fastlane deploy && cd <YOUR PROJECT PATH>/ios && fastlane release"
	end tell
	tell application "System Events"
		try
			set visible of application process "Terminal" to false
		end try
	end tell
end run

10. Try It Out!

Everything should be working now. If you double click on the automator application you should get a confirmation pop up to release the app. The Script will run terminal in the background and you can stay focused on developing awesome flutter applications. If you want to see the progress on fastlane uploading your apps you can click on the terminal icon and the terminal window will reappear. Thanks for reading and please reach out for any questions you have!

The Pitch Pipe

The Pitch Pipe

Sheet Music Made Easy

app-icon

Looking for the perfect pitch pipe companion? Need more features that just playing a note? Don’t know how to read music?

This app is perfect for:

  • Music Teachers and Students
  • Song Leaders
  • A Capella and Band Groups
  • Solo Performers
  • Students learning music
  • Choirs and Music Groups
  • Instrument Tuning

Features:

  • Song List for Pre Selecting Pitches and Scales and arranging them into a list
  • Note Helper for help with Sheet Music
  • Classic C-C and F-F Pitch Pipes
  • Modern Button Layout with C-C and F-F versions
  • 3D Touch Quick Actions
  • Apple Watch App with “C3” to “F4”
  • Full iOS 11 Support
  • Full iPhone X Support (Including True Black Theme)
  • New interface for Pitch Pipe Tab so that it is simple to navigate
  • Notes Field for Song List
  • Share Button for Song List
  • Today Widget for Sheet Music Help
  • In app rating for a better App Store rating experience