Author: Mathias Lipowski

Dart: code snippets for faster coding

There are different concepts that improve the data handling in Dart. The following list of snippets is a collection of the most handy once. Warning: this might simplify your code a lot! 😉

The Spread Operator

Dart supports the spread operator, which allows to insert a collection (multiple elements) into a collection:

var values = [1, 2, 3];
var moreValues = [...values, 4, 5, 6];
print(moreValues);
// [1, 2, 3, 4, 5, 6]

Operators

Dart supports different operators. You can implement many of these operators as class members.

DescriptionOperator
unary postfixexpr++    expr--    ()    []    .    ?.
unary prefix-expr    !expr    ~expr    ++expr    --expr      await expr 
multiplicative*    /    %  ~/
additive+    -
shift<<    >>    >>>
bitwise AND&
bitwise XOR^
bitwise OR|
relational and type test>=    >    <=    <    as    is    is!
equality==    !=
logical AND&&
logical OR||
conditionalexpr1 ? expr2 : expr3
cascade..    ?..
assignment=    *=    /=   +=   -=   &=   ^=   etc.

Merging Two Maps

The code snippet below merges two maps. All (key) values in default are available in the merged map. This snippet only works for single level maps, multidimensional maps are only handled on the first level:

var options = {
    "hidden": "false",
    "option": "3",
};
var defaults = {
    "hidden": "true",
    "escape": "false",
};
options = {...defaults, ...options};
print(options);
// {hidden: false, escape: false, option: 3}

Default Value

To set a default value for a nullable variable, you can use the “if null” operator ‘??’:

const defaultValue = "Default";
final someVar = null;
var expectingValue = someVar ?? defaultValue;
print(expectingValue);
// "Default"

if and for in Collections

Dart offers an easy way to create dynamic lists by using conditionals (if) and repetition (for):

var nav = [
  'Home',
  'Furniture',
  'Plants',
  if (promoActive) 'Outlet'
];
var listOfInts = [1, 2, 3];
var listOfStrings = [
  '#0',
  for (var i in listOfInts) '#$i'
];
assert(listOfStrings[1] == '#1');

String to Number

var stringValue = "123";
var intValue = int.parse(stringValue);
print(intValue);
// 123 (int)
var stringValue = "123.45";
var doubleValue = double.parse(stringValue);
print(doubleValue);
// 123.45 (double)

Numbers to String

Most of the Dart data types support a toString() method, which allows a conversion to strings. This is very handy for every parameter where a string is needed:

int intValue = 123;
var stringValue = intValue.toString();
print(stringValue);
// "123" (string)

GitLab – ERROR: Registering runner… failed, certificate signed by unknown authority

If your self-hosted GitLab server is using a self-signed certificate for https, it might be possible that you get an error during the registration of a GitLab Runner:

ERROR: Registering runner... failed        runner=HbU25D-y status=couldn't execute POST against https://gitlab.example.com/api/v4/runners: Post https://gitlab.example.com/api/v4/runners: x509: certificate signed by unknown authority
PANIC: Failed to register the runner. You may be having network problems.

To solve the problem, you have to provide the full chain certificate *.pem used by your GitLab Server:

gitlab-runner register --tls-ca-file /path/to/fullchain.pem

In my case, the valid certificate could be found on the GitLab server in /etc/gitlab/trusted-certs/fullchain.pem. This one was copied to the GitLab Runner server and used in the command above.

As I did not set up the server on my own, I do not know if this is the default path and filename of a certificate signed by Let’s Encrypt. But in my case, this one worked to register the runner.

Which programming language is the best one?

Is it really possible to answer this question?

Yes, the correct answer is: all of them. Or let’s ask another question first: for which problem?

There is not “the one and only” best programming language, there are tons. This question is simply not a good one. It’s good for endless discussion, but it’s neither complete, nor does it give you details about the problem to solve. An answer will not solve the unknown problem of the author. Every coding language has it advantages when it comes to solving a specific problem. But which one? There are advantages for JavaScript, Python, PHP, Java, Swift, Dart and others. But what if the author wants to write some firmware for a micro controller? Ok, you see the point.

But why do people ask those questions?

I see a lot of such questions posted on all social platforms. And as those questions are so incomplete, there are no correct answers. The results are endless discussions about the advantages of each coding language. And this is what most of the authors want: an open question which leads to endless attention. In detail: likes and retweets to pretend the algorithms to be an interesting account. Honestly, no one reads through thousands of responses. And if yes, you only see the advantages that each comfortable developer or user sees in his area of expertise. This might lead to some short attention, but it will never create some high quality and valuable content fo the users. And that’s a pity.

And what about: iOS or Android? Windows or macOS? Python or JavaScript? Same thing! The answers are just a time wasting mess.

Photo by Donald Giannatti on Unsplash.

Flutter: rounded corners for images

There are different possibilities to create a rounded corner of images:

ClipRRect

ClipRRect(
  borderRadius: BorderRadius.circular(10.0),
  child: Image.network(
    'https://example.com/image.jpg',
    height: 100.0,
    width: 100.0,
  ),
),

BoxDecoration

Container(
  height: 100.0,
  width: 100.0,
  decoration: BoxDecoration(
    image: DecorationImage(
      fit: BoxFit.cover, 
      image: NetworkImage('https://example.com/image.jpg'),
    ),
    borderRadius: BorderRadius.circular(10.0),
  ),
),

Photo by Chaitanya Tvs on Unsplash

brew: install Java on macOS

The following steps will guide you through the installation of Java on macOS.

First, check the available Java related formulas:

% brew search java

==> Formulae
app-engine-java              java                         javacc                       jslint4java                  pdftk-java
google-java-format           java11                       javarepl                     libreadline-java

Currently, there are two different version of Java: java and java11. To check the version of both, you can use the following commands:

% brew info java

openjdk: stable 16.0.1 (bottled) [keg-only]
Development kit for the Java programming language
https://openjdk.java.net/
Not installed
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/openjdk.rb
License: GPL-2.0-only with Classpath-exception-2.0
% brew info java11

openjdk@11: stable 11.0.10 (bottled) [keg-only]
Development kit for the Java programming language
https://openjdk.java.net/
Not installed
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/openjdk@11.rb
License: GPL-2.0-only

Depending on your requirements, you can install one of the above. For me, some of the libraries I use in Dart are currently not compatible with the latest Java version (16.0.1), so I decided to install Java 11 with LTS (long term support).

% brew install java11

This will install Java version 11.0.10 as listed in the output above. The output also shows the following hints:

For the system Java wrappers to find this JDK, symlink it with
  sudo ln -sfn /usr/local/opt/openjdk@11/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-11.jdk

openjdk@11 is keg-only, which means it was not symlinked into /usr/local,
because this is an alternate version of another formula.

If you need to have openjdk@11 first in your PATH, run:
  echo 'export PATH="/usr/local/opt/openjdk@11/bin:$PATH"' >> ~/.zshrc

For compilers to find openjdk@11 you may need to set:
  export CPPFLAGS="-I/usr/local/opt/openjdk@11/include"

For me it was necessary to called the specified command, so that the system finds the java binary:

sudo ln -sfn /usr/local/opt/openjdk@11/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-11.jdk

To see if Java was installed correctly, you can check the version of Java:

 % java --version

openjdk 11.0.10 2021-01-19
OpenJDK Runtime Environment (build 11.0.10+9)
OpenJDK 64-Bit Server VM (build 11.0.10+9, mixed mode)

That’s it!

Photo by Adam Wilson on Unsplash

Flutter: enable scroll-to-top for nested Scaffolds (e.g. in IndexedStack)

When using nested Scaffolds (e.g. in combination with IndexedStack), the PrimaryScrollController is not usable by default. An IndexedStack will load all subviews so scroll-to-top will change all scrollable views at the same time, even if they are not visible or it simply does not work, because the PrimaryScrollController can only be attached to a single Scaffold.

To overcome this issue, the scrolls_to_top package can be used. This also works for nested Scaffolds. The functionality of the package is described in this post (here is the english translation).

The following code example shows the usage. This is how to use ScrollsToTop within each children of IndexedStack:

  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      primary: true,
      body: ScrollsToTop(
        onScrollsToTop: (event) {
          // onScrollsToTop will be called on each touch event, so check if the view is currently visible
          if (!widget.isOnScreen) return;

          _scrollController.animateTo(
            event.to,
            duration: event.duration,
            curve: event.curve,
          );
        },
        child: ListView.builder(
          itemBuilder: _itemBuilder,
          itemCount: 100,
          controller: _scrollController,
        ),
      ),
    );
  }

Introducing Note to Self Mail: The New Key to Productivity

According to the Harvard Business Review, your to-do list is too long. We’ve all experienced the feeling of being overwhelmed with what we need to accomplish. While this may initially seem as though it may help our productivity, too many things to do actually harms our productivity. It causes a never-ending cycle of not feeling accomplished, a lack of focus, and ultimately, procrastination. But, what can we do to avoid these issues? Enter Note to Self Mail.

Note to Self Mail makes it easy to keep your focus on a single task while reducing the time it takes to write out your notes. This improves your productivity both in the sense of keeping your focus on a single task and reducing time spent composing that note. So, let’s take a deeper dive into how Note to Self Mail can improve your productivity.

Compose Notes in Record Times

With the Note to Self Mail app, you can compose notes and send them to your email in just five seconds. Classic mail applications take roughly 25 seconds to compose a single note. This results in a time savings of about 80%.

On top of saving time composing your notes, Note to Self Mail also allows you to send that note to multiple addresses, record audio messages, and attach photos, sketches, or files to your note. These features help you compose comprehensive notes in record times. So with Note to Self Mail, you’re never left scouring for that one piece of information you forgot to include in your notes that you need to accomplish your task. It even archives your notes for easy access to past information you may need at a later date.

Connects with the Top Productivity Apps

Through connecting with the top productivity apps such as Wunderlist, Trello, Evernote, Asana, and OmniFocus, you can create notes and to-do lists in these apps directly through Note to Self Mail. So, instead of having scattered notes across multiple apps and your email, you can maintain one central location for all of your notes and to-do list needs. You can also use this connection to tie notes to different projects you incorporate into these productivity apps for even more efficiencies.

Aside from offering the fastest method for composing notes, Note to Self Mail helps you stay more organized in your favorite productivity apps. If you’re looking to step up your productivity, Note to Self Mail is here to help!