Wednesday, February 26, 2025

An Android Studio Live Template to simplify defining loggers in Flutter

This morning, I came across a discussion on the Flutter Forum about logging. I recently added rudimentary logging support to a side project, and I was interested to hear the perspectives of people with a lot more Flutter experience. Using Android Studio's Live Templates to reduce boilerplate sounded like a good idea. In my case, for every class where I want to log something, I want something like this:

final _logger = Logger('$MyWidget');

The dollar sign there is important because it uses string interpolation to insert the name of the class. If I rename the class, the refactoring tools in Android Studio will also replace this reference.

I don't remember the last time I made a Live Template for a JetBrains IDE, or if I ever have, so I decided I should take a not here. 

I created my Live Template in the "Dart" category. This is not necessary, but it is sensible. I called it "logger" and it looks like this:

final _logger = Logger('$$$CLASSNAME$');

Under "Edit Variables," I configured CLASSNAME to use the expression dartClassName(). Checking "Skip if defined" means that keyboard focus skips over the variable after expanding the template, which is a nice feature. I set the context to Dart/Other.

Using double-dollar-signs to escape a dollar sign is a little strange, but once I got past that, it was easy to set up. One unexpected pitfall is that if you erase a variable from the template and then retype it, you have to remap it to an expression: the IDE doesn't "remember" that the variable had a previous definition while working on the template body.

No comments:

Post a Comment