Building a Flutter app, part 5: adding Firebase to the Flutter project

Welcome to part 5 of my Flutter App development journal, where I document my process of building a “grocery list” app from scratch.

In this post: Adding Firebase to my Flutter app. This is mostly setup (there was a fair amount of it) and the actual coding resumes in Part 6.

At this point, passing around the mock data objects is getting to be more of a nuisance than a help. I don’t want to write code just to support the passing-around of mock data, so it’s time to start putting that data into the db and retrieving it.

I decided to use Firebase for my project’s database needs. Flutter and Firebase are both Google projects and there is a lot of documentation that shows you how to use them together, so this seemed like a good place to start.

Setting up a new Firebase project

In the interest of not duplicating the official docs, I’ll just share the ones I followed:

But there were still a few places where I felt my experience deviated from the videos/docs or where I just kinda got lost, so I am documenting them here.

Registering the app with iOS

The Firebase instructions assume you’re working in Xcode, but if you’re like me and working with a different IDE (Android Studio) in my case you might be wondering how to get the iOS bundle ID.

Here’s what I did (and as far as I can tell, this step has to be done in Xcode.)

  1. Open Xcode
  2. Go to “File… Open” and open just the iOS directory of my project

3. Click on the “Runner” header in the project structure at left and retrieve the “Bundle identifier” from the information at right (just copy/paste it and leave XCode open because we come back to it in a later step).

4. Give that information to Firebase and click Register App

5. Download the GoogleService-Info.plist file it generates for you

6. Note that they tell you this file belongs in the “root of your Xcode” project. (The Flutter/Firebase video totally skips this step, too!) It took me some trial and error to discover that the right way to “install” this file is to drag it from Finder to the Runner folder in Xcode.

  • Do not do this operation just in Finder (or via Terminal), you must do this step in Xcode.
  • Make sure “Copy items if needed” is checked
  • Make sure “Add to targets Runner” is checked

If it looks like this, you’re done and can close Xcode:

7. Since this file contains things like my API key, I added *.plist to my .gitignore file (so you won’t see it if you browse the project there).

8. Back in Firebase setup, I skipped this step:

9. I also skipped the “Add initialization code” step which is for native projects.

Registering the app for Android

The Flutter/Firebase video covers this, but it happens so fast I had to watch it like 5 times to figure out where, exactly, this file is (and of course, pausing the video brings up a bunch of YouTube links and “related video” junk that covers the code, lol).

Search for and open AndroidManifest.xml:

The line in question is at the top, and the highlighted line is the part you need:

I do not actually have an Android device so for now I just have to hope this works, but I won’t know until later in development. I’ll come back and update this section if I have trouble using Firebase on an Android device.

Creating the Firebase database

After the project was successfully created on Google’s end, I created a new database and went with the default settings for now.

Note: I later had to change the “false” to “true”, because by default the Firebase database doesn’t allow access to anyone.

Adding the Firebase packages to pubspec.yaml

I added cloud_firestore and firebase_storage package dependencies to pubspec.yaml.

Now, return to Terminal and run flutter pub get (or if you are in Android Studio it might prompt you to update dependencies as soon as you flip over to another file).

Rebuilding the app

Finally, stop the app if you have it running and rebuild (hit the green “Play” button in Android Studio). Just a heads up, this particular build took a lot longer than they normally do.

Continue on to Part 6 where I write some basic create, read, and update operations for the app.

Building a Flutter app, part 4: refactors, improvements to the mock data, components

Welcome to part 4 of my Flutter App development journal, where I document my process of building a “grocery list” app from scratch.

In this post: Advanced interactions, improvements to the mock data, refactoring repeated code into components.

In the previous post, I built and linked up many of the app’s major routes, but there isn’t much to do on them yet. Changes made on one page aren’t really reflected on another, and a lot of code is repeated.

Now that most pages are represented, I wanted to refine the mock data, improve the way it gets passed around, refactor repeated code into components, and add more interactions such as moving items between lists.

This will be a short post, but this work should be done before moving onto the next step, which is hooking the app up to Firebase.

Refactoring the mock data

The mock data was useful for filling in the UI, but now I’d like to refine it.

  • Items need to exist independent of any particular list, so that they may appear on multiple lists and be moved between lists with ease
  • Lists should be more self-contained so that their data isn’t passed as multiple params; this object should contain the lists’s ID, name, and an array of item IDs
  • Default to local storage and pass data around, syncing with server whenever possible, but don’t prevent usage of the app in “offline” mode

The first thing I did was refactor it so the onTap functions all use a callback method passed in from main.dart or existing_shopping_list.dart. This meant I could finally remove all the “if … else” logic that checked what type of list the item belonged to from list_item.dart. (Sorry you had to see that, that was not my finest code, lol)

Here’s kind of a snippet of how that looks, from main.dart:

...

_editList(ShoppingList list) {
    Navigator.pushNamed(context, ExistingList.routeName, arguments: ExistingListArguments(list));
  }

@override
  Widget build(BuildContext context) {

    const headerShoppingLists = "Shopping Lists";
    const headerStores = "Stores";

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints viewportConstraints) {
          return SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                ItemListHeader(text: headerShoppingLists),
                ItemList(list: shoppingLists, listType: 'shopping list', onItemTap: _goToList, onInfoTap: _editList),

And then, over here in item_list.dart, we continue passing the onItemTap and onInfoTap method handles down:

import 'package:flutter/material.dart';

import 'add_new.dart';
import 'delete_all.dart';
import 'list_item.dart';

class ItemList extends StatelessWidget {

  final list;
  final listType;
  final onItemTap;
  final onInfoTap;

  ItemList({Key key, @required this.list, @required this.listType, @required this.onItemTap, @required this.onInfoTap});

  @override
  Widget build(BuildContext context) {

    int getCount(item) {
      if (listType == 'shopping list') {
        return item.itemIDs.length;
      } else {
        return list.length;
      }
    }

    return ListView.builder(
        shrinkWrap: true, // gives it a size
        primary: false, // so the shopping and store lists don't scroll independently
        itemCount: list.length + 1,
        itemBuilder: (BuildContext context, int index) {
          if (index == list.length) {
            if (listType == 'crossedOff') {
              return DeleteAll();
            } else { // store, shopping list
              return AddNew(listType: listType);
            }
          } else {
            return ListItem(item: list[index], listType: listType, count: getCount(list[index]), onTap: onItemTap, onInfoTap: onInfoTap);
          }
        }
    );
  }
}

And then in list_item.dart, the passed-in methods are invoked on onPressed or on onTap, and this is where I pass back the entire item (we’ll see if I regret that decision later, for now passing the whole item makes it easy to pick it apart on the next page for its ID, name, and contents).

@override
Widget build(BuildContext context) {
return ListTile(
title: Text(buildTitleString(), style: (listType == 'crossedOff' ? TextStyle(decoration: TextDecoration.lineThrough) : TextStyle(decoration: TextDecoration.none))),
subtitle: Text(buildSubtitleString()),
leading: FlutterLogo(),
trailing: IconButton(
icon: Icon(Icons.info),
onPressed: () => onInfoTap(item),
),
onTap: () => onTap(item), //handleTap(context),
);
}

There are some other refactors in this pull request, too:

  • I added IDs to the mock data sets and restructured some of them
  • I renamed ome of the default Flutter boilerplate (“MyApp” is now “GroceryGoApp”, etc.)
  • I moved some existing code into new components, such as delete_all.dart and add_new.dart.

You can view all of these changes here.

On to database stuff

At this point, I can either continue building with mock data, passing it around and modifying it locally but really, it’s time to start putting it into/taking it out of a database. On to part 5!

Building a Flutter app, part 2: boilerplate, reusable components, and the main screen UI

Welcome to part 2 of my Flutter App development journal. In Part 1, I set up Flutter on my MacBook and documented some of the hurdles I encountered. In Part 2, I am going to build the main screen UI and many of the app’s reusable components.

In this post: Putting together the main screen’s UI using ordinary Flutter widgets. Features include: scrollable screen with multiple lists and headers, models for mock data, and displaying mock data.

To view all of the code associated with this step on GitHub, click here.

Creating the boilerplate Flutter app

Running the flutter create app_name command creates a folder with the app_name you give it and fill it with some starter code (called “boilerplate”) that you’ll either use or delete as you build your own app.

I like to build from the boilerplate app code you get from running flutter create, so I started with that.

Where to run flutter create

Run flutter create app_name in the folder where you want your codebase to be created. In other words, if you want it to be in /projects, go to projects and run it inside projects.

Note: Don’t do what I initially did, which was create the project folder, enter it, and run flutter create inside it. That will give you a folder structure like this: /projects/app_name/app_name/ and I assume you don’t want that.

I keep all of my projects inside a folder named projects, so I created my “Grocery Go” app from that directory:

cd projects
flutter create grocery_go 

That will give you /projects/grocery_go/

Planning the main screen UI

My favorite mockup tools all seem to have gone to a subscription model, so I’m just gonna sketch my UI plans real quick on this notecard here…

High tech!

The “goals” for this UI are:

  • Two lists of items, one to represent “Shopping Lists” and one to represent “Stores”.
  • Each list has a header
  • Neither list should be scrollable on its own (no “scrolling within scrolling”), but the whole screen should scroll up/down

Creating the “Header” reusable component

This is the part that displays the section title, like “Shopping Lists” or “Stores”, in the scrolling list on the main page.

I know I’m going to use that “Header” bar at least twice, so I made it its own component. I also created a /components directory to hold MainScreenListHeader.

(Perhaps this might be better termed a “widget”, but “component” was ingrained during my years of working as a web developer and it’s the first word I think of when describing reusable pieces of UI).

Anyway, I now have:

grocery_go/lib/components/main_screen_list_header.dart

I use underscores in the filenames and UpperCamelCasing for the class names inside, which is Dart convention.

Inside the file, I create a class called MainScreenListHeader that extends StatelessWidget and give it a constructor that takes this.text, which will serve as the title displayed in the header bar. This component returns a Container with a color, height, and a child Text widget.

import 'package:flutter/material.dart';

class MainScreenListHeader extends StatelessWidget {
  final String text;

  MainScreenListHeader({Key key, @required this.text});

  @override
  Widget build(BuildContext context) {
    return Container(
        color: Colors.blue[800],
        height: 30.0,
        child: Center(
            child: Text(text,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                )
            )
        )
    );
  }
}

I wanted to pick a simple example for the first component, but the next one will be more complicated.

Creating the reusable “ListView” component

The list that contains individual shopping lists (such as “Groceries”, “House stuff”, etc.) and the list of the user’s stores (“Safeway”, “Fred Meyer”, etc.) appear in vertical lists the user can scroll up and down through.

Stores also display their address or location so the user can distinguish the Safeway near their office from the Safeway near their home.

Since I don’t know how many Shopping Lists or Stores a user might have saved, ListView builder seemed like a good widget to start with. I also put this in its own component from the beginning, which I named

grocery_go/lib/components/main_screen_list.dart

import 'package:flutter/material.dart';
import 'package:grocery_go/models/shopping_list.dart';

class MainScreenList extends StatelessWidget {

  final list;

  MainScreenList({Key key, @required this.list});

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        shrinkWrap: true, // gives it a size
        primary: false, // so it doesn't scroll
        itemCount: list.length,
        itemBuilder: (BuildContext context, int index) {
          return ListTile(
            title: Text(list[index].name),
            subtitle: Text(list[index] is ShoppingList ? list.length.toString() + ' items' : list[index].address),
          );
        }
    );
  }
}

Now all I need to do is pass in list objects from main.dart, which are declared as two separate lists of ShoppingList and Store objects.

I created two model files:

grocery_go/lib/models/shopping_list.dart

class ShoppingList {
final String name;

ShoppingList({this.name});
}

and

grocery_go/lib/models/store.dart

class Store {
  final String name;
  final String address;

  Store({this.name, this.address});
}

The last piece of the puzzle was to import the components and models in main.dart and change the body: property of the Scaffold that gets returned to use a LayoutBuilder that returns a SingleChildScrollView of a Column with children that are instances of my MainScreenListHeader and MainScreenList (whew – I’ll explain more after the code).

import 'package:flutter/material.dart';

import './components/main_screen_list.dart';
import './components/main_screen_list_header.dart';

import './models/shopping_list.dart';
import './models/store.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: 'Grocery Go!'),
);
}
}

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

final String title;

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

class _MyHomePageState extends State<MyHomePage> {

// Some placeholder data just so we can see things working
final List<ShoppingList> shoppingLists = [
ShoppingList(name: "Groceries"),
ShoppingList(name: "House stuff"),
];

final List<Store> stores = [
Store(name: "Safeway", address: "Juanita"),
Store(name: "Safeway", address: "Bellevue"),
Store(name: "Home Depot", address: "Bellevue"),
Store(name: "Fred Meyer", address: "Kirkland"),
Store(name: "Fred Meyer", address: "Bellevue"),
Store(name: "Fred Meyer", address: "Ellensburg")
];

@override
Widget build(BuildContext context) {

const headerShoppingLists = "Shopping Lists";
const headerStores = "Stores";

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: LayoutBuilder(
builder: (BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
MainScreenListHeader(text: headerShoppingLists),
MainScreenList(list: shoppingLists),
MainScreenListHeader(text: headerStores),
MainScreenList(list: stores),
],
),
);
}),
);
}
}

These are the major widgets used in this layout and why I picked them:

Layout Builder – this widget sizes itself to its children at runtime (among other things, but that’s why I picked it). Since I don’t know how many Shopping Lists or Stores the user has, I need to build the layout with that in mind.

SingleChildScrollView – This is a container that scrolls, and you can fill it with whatever you want. I have multiple ListViews inside it but I want them to scroll as a single unit, so I’m going to turn off their own independent scrolling ability and let the SingleChildScrollView handle it instead.

Column – I want my elements to appear in a vertical column, one after another: header, list, header, list, and a Column makes that easy. I had to set mainAxisSize: mainAxisSize.min to get it to work with everything else I have going on.

ListView.builder – I don’t know how many Stores or Shopping lists will be displayed, so I used ListView.builder. There were two important properties I had to set on it:

shrinkWrap: true – I had some trouble getting my ListView to work inside a Column at first. I kept getting a 'hasSize': is not true error. I found this StackOverflow post helpful, particularly Aziza’s reply.

primary: false – setting primary to false disables scrolling for this particular list. I want the SingleChildScrollView to handle the scrolling instead.

Here it is in Simulator: two ListViews inside a Column inside a SingleChildScrollView so they move as a unit. Hooray!

GitHub repo at this step.

Adding ‘add new…’ buttons to each list

The next thing this UI needs is a “Add new list…” and “Add new store…” button at the end of each list. Tapping these buttons will take the user to a page where they can create a list or a store.

I changed the MainScreenList widget to take a listType string, which I will use on the “add new” button itself:

class MainScreenList extends StatelessWidget {

  final list;
  final String listType;

  MainScreenList({Key key, @required this.list, @required this.listType});

...

Also in main_screen_list.dart, I changed itemCount to be the list length plus one more, so that last iteration can be used to draw the button at the end of the list, and the “listType” string that got passed in will used in the title, like so:

...
itemCount: list.length + 1,
itemBuilder: (BuildContext context, int index) {
  if (index == list.length) {
    return ListTile(
        title: Text("Add new " +  listType  + "...")
    );
... 

Back in main.dart, I now pass “shopping list” or “store” to MainScreenList.

children: <Widget>[
MainScreenListHeader(text: headerShoppingLists),
MainScreenList(list: shoppingLists, listType: "shopping list"),
MainScreenListHeader(text: headerStores),
MainScreenList(list: stores, listType: "store"),

Now there is a “Add new shopping list…” string at the end of the shopping lists:

And there is one at the end of the Stores list, too:

You can see these changes in this commit.

And that’s it for Part 2! Here’s a summary of what we did:

  • Drew a quick mockup of what the main screen of the app should look like
  • Ran flutter create to start the project
  • Built some reusable components that are used to build a list of Shopping Lists and a list of Stores
  • Populated those components with mock data
  • Made the main page scroll as one large list

Up next in Part 3: adding more screens and navigating between them.

Building a Flutter app, part 1: installation and setup

One of my favorite classes in OSU’s online CS degree program was CS492 Mobile Development. I’ve always wanted to make my own iOS/Android app and CS492 gave me enough of a foundation to attempt it.

In this multi-part “journal” series, I’ll share all the major steps and decisions I made as I developed a Flutter app.

In this post: some set-up hurdles I encountered on my MacBook. If you want to skip setup and go to the beginning of the code, go ahead to part 2.

Initial Flutter set up

For the most part, setting up Flutter was easy – I followed the official docs and it took me about 45 minutes to get the sample app running. (I’m on a new MacBook running macOS Catalina 10.15.3.)

I ran into a few hurdles, though, which I’ve documented here for other Mac users and for my future self (because I will inevitably go through this again someday).

Adding Flutter to the $PATH on a Mac

I followed the doc’s example of creating a “development” folder in my Users/mandi directory.

The full directory structure surrounding my “flutter” development directory.

I wanted to follow the Flutter documentation example for adding Flutter to my path permanently, but I didn’t know how to find the PATH_TO_FLUTTER_GIT_DIRECTORY on my machine. I know I made a ‘development’ folder, but I don’t know what’s “before” it in its file path.

As it turns out, there’s a handy trick you can do using Finder and a Terminal window to get the full path to a directory or file.

Dragging the ‘development’ folder into Terminal reveals its full path.

Dragging the “development” folder into a Terminal window gives the complete path you need for setting the $PATH.

That was what I needed to run:

export PATH="$PATH:/Users/mandi/development/flutter/bin"
source ~/.zshrc

Unfortunately, this didn’t “stick” on my machine. It worked for the Terminal window I was in, but as soon as I opened a new Terminal window the “flutter” command was no longer found.

It’s still in there if I echo $PATH, so I’m not sure what’s wrong here. But I’m not the only person who ran into this issue, as evidenced by this Stack Overflow post. Kaushik Bharadwaj’s answer explains how to add it to the path file permanently.

In a Terminal window, enter:

sudo nano /etc/paths

Add the full path to the flutter/bin folder [this is what mine looks like, yours may vary] to this file and save it:

/Users/YOURNAMEHERE/development/flutter/bin

On my machine, the paths file looks like this:

Now the “flutter” command persists through Terminal window closures, reboots, etc.

IDE for Flutter

There are a bunch of choices but I’ve only used Android Studio for Flutter development so far. I’m happy with it and it’s pretty good at formatting Flutter’s copious amounts of nested code.

If you choose Android Studio, beware that the default project setting might be “Android”. You can change that by clicking the little Project dropdown in the upper left corner and selecting “Project” instead of “Android”.

That should give you a nice view of the project structure, like so:

This step is unnecessary but it’ll get rid of the weird “Java” folder that isn’t represented in the project structure if you view it in Terminal or Finder and it’ll make your environment look like the one I’ll be sharing in screenshots throughout this journal.

Emulators

There are a few to pick from. I’m on a MacBook and I find that the iOS Simulator runs way better than the Android simulator. In Android Studio, they appear here in the top bar:

On a Mac it “just works” with the built-in Simulator (which is iOS-specific). I’m not sure what’s involved in other dev environments but I’ll come back to this when I try to build for Android later.

Final checks with Flutter Doctor

In Terminal, using flutter doctor will show the status of your flutter setup. You don’t actually need a checkmark next to everything in this list to start coding, but when it’s time to push your app onto a device you’ll want to clear out the “!” and “x” marks where appropriate.

Here is my flutter doctor output at the time of this writing. I’ll come back to these later when it’s time to test on an actual device – this is good enough to get started.

With the project set up, it’s time to move on to Part 2 where I’ll show you how I built the main page’s UI.