Category: Dart

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)

Flutter: expand TextField height to match parent widget

To expand the height of TextField to match the parents widgets height, the following code can be used:

Container(
  height: 500.0,
  child: TextField(
    expands: true,
    minLines: null,
    maxLines: null,
    ...
  ),
),

The important thing is, that both minLines and maxLines need to be set to null.

To set the height of the Container to match it’s parent or even the complete screen, height can be set to double.infinity.

Flutter on iOS: themeMode does not change to dark mode if `ThemeMode.system` is used

In my case, a simple app should automatically use the theme (light or dark) of the system to style the user interface. By default, this should work when using ThemeMode.system (see flutter documentation). But it didn’t.

The themes have been defined as follows:

    return MaterialApp(
      themeMode: ThemeMode.system,
      theme: ThemeData( ... ),
      darkTheme: ThemeData( ...),
      ...
    );

In addition, the WidgetsBindingObserver callback didChangePlatformBrightness() was never called. It was defined as follows:

class MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver
{
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangePlatformBrightness() {
    print(WidgetsBinding.instance.window.platformBrightness);
    // > should print Brightness.light / Brightness.dark when you switch
    super.didChangePlatformBrightness();
  }
}

After hours and days of searching, it turned out, that the following definition was set in info.plist of iOS:

<key>UIUserInterfaceStyle</key>
<string>Light</string>

Removing this line solved the issue. This setting sets the apps theme to Light, which results in a constant value even if the user changed the brightness to dark. Without this line, UIUserInterfaceStyle depends on the global setting.

Source: https://stackoverflow.com/questions/61620332/platform-brightness-is-still-light-on-ios-even-when-dark-mode-is-on-flutter

fatal error: ‘Flutter/Flutter.h’ file not found

After switching the flutter channel to beta and back to stable, my app did not compile anymore. The compilation stopped with the error:

fatal error: 'Flutter/Flutter.h' file not found

Multiple flutter clean and channel switches did not work in this case.

The following commands fixed this behavior:

rm ios/Flutter/Flutter.podspec
flutter clean

See: https://github.com/flutter/flutter/issues/70895#issuecomment-744734693

Flutter: generating *.g.dart files for json serialization

The full documentation for this is available on flutter.dev

When creating json_serializable classes the first time, you‚Äôll get errors similar to what is shown in the image below.

IDE warning when the generated code for a model class does not exist yet.

These errors are entirely normal and are simply because the generated code for the model class does not exist yet. To resolve this, run the code generator that generates the serialization boilerplate.

There are two ways of running the code generator.

One-time code generation

By running 

flutter pub run build_runner build

in the project root, you generate JSON serialization code for your models whenever they are needed. This triggers a one-time build that goes through the source files, picks the relevant ones, and generates the necessary serialization code for them.

While this is convenient, it would be nice if you did not have to run the build manually every time you make changes in your model classes.

Generating code continuously

A watcher makes our source code generation process more convenient. It watches changes in our project files and automatically builds the necessary files when needed. Start the watcher by running

flutter pub run build_runner watch

in the project root.

It is safe to start the watcher once and leave it running in the background.

Source: https://flutter.dev/docs/development/data-and-backend/json#code-generation