Flutter 💙 The widgets are trees 🌲 your app is a forest 🌲🌲🎄

These are a few of the things I wish someone had shown me when I first started learning Flutter.

Ten Thousand
Source: xkcd, May 2012 via the Flutter Code of Conduct

To start, if things aren’t working and you aren’t sure why try running flutter clean, it’s kind of a magic fix all.

flutter clean

On Android it can help to manually delete the cache folder inside of bin and on macOS deleting podfile.lock is worth trying.

If you run into any version conflicts a good approach to fix it is to set the version to any (@koorankka), run upgrade again, and if it completes check the pubspec.lock file for the version it resolved to and use it in the pubspec.yaml file.

I also strongly recommend bookmarking the “Workarounds for common issues” page in the Flutter Wiki, in particular the section on pub dependencies.

Related to this if your project fails to open correctly in Android Studio you should be aware of the “Invalidate Caches” option.

invalidate_caches

Also in Android Studio the keyboard shortcuts (@pblead26) I use constantly are Shift + F10 to run the app, Ctrl + Alt + L to format it and Alt + Enter to show the context menu.

I’m a huge fan of dartfmt, and love how it makes the code consistent. I find it can be helpful to run:

flutter dartfmt lib

To apply formatting across the entire project, in particular this can help clean up future git commits.

A default Flutter project has pretty forgiving linting rules, you can use the sames rules as the Flutter team by downloading the analysis_options.yaml file from the repo. I highly recommend this if you’re new to Dart as it can help reinforce some best practices when getting started.

Quick shout out to Effective Dart, an amazing resource for learning Dart.

In general Flutter’s errors are extremely clear, however the Gradle build errors are sometimes a bit less informative. A useful trick is to open the android folder of the project directly in your IDE and build the app from there, it can sometimes reveal more details about the problem.

fluttersamples.com (@brianegan) is a great site to help understand the many different architecture choices available and awesome-flutter (@BlueAquilae) definitely lives up to its name.

One mistake I continue to make is to mix up the use of parentheses. For example, either of the first two are fine however if you map the property directly to the called function it will cause it to be called repeatedly most likely crashing the app and if you’re really lucky it will take down your IDE with it.

onPressed: onPressed // OK 
onPressed: () => onPressed() // OK
onPressed: onPressed() // VERY BAD!!!

Another common error is dealing with the ‘need layout/need paint’ error in rows and columns. The short answer is try adding an Expanded or Flexible widget, for a more detailed explanation checkout this great series (@scottstoll2017).

Lastly in the ‘mistakes I continue to make’ category is remembering to add .toList() when using a map to general a list of widgets.

I still rely on print statements for debugging more than I’d like to admit but by default the output can be cut off. You can use debugPrint and set a value for wrapWidth to workaround this.

debugPrint(string, wrapWidth: 1000);

Finally, here are few key Flutter links to be aware of. The projects page in the Flutter repo on GitHub provides a great high level view on what the Flutter team are actively working on. This list of links from GitHub is an excellent collection of docs detailing where the project is going in the future and the wiki has a ton of great info.

Let me know if you think I missed anything in the comments and I’ll update the post.

Hope you found this useful! You can follow me on Twitter @hillelcoren or checkout some of the projects I’m working on:

Update: here are some additional suggestions from the community:

Announcing a rewrite/version 2.0 without causing a panic

When we decided to start from scratch and build a v2 of Invoice Ninja one of our first actions was drafting a blog post to share with our community.

Before sharing it with everyone we initially posted it in our Slack group. I can’t overstate how valuable the feedback was. I thought it may be worthwhile to share the before/after versions of the post.

Here’s the initial draft.

Fork In The Road

We’re coming up on five years since we first started working on Invoice Ninja and are at a critical point in our company’s story.

When we first started working on the app we were experienced developers & marketers with basic understanding of invoicing. Over this time we’ve had the opportunity to learn a tremendous amount about invoicing practices around the world.

Although we’ve taken great care to keep our code to a high quality, a combination of domain considerations and changes to our underlying frameworks have made our code less than the perfect ideal we’re striving for.

We now have a choice to make. We can either maximize immediate profits and short terms gains, or work to reduce our technical debt creating a stable platform for the future. We choose the latter.

Our plan is simple… while building the new version, hosted platform users will continue to receive security and bug fixes. Once we’ve completed the core features existing users will be able to easily migrate over.

For self-host users we’ll create a branch in our GitHub repository which will include new features added by the community. We’ll also continue to improve our new mobile app making sure it’s entirely feature complete.

We’re at the beginning of something amazing. As always, we will be completely transparent with our work. You’ll be able to follow the development process in our GitHub repository, the new version will of course be entirely open source.

If you have any concerns please don’t hesitate to contact us. We see this as a great opportunity and hope with your input we’ll be able to create an even more outstanding invoicing platform.

Here is some of the (extremely helpful) feedback we received:

  • Rob: Is this a v2 or something else?
  • Gijs Rutten: Is there a migration process?
  • Billyggla: Those who have used Invoice Ninja will understand the post and the reasons behind it. However someone new to Invoice Ninja reading the post may come away with “Although we’ve taken great care” “less than the perfect ideal” “maximize immediate profits”. It may be simpler to put across the point that Invoice Ninja is at the forefront of invoicing software and you can continue to use it while we focus on…
  • Nateamus: Transparency is the key to any successful open source project but I think you can be a little to militant about it to the point of creating fear. Really, the net effect of this will be a vastly improved experience once everything has been refactored. Instead of posting about how you’ve “…taken great care” etc etc, I would simply inform the user base that you have bandwidth constraints and perhaps won’t be as responsive to requests because you are focusing on improving the core product. I agree with Billy that it may be a tad alarming. The net effect is going to be amazing with no change in vision, mission or direction, just perhaps less bandwidth. Perhaps that could be the focus.
  • Olivier B. Deland: I think your post is maybe too “developer-friendly”. I would start with something more client-friendly, saying that you are starting a 2.0 version which will allow you to pump more great features faster in the future, cleaner UI, or whatever, etc. Then, start a new sub section with the transparency details for people who are more interested in those things. Non-technical people, who will just stop reading at this point, need to be reassured already that everything is fine and for the better.

Finally, here’s the revised version incorporating the feedback.

Invoice Ninja v2.0

We’re excited to announce that we’re starting work on a major redesign of Invoice Ninja! By upgrading to the latest and greatest web technologies we’ll be able to provide more features at a faster rate.

We’re a small team, accomplishing this task will requires us to slow down feature development of the current version while we focus on v2.0. Once the new version is ready you’ll be able to click a button to migrate all of your data and settings.

For self-host users we’ll create a branch in our GitHub repository which will include new features added by the community. We’ll also continue to improve our new mobile app making sure it’s entirely feature complete.

As always, we will be completely transparent with our work. You’ll be able to follow the development process in our GitHub repository, the new version will of course be entirely open source.

If you have any concerns please don’t hesitate to contact us. We see this as a great opportunity and hope with your input we’ll be able to create an even more outstanding invoicing platform.

Thankfully our announcement went extremely well. I believe the revised post does a much better job of explaining our intentions without causing unnecessary fear. I’m extremely grateful to our community for their help here and of course their ongoing support of our project. We’re a few months in now… v2 is coming along great.

 

android-chrome-512x512

An architectural review of the Invoice Ninja Flutter app

We’ve been working on our Flutter mobile app for a few months now, I thought it may helpful to share some of the techniques we’re using to help keep our code maintainable.

OpenSourcedResized

Create widgets!

Keep your code DRY (don’t repeat yourself). Refactoring widgets is just like refactoring standard code, look for patterns of duplicate code and refactor it out to a widget. Widgets can be incredibly small but if used throughout the app they both reduce code and make it easier to apply changes later on.

For example we created an ElevatedButton widget which wraps a standard RaisedButton class so it always has a consistent elevation and enables setting the color or applying an icon. Another example is this IconText widget which just makes it easier to show an icon and text together.

Wrapping/extending widgets is a great way to customize the framework to suit your needs. We try to follow the convention where the name of the widget is the concatenation of the child widgets it combines.

View models

One of the core principles of software architecture is SRP (Single Responsibility Principle). As the views get more complicated a great way to implement separation of concerns is to create a view model which backs the view.

This enables the view to focus on the layout of the UI while the view models manage the view logic. For example, the view model would handle preparing data (ie, caching using memoize) from the central store to the format needed by the view and provide methods to dispatch actions to update the store.

Completers

In the app it’s common for the user to trigger an action in the UI which depends on completing a successful request on the server. For example, saving a new record.

Initially we passed the context in the action and had the middleware use the context, however we’ve found using completers provides much cleaner code in the UI layer.

We use a utility class to create common completer types. For example. a snackBarCompleter will show a SnackBar message if the request completes successfully or a modal ErrorDialog if the request fails.

final completer = snackBarCompleter(context, localization.archivedProduct)
store.dispatch(ArchiveProductRequest(product.id, completer));

There’s also a popCompleter which is used by actions dispatched from dialogs which will automatically close the dialog and return the response message in the call to pop().

Enums

Our app has many modules, for example: clients, products, invoices, tasks, expenses, … They all provide similar functionality (list, view, edit, archive, delete, restore) and then some provide other actions such as invoice or email.

To support this we use built_value enums. In this case we have an EntityType enum and an EntityAction enum. A nice aspect of this solution is it’s automatically serialized/deserialized when the state is persisted.

Our custom widgets then can accept an EntityType parameter which can be used to configure itself from the store. We’ve also added a lookup function in the AppLocalization class to help with translations.

Persistence

Our solution to persistence is to split up the core parts of the store (data, UI and auth) to persist each part separately. As a user makes changes to a new record we can constantly persist the UI store without needing to persist the data store which could potentially have tens of thousands or records.

If a user starts to create a new record and then quits the app we’re able to present the partially completed record when the app is relaunched. This is handled in the code by having any action which requires persistence (such as when data is loaded or modified) implement the PersistData or PersistUI abstract classes.

class SortProducts implements PersistUI {
  final String field;
  SortProducts(this.field);
}

Abstract classes

We have two types of data in the app: editable entities which the user can create and edit (such as clients and invoices) and static data which can be referenced but not changed (such as the list of languages or currencies).

To support typical interactions in the app (ie, selecting a choice from a list) we’ve created a SelectableEntity abstract class. The built_value classes then implement the class. This provide a way for each entity type to define how it should be presented and searched in a list, we use the subtitle of the ListTile to show the matching field. This class is implemented by both types of data.

The editable entities implement the BaseEntity class which provides shared functionality such as archiving and deleting and handles filtering the list by their state (active, archived or deleted) and status (ie, draft, sent, paid, …).

Clean code

If you’re just getting started I’d highly recommend using a more comprehensive analysis_options.yaml file. Our approach was to start with the Flutter project’s file and comment out if needed. This can be harder to change in an existing app as it can generate thousands of new warnings.

Hope you found this useful, if anything’s unclear or can be improved please let me know. You can follow my thoughts on Flutter on my Twitter feed or subscribe to the blog for more posts. Thanks for reading!

Continue to part 5 >>

Flutter API Docs Sorted by Length

It goes without saying that one of the best sources for information about Flutter are the API docs. Many of the widgets provide detailed explanations with useful samples.

If you have a specific widget you’re trying to use the docs are extremely helpful but if you’re new to Flutter and just want to do a bit of reading up it can be hard to find some of this great content. So of course as a developer I wrote a script…

The following list shows the widgets included in the material library sorted in reverse order by length of the explanation text.

 

Follow me on Twitter for more post related to Flutter.

flutter-logo-sharing

Dart for JavaScript Programmers

My perspective on Dart has quickly changed from being a language I needed to learn to build something with Flutter to a language I enjoy using on a daily basis.

dartlang-card

When starting with Flutter you often hear that Dart is just like JavaScript. Well, it is… except for when it isn’t. I thought it may be helpful to highlight some of the subtle ways in which Dart differs from JavaScript to make it easier to get up to speed when switching languages.

Conditions must have a static type of ‘bool’

In addition to types, Dart is in general a stricter language. In JavaScript you can use any ‘truthy’ value in a conditional. For example:

var name = 'Joe';
if (name) {
  // do something...

If you try the equivalent code in Dart you’d see “Conditions must have a static type of ‘bool'”. The reason is that Dart requires that a condition is a bool true not just a ‘truthy’ value. You could correct the code by changing it to:

if (name.length > 0)

But the preferred approach would be:

if (name.isNotEmpty)

Related to this, there is no triple equals (===) in Dart.

As a side note I saw this great tip on Twitter to use the same analysis_options.yaml as the Flutter team. It’s been a big help getting up to speed with Dart best practices in general.

Where is console.log

Although I’m constantly trying to train myself to rely on the debugger old habits die hard. In place of console.log you can use print. Dart supports string interpolation so whereas with JavaScript you may write:

console.log('Name is %s', name);

With Dart you’d use:

print('Name is $name');

If you need to access properties on the variable or call functions you can wrap it in curly braces.

print('Length is ${name.length}');

Function Parameters

This is one area where I think JavaScript and Dart are the most different. Dart provides a far more powerful implementation but it can take a bit of time to adjust to.

This answer on StackOverflow by Seth Ladd does a great job of explaining the differences in detail. At a high level with Dart you can either pass parameters in set positions:

getFullName('John', 'Doe');

Or you can pass them by name:

getFullName(firstName: 'John', lastName: 'Doe');

For constructors you can use this.fieldName to tell Dart that the value passed should be assigned to the property.

Contact(this.firstName);

Handling Arrays

Arrays are mainly the same but there are a few differences worth pointing out. A key difference is that you add an item to array by calling add rather than push.

Dart provides helper methods first and firstWhere which you may not be surprised to learn returns the first item in the array. What’s less obvious is that by default if a match isn’t found the methods will throw an error. You can handle this case by specifying a value for orElse which will be returned if no item is found.

Final and Const

This one took a while for it to sink in. I think this post does the best job explaining the differences that I’ve found. The key difference between final and const is that ‘final’ describes the variable whereas ‘const’ describe the value itself. A final variable can only be set once but the value it points to can be changed, a const’s value is frozen and can not be changed.

Another good tip you’ll get from using the Flutter analysis_options file is to use const constructors where possible when creating your widgets. This can have a great impact on your app’s performance by enabling the framework to cache the widgets.

Fat Arrow

The ‘Fat Arrow’ or => can be used for single line functions. For example, instead of:

someField: () {
  return true;
},

You could write:

someField: () => true,

It seems like a small difference but it can definitely have a positive impact on the readability of the code.

Odds & Ends

To wrap up here are a few other points worth keeping in mind.

  • To convert a value (for example) to a double you can either use double.parse or double.tryParse. The former will throw an error if it fails whereas the latter will not.
  • You can use null-aware operators (ie contact?.firstName) to make it easier to handle null values. This post (also by Seth) does a great job explaining it in detail.

Hope this helps, if anything’s unclear please let me know and I’ll update it.

 

Flutter: Using Redux to manage complex forms with multiple tabs and relationships

The full code for this post can be found here.

In my last post I described how we’re using keys to manage the state of complex forms. Although the implementation works having any state outside of our main Redux store meant that persistence was incomplete. For example, if a user started to create an invoice and then closed/reopened the app before saving their work would be lost.

Screenshot_1528817346

I had initially decided to keep some of the state separate due to the large size of our store. A user can have up to five companies linked under a single account. Each company can have thousands of clients, invoices, etc. Having to constantly write the state to disk would be CPU intensive. To solve this we’ve modified our persistence middleware to save parts of the state separately and then piece it back together when initializing the state on load.

Many of the actions in our app require persisting either data state (ie, a list of clients) or UI state (ie, the current sort field). In order to prevent having an extremely long list of actions in the reducers we’ve create two base classes PersistData and PersistUI. Actions that require either can add them as mixins. We use the same approach to track the if the app is currently loading data or not.

Here’s an example with some of the client actions.

class LoadClientRequest implements StartLoading {}

class LoadClientSuccess implements StopLoading, PersistData {
 final BuiltList<ClientEntity> clients;
 LoadClientSuccess(this.clients);
}

class LoadClientsFailure implements StopLoading {
 final dynamic error;
 LoadClientsFailure(this.error);
}

class SortClients implements PersistUI {
 final String field;
 SortClients(this.field);
}

We’re using a shell script to help quickly generate some of the boilerplate Redux code. Using the mixins has the added benefit that it requires far fewer manual adjustments to the code once it’s generated.

You can see a full example here. We’re using Redux to manage a client’s details across multiple tabs. There are a few implementation details worth pointing out.

  • The code for the reducer is a bit unwieldy. In an actual app you’d most likely use built_value which provide a clean way to handle immutability.
  • In order to update the TextControllers with the state from the model overriding didChangeDependencies seems to work best.

Hope you found this post useful. If you can see any ways to improve the code feedback is greatly appreciated!

Continue to part 4 >>

Flutter: Complex forms with multiple tabs and relationships

Note: we’re no longer using this approach, you can see our updated solution here.

In our app we needed to support editing complex entities with nested relationships, in this post I’ll try provide a high level overview of our solution.

The full code for this post can be found here

Screenshot_1528817346

For this example we’ll use a Client entity which has a name and a list of contacts, each contact has an email address.

class ClientEntity {
 ClientEntity({this.name, this.contacts});
 String name;
 List<ContactEntity> contacts;
}

class ContactEntity {
 ContactEntity({this.email});
 String email;
}

Dividing the UI into multiple tabs is relatively straightforward however as soon as we started testing we realized if a user made a change in one tab and then switched to a different tab without first clicking save their changes would be lost. Not good…

The solution is to have the state class use the AutomaticKeepAliveClientMixin. Adding the mixin is pretty simple, you just need to override the wantKeepAlive method to return true.

class ContactsPageState extends State<ContactsPage>
 with AutomaticKeepAliveClientMixin {

 @override
 bool get wantKeepAlive => true;

For most simple forms you can use keys or text controllers to access the text input values however with arrays/relationships it gets a bit more complicated. The approach we’re using is to have the master page create global keys for the sub-pages to use.

On the contacts page we store two lists for the contacts: the contact models as well as the keys for the contact form state.

List<ContactEntity> _contacts;
List<GlobalKey<ContactFormState>> _contactKeys;

@override
 void initState() {
  super.initState();
  var client = widget.client;
  _contacts = client.contacts.toList();
  _contactKeys = client.contacts
    .map((contact) => GlobalKey<ContactFormState>())
    .toList();
 }

To build the view we loop through each of the contacts/keys. When initially working on this whenever we focused the text input the focus would be lost, this was caused by using anonymous keys which were being recreated every time the view was rebuilt. The solution was to just make sure we reused the same keys when rebuilding the layout.

for (var i = 0; i < _contacts.length; i++) {
   var contact = _contacts[i];
   var contactKey = _contactKeys[i];
   items.add(ContactForm(
     contact: contact,
     key: contactKey,
     onRemovePressed: (key) => _onRemovePressed(key),
   ));
 }

When the user clicks save the master page can use the keys to generate a new client from a combination of the existing client and the changes in the form. We need to check if the state is null in case the user clicks save without first viewing the second tab.

 ClientEntity client = ClientEntity(
   name: clientState?.name ?? _client.name,
   contacts: contactsState?.getContacts() ?? _client.contacts,
 );

There’s one caveat, as of right now I haven’t been able to make this work with more than two tabs. I believe it’s a bug, I’ve opened a GitHub issue for it and hope it will be resolved before our app launches 🙂

Hope you found this post useful, if you have any suggestions to improve the code please let me know.