Short source code examples

If you get a Flutter error like this one:

Unhandled Exception: MissingPluginException(No implementation found 
for method canLaunch on channel plugins.flutter.io/url_launcher)

fear not, I get it about once a week. For me it happens every time I add a new plugin to my Flutter project, and then forget to stop my application and restart it. Either that, or you might be working from the command line and forgot to run flutter pub get.

Usually what happens in my workflow is:

As a brief note, on this page I found this example of how to set the size of a Flutter Container:

Container(
    height: MediaQuery.of(context).copyWith().size.height / 3,
);

After looking at what the copyWith method does:

copyWith: Creates a copy of this media query data but with the given fields replaced with the new values.

If you ever need a Dart/Flutter method to format a TimeOfDay variable — i.e., convert a TimeOfDay to a String — I can confirm that this method works:

String formatTimeOfDay(TimeOfDay tod) {
    final now = new DateTime.now();
    final dt = DateTime(now.year, now.month, now.day, tod.hour, tod.minute);
    final format = DateFormat.jm();  //"6:00 AM"
    return format.format(dt);
}

When I was trying to debug a problem that I thought was related to Flutter’s SharedPreferences library, I ended up rewriting a preferences method to use code like this rather than the normal approach:

Future<SharedPreferences> fPrefs = SharedPreferences.getInstance();
fPrefs.then((value) {rez = value.getBool(KEY_ENABLE_NOTIFICATIONS) ?? false; })
   .catchError((e) {
       debugPrint("===== ERROR: ${e.error}");
       return 60;
   });
return rez;

While that ended up being a waste of time, the benefit of my side excursion is that I get to show this example of how to use then and catchError with a Dart future. So if you wanted to see a Dart Future/then/catchError example, I hope this is helpful.

As a quick note, here are two examples of how to use a Future with a Duration delay in Dart (and Flutter):

// example 1
Future<bool> _getFutureBool() {
    return Future.delayed(Duration(milliseconds: 500))
        .then((onValue) => true);
}

// example 2
print('1');
Future.delayed(const Duration(milliseconds: 500), () {
    print('Hello, world');
});
print('2');

If you’re comfortable with Dart futures, you know that the second example will (eventually) print this output:

1
2
Hello, world

As a brief note to self, here’s an example of how to create a popup dialog (AlertDialog) using Dart and Flutter:

As a brief note to self, I was just trying to create a native image of a Scala application with GraalVM, and had this java.lang.NoClassDefFoundError error message:

Here’s a little Scala 3 (Dotty) enum match/case expression example:

As a note about Scala style, this Scala page strongly encourages that side-effect methods that takes no parameters should be declared with parentheses:

“However, this syntax (leaving off parentheses) should only be used when the method in question has no side-effects (purely-functional). In other words, it would be acceptable to omit parentheses when calling queue.size, but not when calling println() (or openGarageDoor()). This convention mirrors the method declaration convention given above.”

“Religiously observing this convention will dramatically improve code readability and will make it much easier to understand at a glance the most basic operation of any given method. Resist the urge to omit parentheses simply to save two characters!”

As a brief note to self, I was experimenting with passing methods as parameters to Scala functions — in particular trying to overload those method signatures to see what would work and what would not work — and I came up with these simple function signature overloading tests:

As a brief note to self, you compile a TypeScript source code file with the tsc command:

tsc Foo.ts

Depending on what you’re doing, you can also run the resulting JavaScript file from the command line with this node command:

tsc Foo.ts && node Foo.js

That command can be read as, “Compile the TypeScript file and then if that compiles successfully, run the resulting JavaScript file.” Note the ts and js extensions on those files.

As a brief note today, here’s a Scala method that writes the strings in a list — more accurately, a Seq[String] — to a file:

def writeFile(filename: String, lines: Seq[String]): Unit = {
    val file = new File(filename)
    val bw = new BufferedWriter(new FileWriter(file))
    for (line <- lines) {
        bw.write(line)
    }
    bw.close()
}

Here’s a brief example of how to sort data that’s already in a Java HashMap. First, some HashMap data:

import java.util.*;

Map<Integer, Float> playMap = new HashMap<Integer, Float>() {{
    put(10,  1f);
    put(12,  2f);
    put(15,  4f);
    put(18,  6f);
    put(20,  6f);
    put(25,  7f);
    put(30,  6f);
    put(35,  5f);
    put(40,  5f);
}};

A HashMap won’t keep that data in sorted order, so if you want your data sorted, one way to sort it is to add the elements to a Java TreeMap:

In an effort to share some source code (but without taking the time to explain it), here’s some Java source code that I just used to create a JFreeChart chart/graph of some data that I use in my Android football game:

If you need to copy a directory on Unix/Linux and want to preserve the date/time information while copying the directory and files, use the -p option to save the date/time information, and the -r option to copy the directory properly. For instance, I just used this cp command to copy a directory named OldDir to a new directory named NewDir, while retaining all of the date/time file information:

I was just going through some old notes and found this Scala DSL example from 2010:

As a brief note today, here’s an example of stackable modifications in Scala.

What is ‘super’ in Scala when you mix in traits?

Lately I was curious about what super means when you mix Scala traits into a class or object. A simplified answer is that super refers to the last trait that’s mixed in, though I should be careful and note that this is an oversimplification.

This can be demonstrated in an example that uses both inheritance and mixins with traits. Given this combination of traits and classes:

If you ever need to left-justify a multiline Scala string, the solution is to use the stripMargin method, as shown in this example:

def getWordFormatted(s: String): String = {
    s"""
      |
      |Word of the Day
      |---------------
      |Word: $s
    """.stripMargin
}

The | character has a special meaning when used in conjunction with stripMargin, so that method results in a string like this being output:

As a note to self, the Scala 3 “Dotty” procedure syntax is going to look like this:

def f() = { ... }
def f(): Unit = { ... }

This Scala 2 procedure syntax is being dropped:

def f() { ... }

You can find the official Dotty procedure syntax page at this link.

As for me, I’m adding this page right now because I noticed today that this procedure syntax (without the parentheses) also works with Dotty:

I can never remember how to create a Scala 3 (Dotty) project with SBT (in early 2019), so:

# create a new Dotty project
sbt new lampepfl/dotty.g8

# create a dotty project that cross compiles with scala 2
sbt new lampepfl/dotty-cross.g8

# start a dotty reply from within your sbt project
$ sbt

> console
scala> _

Here’s what an example interaction looks like — include SBT renaming my directory name to all lowercase, which brings me no joy: