Building a Flutter app: “Cross off” feature

This post is part of my “Building a Flutter App” dev journal, which begins here.

In this post: I built the “cross off” feature to my “Grocery Go” shopping list management app.

First, the final product

Watch as items move between the top list (the “active” list) and the bottom list (the “crossed off” list).

Feature list

Here are all the things that should happen when this feature is considered done:

  • When the user taps the item, it is visibly removed from the shopping list and added to the “Crossed off” list below the shopping list
  • The parent shopping list itemCount is decreased by one
  • A “crossed off” item appears at the top of the crossed off items list
  • The time/date of this action is saved to the item so we know when it was crossed off [dateLastMoved]
  • If the user taps a “crossed off” item, it returns to the shopping list and the itemCount is increased by one
  • The time/date of this action is saved to the item so we know when it was added to the list [dateLastMoved]
  • Shopping Lists maintain their own lists of Crossed Off items, so that the user doesn’t see a crossed off item from their “home improvement” list in their “groceries” list – add CrossedOff subcollection to Shopping List

Adding the isCrossedOff property to Item

I thought it might be simple to just have each item track whether it is “active” or “crossed off”. isCrossedOff will be a boolean value on Item instances, so it had to be added to any code that models Item’s data.

That includes item_dto.dart:

class ItemDTO {

  String id;
  String name;
  String date;
  int quantity;
  bool subsOk;
  List substitutions;
  String addedBy;
  String lastUpdated;
  bool private;
  bool urgent;
  bool isCrossedOff;

  String toString() {
    return 'id: $id, name: $name, date: $date, '
        'quantity: $quantity, subsOk: $subsOk, substitutions: $substitutions, '
        'addedBy: $addedBy, lastUpdated: $lastUpdated, private: $private, urgent: $urgent, isCrossedOff: $isCrossedOff';
  }

  Map<String, dynamic> toJson() => <String, dynamic> {
    'id': this.id,
    'name': this.name,
    'date': this.date,
    'quantity': this.quantity,
    'subsOk': this.subsOk,
    'substitutions': this.substitutions,
    'addedBy': this.addedBy,
    'lastUpdated': this.lastUpdated,
    'private': this.private,
    'urgent':this.urgent,
    'isCrossedOff':this.isCrossedOff,
  };
}

models/item.dart:

import 'package:cloud_firestore/cloud_firestore.dart';

class Item {
  String id;
  String name;
  String date;
  int quantity;
  bool subsOk;
  List substitutions;
  String addedBy;
  String lastUpdated;
  bool private;
  bool urgent;
  bool isCrossedOff;

  Item(DocumentSnapshot document) {
    this.id = document['id'];
    this.name = document['name'];
    this.date = document['date'];
    this.quantity = document['quantity'];
    this.subsOk = document['subsOk'];
    this.substitutions = document['substitutions'];
    this.addedBy = document['addedBy'];
    this.lastUpdated = document['lastUpdated'];
    this.private = document['private'];
    this.urgent = document['urgent'];
    this.isCrossedOff = document['isCrossedOff'];
  }
}

new_item_form.dart

    if (formState.validate()) {
      formKey.currentState.save();

      itemFields.date = DateTime.now().toString();
      itemFields.lastUpdated = DateTime.now().toString();
      itemFields.addedBy = "TILCode";
      itemFields.subsOk = true;
      itemFields.substitutions = new List<String>();
      itemFields.private = false;
      itemFields.quantity = 1;
      itemFields.urgent = false;
      itemFields.isCrossedOff = false;

      var docRef = await db.createItem(args.parentListID, itemFields);

and edit_item_form.dart:

  @override
  void initState() {
    print(args.item.date.toString());
    itemFields.id = args.item.id;
    itemFields.name = args.item.name;
    itemFields.addedBy = args.item.addedBy;
    itemFields.date = args.item.date;
    itemFields.quantity = args.item.quantity;
    itemFields.subsOk = args.item.subsOk;
    itemFields.private = args.item.private;
    itemFields.urgent = args.item.urgent;
    itemFields.isCrossedOff = args.item.isCrossedOff;
    return super.initState();

To avoid having to delete my existing items and re-create them through the form just now, I also went into their Firebase documents and added isCrossedOff to my three test items:

Filtering the item stream by isCrossedOff’s value

Next up: adding a second “get item stream” method to database_manager.dart.

Originally, getItemsStream() returned all the items. Now, I want it to only return items where isCrossedOff is set to false, like so:

Stream<QuerySnapshot> getItemsStream(shoppingListID) {
    return shoppingLists.document(shoppingListID).collection('items').where('isCrossedOff', isEqualTo: false).snapshots();
}

A second stream method can return items where crossedOff is true.

Stream<QuerySnapshot> getCrossedOffStream(shoppingListID) {
    return shoppingLists.document(shoppingListID).collection('items').where('isCrossedOff', isEqualTo: true).snapshots();
  }

Back in main_shopping_list.dart I added another use of my ItemListStream widget and pass it db.getCrossedOffStream for the given shopping list ID:

return SingleChildScrollView(
  child: Column(
    mainAxisSize: MainAxisSize.min,
    mainAxisAlignment: MainAxisAlignment.start,
    children: <Widget>[
      ItemListHeader(text: args.list.id), 
      ItemListStream(dbStream: db.getItemsStream(args.list.id), listType: 'item', onTap: _crossOff, onInfoTap: _editItem, parentList: args.list),
      ItemListHeader(text: "Crossed off"),
      ItemListStream(dbStream: db.getCrossedOffStream(args.list.id), listType: 'item', onTap: _moveBack, onInfoTap: _editItem, parentList: args.list),
    ],

Now the items are being filtered by their isCrossedOff value:

Once I saw it working and was satisfied that I could filter the items this way, I decided to do a quick refactor to turn getItemsStream() in database_manager.dart into one method that takes a second parameter indicating whether I want the active items or the crossed off items.

  Stream<QuerySnapshot> getItemsStream(shoppingListID, isCrossedOff) {
    return shoppingLists.document(shoppingListID).collection('items').where('isCrossedOff', isEqualTo: isCrossedOff).snapshots();
  }

Which looks like this when I call getItemsStream():

 ItemListStream(dbStream: db.getItemsStream(args.list.id, false), listType: ...

Making crossed off items look “crossed off” by drawing a line through them

This step was easy – in main_shopping_list.dart, I changed the existing listType param from ‘item’ to ‘crossedOff’.

ItemListStream(dbStream: db.getItemsStream(args.list.id, true), listType: 'crossedOff', ... 

In item_list.dart, I added an additional check for the ‘crossedOff’ list type in the itemBuilder so that an Item instance it still created for it.

...

var listItem;

if (listType == 'shopping list') {
  listItem = ShoppingList(list[index]);
} else if (listType == 'store') {
  listItem = Store(list[index]);
} else if (listType == 'item' || listType == 'crossedOff') {
  listItem = Item(list[index]);
} else {
  print("Unhandled list item type");
}

list_item.dart was already set up to apply a lineThrough style if the listType is ‘crossedOff’.

return ListTile(
      title: Text(buildTitleString(), style: (listType == 'crossedOff' ? TextStyle(decoration: TextDecoration.lineThrough) : TextStyle(decoration: TextDecoration.none))),
...

Crossed off text result:

Moving items between the “active” list and the “crossed off” list

In main_shopping_list.dart, there are two methods that get passed all the way down to the Item instances:

  _crossOff(Item item) {
    print("Remove this id from this list: " + item.id);
  }

  _addToList(Item item) {
    print("Moving this item back to the list: " + item.id);
  }

They are fed into the ItemListStream as onTap: methods. Items that are ‘active’ get the _crossOff method:

ItemListStream(dbStream: db.getItemsStream(args.list.id, false), listType: 'item', onTap: _crossOff, onInfoTap: _editItem, parentList: args.list),

Items that are on the ‘crossedOff’ list get the _addToList method:

ItemListStream(dbStream: db.getItemsStream(args.list.id, true), listType: 'crossedOff', onTap: _addToList, onInfoTap: _editItem, parentList: args.list),

In my first attempt at this, I ended up with two methods that almost looked identical:

    _crossOff(Item item) async {
      await db.updateItemCrossedOffStatus(
          args.list.id,
          item.id,
          {
            'isCrossedOff': true,
            'lastUpdated': DateTime.now().toString()
          }
        );
    }

    _addToList(Item item) async {
      await db.updateItemCrossedOffStatus(
          args.list.id,
          item.id,
          {
            'isCrossedOff': false,
            'lastUpdated': DateTime.now().toString()
          }
      );
    }

They both call the same DatabaseManager method:

  Future updateItemCrossedOffStatus(String parentListID, String itemID, data) async {
    if (parentListID != null && parentListID.length > 0) {
      // adjust the shopping list's item count accordingly
      if (data['isCrossedOff']) {
        shoppingLists.document(parentListID).updateData({'itemCount': FieldValue.increment(-1)});
      } else {
        shoppingLists.document(parentListID).updateData({'itemCount': FieldValue.increment(1)});
      }
      // update the item itself
      DocumentReference itemDocRef = shoppingLists.document(parentListID).collection('items').document(itemID);
      Firestore.instance.runTransaction((Transaction tx) async {
        await tx.update(itemDocRef, data);
      }).catchError((e) {
        print(e.toString());
      });
    } else {
      print("ID is null/has no length");
    }
  }

I refactored them into one method that just flips whatever the item’s current value for isCrossedOff currently is:

    _updateCrossedOffStatus(Item item) async {
      await db.updateItemCrossedOffStatus(
          args.list.id,
          item.id,
          {
            'isCrossedOff': !item.isCrossedOff,
            'lastUpdated': DateTime.now().toString()
          }
        );
    }

Note: I initially set out to use the “ItemDTO” for this update, but I couldn’t figure out how to use it “partially” – ie, the only parts of the item I want to update are the lastUpdated and isCrossedOff fields, but the ItemDTO requires all of the fields to be present. I could copy the entire item into it, but I wonder if there’s just some better way to do this in general…

View this feature’s pull request.

Now the user can cross items off and add them back to the active list by tapping on them. Return to the feature work list.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.