Flutter: Design to app like a pro

Posted on Leave a comment

Sharing with ya’ll the recording of my session from Sapient’s April 11 Flutter meetup.

Warning: This is a longish session (48 mins). Watch at your discretion. You have been warned.
(I really need to work on my time-boxing skills)

Do also see the other 🆒 sessions in this playlist:
https://www.youtube.com/playlist?list=PLfZqxzeCGmPUWopRNcf86Kmusrog73yhL

Use Flutter’s FutureBuilder with care

Posted on 1 Comment

I learned this the hard way. I knew Flutter’s stateless and stateful widget lifecycles well. But I was ignorant.

I made a grave, mostly fatal, mistake of doing something like this:

FutureBuilder<List<Product>>(
  future: this.productRepo.getProducts(),
  builder: (context, snapshot) {
    ...
)

class ApiProductRepo implements ProductRepo {
  Future<List<Product>> getProducts() async {
    // Call an API to get products
    // Return products
  }
}

Do you see the graveness of my code? No? Check again, I’ll wait.

Okay. Maybe you’ve guessed it, maybe not. See the code below. This is the culprit:

future: this.productRepo.getProducts()

FutureBuilder’s official docs say:

The future must have been obtained earlier, e.g. during State.initState, State.didUpdateConfig, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder’s parent is rebuilt, the asynchronous task will be restarted.

A general guideline is to assume that every build method could get called every frame, and to treat omitted calls as an optimization.

https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

Commit the bolded line in memory. For like ever. Otherwise, you’ll end up in the same trap as I. Flutter makes app development so seamless and fun that at times you forget basic optimizations. In my case, I was using a third-party metered API and found myself hitting close to my daily quotas 4x sooner than anticipated. That’s because FutureBuilder was calling the API 4 times, once on each widget rebuild.

My fix was simple: convert my stateless widget to a stateful one and cache API response in state.

class ProductListScreen extends StatefulWidget {
  static const id = 'product_list';

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

class _ProductListScreenState extends State<ProductListScreen> {
  List<Product> products;

  /// Returns recipes in cache-first fashion.
  Future<List<Product>> _getProducts() async {
    if (this.products != null) {
      return this.products;
    }

    final productRepo = Provider.of<ProductRepository>(context);
    this.products = await productRepo.getProducts();
    return this.products;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<List<Recipe>>(
        future: this._getProducts(),
        builder: (context, snapshot) {
          ...
        },
      ),
    );
  }
}

Follow this advice, and save tonnes of troubles later.

Mocking Firestore in Flutter

Posted on Leave a comment

I have been writing unit tests like crazy for my muse Flutter app, in my own TDD-like fashion. Writing meaningful tests and watch them go from red to green is a great feeling for real. If you aren’t doing that yet, I highly recommended.

Flutter comes with an excellent testing library called — wait a minute — test. It has one of the most comprehensive set of assertion matchers I have ever seen.

  • Want to test a type? Check.
  • Want to test a future? Check.
  • Want to test an error emitted by a stream? Check.
  • Want to test if your method accidentally rings your neighbor’s door? Umm, well, you gotta do it yourself.

A lot of times you will need to create mocks to avoid side effects in your production database or APIs. Mockito is an awesome package for that. While Mockito works great for general-purpose mocking, I found cloud_firestore_mocks to be closer to the real deal in my testing.

I have used it so extensively in my own tests that I found myself wanting for more. cloud_firestore_mocks, as awesome as it is, does not yet support 100% of Firestore’s APIs. For example, it does not yet support arrayContainsAny where query clause. Same is true for startAt and endAt.

I wanted it so much that I implemented it myself and sent a pull request to Ahn, cloud_firestore_mocks original author. The PR has been merged and the change will land on pub.dev soon. More power to open source!

If you are using Firestore with Flutter, check out cloud_firestore_mocks today and save yourself shit loads of time troubleshooting bugs later. Highly recommended.

A joke only Flutter developers would understand

Posted on Leave a comment

Developer: “YESSS! My world-class widget test is ready to run.”

(runs the test)

Debug Console: “Expected to see 1 widget, found none.”

Developer: What! Why, why, why!!!

(figures out all async calls in the widget; spends 4 hours re-reading about widget testing, exploring the source code of WidgetTester.pump() and setting up mock classes using Mockito.)

Developer: “Muwaha haha! I am the greatest mocker ever lived.”

(runs the test again)

Debug Console: “A RenderFlex overflowed by 20 pixels on the right.”

SS Menu: A simple orders mgt. app for restaurants

Posted on Leave a comment
SS Menu logo

More than 2 years ago, I created a lightweight point of sale system (POS) for our restaurant in Jalandhar called SkewerSpot (SS). I wrote the thing in under a week (cowboy coding, yodlee yodlee youdoo) in Ionic/Angular. Essentially, it’s a collection of hybrid mobile apps that allows a restaurant to manage orders in real-time via Firebase. The 3 apps in this collection are:

  1. SS Menu — to take orders
  2. SS Orders — to manage orders
  3. SS Stats — to view sales data

Nothing too complicated. The thing has been running quite reliably since 2.5 years. So why the rewrite?

Recently, Dad asked me to change a few things in SS Menu. When I got to working on the changes, I realized that my Ionic tooling had somehow become broken. I just couldn’t create new builds. I left it as is and informed Dad I didn’t have sufficient time to fix things around. But he insisted. So much that I finally decided to just rewrite the entire thing in a more modern mobile SDK — Flutter.

I donned my cowboy hat again and sat down to create the menu app from scratch using a skill I had just recently acquired. I think I was able to spit out a functional version of the app in 4-5 non-contiguous days. Creating in Flutter is such a blissful experience. I loved every bit of it.

Flutter makes it infinitely easy to create 100% custom interfaces inspired by designs at Dribbble. You are never crippled by the difficulty of customizing platform’s underlying UI controls. You are always in the driver’s seat.

— Me, after having created several Flutter apps based on designs at Dribbble

Unlike the last time, I created the app from day 1 with open-sourcing in mind. I also made sure that my git history was readable enough to help others starting in the world of Flutter learn quickly from my development experience.

But due to a lack of time, I had to make certain trade-offs: the code lacks automated tests, i18n, l10n and accessibility options. There’s also no iOS version as of now. What a bummer!

Check out the code and more details about the app on GitHub:

https://github.com/anuragbhd/ss-menu-app

Help me, if you can, take it to the next level by fixing the caveats and implementing TODOs.

Some screenshots to feast your eyes on: