Developer Blog

Tipps und Tricks für Entwickler und IT-Interessierte

Flutter | Cookbook

Development Workflow

TL;DR

flutter create <app>
cd <app>
flutter run

Run App

flutter
flutter run --release .\lib\go_router.dart

VSCode and DevTools

Change default browser

Press F1, find Preferences: Open Settings (UI) then search for devtoolsbrowser.

Change in DevTools Menu

Working with Modules and Classes

Import all Modules from a Folder

Suppose you have a list of modules located in the folder models and you want to import all of them.

To do this

  • create a file index.dart which exports all files
  • in your dart file, import this index.dart
export 'counter.dart';
export 'number.dart';
import 'data/models/index.dart';

Create custom code for unsupported packages

Create main file to check, if package is available. If not, then switch to custom code

export 'unsupported.dart' if (dart.library.io) 'io.dart';

Use this file in your code

import 'plugins/desktop/desktop.dart';

Create files for supported and unsupported packages

io.dart

import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void setTargetPlatformForDesktop({TargetPlatform platform}) {
  TargetPlatform targetPlatform;
  if (platform != null) {
    targetPlatform = platform;
  }
  if (targetPlatform == null) {
    if (Platform.isMacOS) {
      targetPlatform = TargetPlatform.iOS;
    } else if (Platform.isLinux || Platform.isWindows) {
      targetPlatform = TargetPlatform.android;
    }
  }
  debugDefaultTargetPlatformOverride = targetPlatform;
}

unsupported.dart

import 'package:flutter/material.dart';

void setTargetPlatformForDesktop({TargetPlatform platform}) {}

Working with Themes

Using a Theme in MaterialApp()

return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData.light().copyWith(
        primaryColor: Colors.blue,
      ),
      darkTheme: ThemeData.dark(),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );

Working with CSS Colors

Import

import 'package:css_colors/css_colors.dart';

Usage

new Container(color: CSSColors.orange)

App Bar

How to remove a DEBUG Banner

MaterialApp(
  debugShowCheckedModeBanner: false,

  home: Scaffold(
    appBar: AppBar(
      title: const Text('Home'),
    ),
  ),  
);

Working With Data and Data Models

Replace Integer Variables with a Data Model

Examining the default Flutter App (Counter Sample), shows, that the real counter is implemented as integer with integer operations:

int _counter = 0;

void _incrementCounter() {
  setState(() {
    _counter++;
  });
}

If you want to customize the varianble and operations, you could replace the interger variable witrh your own data model

import 'data/models/counter.dart';

CounterModel _counter = CounterModel();

void _incrementCounter() {
  setState(() {
    _counter.add(1);
  });
}

The CounterModel is defined in data/models/counter.dart'

class CounterModel {
  int _value = 0;

  int get value => _value;

  void set(int val) => _value = val;
  void add(int val) => _value += val;
  void remove(int val) => _value -= val;

  void reset() => _value = 0;

  @override
  String toString() {
    return value.toString();
  }
}

Interesting Pack

device_preview

Dart | Cookbook

Additional Tools

Grinder

Dart workflows, automated.

Grinder consists of a library to define project tasks (e.g., test, build, doc) and a command-line tool to run them.

mono_repo

Manage multiple Dart packages within a single repository.

❯ dart pub global activate mono_repo
❯ mono_repo
Manage multiple packages in one source repository.

Usage: mono_repo <command> [arguments]

Global options:
-h, --help              Print this usage information.
    --version           Prints the version of mono_repo.
    --[no-]recursive    Whether to recursively walk sub-directories looking for packages.
                        (defaults to on)

Available commands:
  check       Check the state of the repository.
  generate    Generates the CI configuration for child packages.
  presubmit   Run the CI presubmits locally.
  pub         Runs the `pub` command with the provided arguments across all packages.

Run "mono_repo help <command>" for more information about a command.

Protocol Buffers

Protocol buffers are a language-neutral, platform-neutral extensible mechanism for serializing structured data.

Learn more in this Dart Tutorial

very_good_cli

A Very Good Command Line Interface for Dart created by Very Good Ventures 

Dart | Learning Dart

Introduction

Creating a simple class

class Bicycle {
  int cadence;
  int _speed = 0;
  int get speed => _speed;
  int gear;

  Bicycle(this.cadence, this.gear);

  void applyBrake(int decrement) {
    _speed -= decrement;
  }

  void speedUp(int increment) {
    _speed += increment;
  }

  @override
  String toString() => 'Bicycle: $_speed mph';
}

void main() {
  var bike = Bicycle(2, 1);
  print(bike);
}

Using optional parameters

import 'dart:math';

class Rectangle {
  int width = 0;
  int height = 0;
  Point origin = Point(0, 0);

  Rectangle({this.origin = const Point(0, 0), this.width = 0, this.height = 0});

  @override
  String toString() =>
      'Origin: (${origin.x}, ${origin.y}), width: $width, height: $height';
}

main() {
  print(Rectangle(origin: const Point(10, 20), width: 100, height: 200));
  print(Rectangle(origin: const Point(10, 10)));
  print(Rectangle(width: 200));
  print(Rectangle());
}

Create a factory

import 'dart:math';

abstract class Shape {
  // Option 2: Create a factory constructor

  factory Shape(String type) {
    if (type == 'circle') return Circle(2);
    if (type == 'square') return Square(2);
    throw 'Can\'t create $type.';
  }

  num get area;
}

class Circle implements Shape {
  final num radius;
  Circle(this.radius);

  @override
  num get area => pi * pow(radius, 2);
}

class Square implements Shape {
  final num side;
  Square(this.side);

  @override
  num get area => pow(side, 2);
}

// Option 1: Create a top-level function
Shape shapeFactory(String type) {
  if (type == 'circle') return Circle(2);
  if (type == 'square') return Square(2);
  throw 'Can\'t create $type.';
}

main() {
  // final circle = Circle(2);
  // final square = Square(2);

  // Option 1: Create a top-level function
  // final circle = shapeFactory('circle');
  // final square = shapeFactory('square');

  // Option 2: Create a factory constructor
  final circle = Shape('circle');
  final square = Shape('square');
  
  print(circle.area);
  print(square.area);
}

Implement an interface

class CircleMock implements Circle {
  num area = 0;
  num radius = 0;
}

Use Dart for functional programming

String scream(int length) => "A${'a' * length}h!";

main() {
  final values = [1, 2, 3, 5, 10, 50];
  for (var length in values) {
    print(scream(length));
  }
  
  // Functional
  values.map(scream).forEach(print);
}

Language samples

The following is copied from the Dart Website.

Hello World

Every app has a main() function. To display text on the console, you can use the top-level print() function:

void main() {
  print('Hello, World!');
}

Variables

Even in type-safe Dart code, most variables don’t need explicit types, thanks to type inference:

var name = 'Voyager I';
var year = 1977;
var antennaDiameter = 3.7;
var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];
var image = {
  'tags': ['saturn'],
  'url': '//path/to/saturn.jpg'
};

Read more about variables in Dart, including default values, the final and const keywords, and static types.

Control flow statements

Dart supports the usual control flow statements:

if (year >= 2001) {
  print('21st century');
} else if (year >= 1901) {
  print('20th century');
}

for (final object in flybyObjects) {
  print(object);
}

for (int month = 1; month <= 12; month++) {
  print(month);
}

while (year > 2016) {
  year += 1;
}

Read more about control flow statements in Dart, including break and continueswitch and case, and assert.

Functions

We recommend specifying the types of each function’s arguments and return value:

int fibonacci(int n) {
  if (n == 0 || n == 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}

var result = fibonacci(20);

A shorthand => (arrow) syntax is handy for functions that contain a single statement. This syntax is especially useful when passing anonymous functions as arguments:

flybyObjects.where((name) => name.contains('turn')).forEach(print);

Besides showing an anonymous function (the argument to where()), this code shows that you can use a function as an argument: the top-level print() function is an argument to forEach().

Read more about functions in Dart, including optional parameters, default parameter values, and lexical scope.

Comments

Dart comments usually start with //.

// This is a normal, one-line comment.

/// This is a documentation comment, used to document libraries,
/// classes, and their members. Tools like IDEs and dartdoc treat
/// doc comments specially.

/* Comments like these are also supported. */

Read more about comments in Dart, including how the documentation tooling works.

Imports

To access APIs defined in other libraries, use import.

// Importing core libraries
import 'dart:math';

// Importing libraries from external packages
import 'package:test/test.dart';

// Importing files
import 'path/to/my_other_file.dart';

Read more about libraries and visibility in Dart, including library prefixes, show and hide, and lazy loading through the deferred keyword.

Classes

Here’s an example of a class with three properties, two constructors, and a method. One of the properties can’t be set directly, so it’s defined using a getter method (instead of a variable).

class Spacecraft {
  String name;
  DateTime? launchDate;

  // Read-only non-final property
  int? get launchYear => launchDate?.year;

  // Constructor, with syntactic sugar for assignment to members.
  Spacecraft(this.name, this.launchDate) {
    // Initialization code goes here.
  }

  // Named constructor that forwards to the default one.
  Spacecraft.unlaunched(String name) : this(name, null);

  // Method.
  void describe() {
    print('Spacecraft: $name');
    // Type promotion doesn't work on getters.
    var launchDate = this.launchDate;
    if (launchDate != null) {
      int years = DateTime.now().difference(launchDate).inDays ~/ 365;
      print('Launched: $launchYear ($years years ago)');
    } else {
      print('Unlaunched');
    }
  }
}

You might use the Spacecraft class like this:

var voyager = Spacecraft('Voyager I', DateTime(1977, 9, 5));
voyager.describe();

var voyager3 = Spacecraft.unlaunched('Voyager III');
voyager3.describe();

Read more about classes in Dart, including initializer lists, optional new and const, redirecting constructors, factory constructors, getters, setters, and much more.

Enums

Enums are a way of enumerating a predefined set of values or instances in a way which ensures that there cannot be any other instances of that type.

Here is an example of a simple enum that defines a simple list of predefined planet types:

enum PlanetType { terrestrial, gas, ice }

Here is an example of an enhanced enum declaration of a class describing planets, with a defined set of constant instances, namely the planets of our own solar system.

/// Enum that enumerates the different planets in our solar system
/// and some of their properties.
enum Planet {
  mercury(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),
  venus(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),
  // ···
  uranus(planetType: PlanetType.ice, moons: 27, hasRings: true),
  neptune(planetType: PlanetType.ice, moons: 14, hasRings: true);

  /// A constant generating constructor
  const Planet(
      {required this.planetType, required this.moons, required this.hasRings});

  /// All instance variables are final
  final PlanetType planetType;
  final int moons;
  final bool hasRings;

  /// Enhanced enums support getters and other methods
  bool get isGiant =>
      planetType == PlanetType.gas || planetType == PlanetType.ice;
}

You might use the Planet enum like this:

final yourPlanet = Planet.earth;

if (!yourPlanet.isGiant) {
  print('Your planet is not a "giant planet".');
}

Read more about enums in Dart, including enhanced enum requirements, automatically introduced properties, accessing enumerated value names, switch statement support, and much more.

Inheritance

Dart has single inheritance.

class Orbiter extends Spacecraft {
  double altitude;

  Orbiter(super.name, DateTime super.launchDate, this.altitude);
}

Read more about extending classes, the optional @override annotation, and more.

Mixins

Mixins are a way of reusing code in multiple class hierarchies. The following is a mixin declaration:

mixin Piloted {
  int astronauts = 1;

  void describeCrew() {
    print('Number of astronauts: $astronauts');
  }
}

To add a mixin’s capabilities to a class, just extend the class with the mixin.

class PilotedCraft extends Spacecraft with Piloted {
  // ···
}

PilotedCraft now has the astronauts field as well as the describeCrew() method.

Read more about mixins.

Interfaces and abstract classes

Dart has no interface keyword. Instead, all classes implicitly define an interface. Therefore, you can implement any class.

class MockSpaceship implements Spacecraft {
  // ···
}

Read more about implicit interfaces.

You can create an abstract class to be extended (or implemented) by a concrete class. Abstract classes can contain abstract methods (with empty bodies).

abstract class Describable {
  void describe();

  void describeWithEmphasis() {
    print('=========');
    describe();
    print('=========');
  }
}

Any class extending Describable has the describeWithEmphasis() method, which calls the extender’s implementation of describe().

Read more about abstract classes and methods.

Async

Avoid callback hell and make your code much more readable by using async and await.

const oneSecond = Duration(seconds: 1);
// ···
Future<void> printWithDelay(String message) async {
  await Future.delayed(oneSecond);
  print(message);
}

The method above is equivalent to:

Future<void> printWithDelay(String message) {
  return Future.delayed(oneSecond).then((_) {
    print(message);
  });
}

As the next example shows, async and await help make asynchronous code easy to read.

Future<void> createDescriptions(Iterable<String> objects) async {
  for (final object in objects) {
    try {
      var file = File('$object.txt');
      if (await file.exists()) {
        var modified = await file.lastModified();
        print(
            'File for $object already exists. It was modified on $modified.');
        continue;
      }
      await file.create();
      await file.writeAsString('Start describing $object in this file.');
    } on IOException catch (e) {
      print('Cannot create description for $object: $e');
    }
  }
}

You can also use async*, which gives you a nice, readable way to build streams.

Stream<String> report(Spacecraft craft, Iterable<String> objects) async* {
  for (final object in objects) {
    await Future.delayed(oneSecond);
    yield '${craft.name} flies by $object';
  }
}

Read more about asynchrony support, including async functions, FutureStream, and the asynchronous loop (await for).

Exceptions

To raise an exception, use throw:

if (astronauts == 0) {
  throw StateError('No astronauts.');
}

To catch an exception, use a try statement with on or catch (or both):

try {
  for (final object in flybyObjects) {
    var description = await File('$object.txt').readAsString();
    print(description);
  }
} on IOException catch (e) {
  print('Could not describe object: $e');
} finally {
  flybyObjects.clear();
}

Note that the code above is asynchronous; try works for both synchronous code and code in an async function.

Read more about exceptions, including stack traces, rethrow, and the difference between Error and Exception.

Other topics

Many more code samples are in the language tour and the library tour. Also see the Dart API reference, which often contains examples.

Learn more

Articles

Resources

Websites

Flutter | Working with the Flutter Command Line

Introduction

Flutter Command Line

To show all commands, just run flutter

❯ flutter
Manage your Flutter app development.

Common commands:
  flutter create <output directory>
    Create a new Flutter project in the specified directory.

  flutter run [options]
    Run your Flutter application on an attached device or in an emulator.

Usage: flutter <command> [arguments]

Global options:
-h, --help                  Print this usage information.
-v, --verbose               Noisy logging, including all shell commands executed.
                            If used with "--help", shows hidden options. If used with "flutter doctor", shows additional diagnostic information. (Use "-vv" to force verbose logging in those cases.)
-d, --device-id             Target device id or name (prefixes allowed).
    --version               Reports the version of this tool.
    --suppress-analytics    Suppress analytics reporting when this command runs.

Available commands:

Flutter SDK
  bash-completion   Output command line shell completion setup scripts.
  channel           List or switch Flutter channels.
  config            Configure Flutter settings.
  doctor            Show information about the installed tooling.
  downgrade         Downgrade Flutter to the last active version for the current channel.
  precache          Populate the Flutter tool's cache of binary artifacts.
  upgrade           Upgrade your copy of Flutter.

Project
  analyze           Analyze the project's Dart code.
  assemble          Assemble and build Flutter resources.
  build             Build an executable app or install bundle.
  clean             Delete the build/ and .dart_tool/ directories.
  create            Create a new Flutter project.
  drive             Run integration tests for the project on an attached device or emulator.
  format            Format one or more Dart files.
  gen-l10n          Generate localizations for the current project.
  pub               Commands for managing Flutter packages.
  run               Run your Flutter app on an attached device.
  test              Run Flutter unit tests for the current project.

Tools & Devices
  attach            Attach to a running app.
  custom-devices    List, reset, add and delete custom devices.
  devices           List all connected devices.
  emulators         List, launch and create emulators.
  install           Install a Flutter app on an attached device.
  logs              Show log output for running Flutter apps.
  screenshot        Take a screenshot from a connected device.
  symbolize         Symbolize a stack trace from an AOT-compiled Flutter app.

Run "flutter help <command>" for more information about a command.
Run "flutter help -v" for verbose help output, including less commonly used options.

Flutter | Troubleshooting

Basic

flutter doctor

Error: Exception: Bad UTF-8 encoding
Solution: Use the current version of vswhere

Download from: https://github.com/microsoft/vswhere/releases

Store/overwrite: C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe

PS> Set-Location "C:\Program Files (x86)\Microsoft Visual Studio\Installer"                                                                                                                                              
PS> Move-Item vswhere.exe vswhere.exe.original
PS> Invoke-WebRequest https://github.com/microsoft/vswhere/releases/download/3.0.3/vswhere.exe -O vswhere.exe
Null safety features are disabled for this library.
lib/main.dart:8:19: Error: Null safety features are disabled for this library.
Try removing the package language version or setting the language version to 2.12 or higher.
  const MyApp({Key? key}) : super(key: key);
Solution: Edit pubspec.yaml
environment:
  sdk: '>=2.17.3 <3.0.0'

Migration Dart Plugins

import 'package:flutter/services.dart';
client =createHttpClient();

 

import 'package:http/http.dart' as http;
client = new http.Client();

Your app is not using AndroidX

GoTo Flutter_Project -> android -> gradle.properties file. Open the gradle.properties file in any Text editor.

Add below lines in this file and Save the file.

android.useAndroidX=true
android.enableJetifier=true

Open your Flutter Project Root directory in Command Prompt or Terminal and execute

flutter clean

Flutter | Getting started

Installation

Installation of Flutter

Details are here

Installation of Dart SDK

Details are here

$ brew tap dart-lang/dart
$ brew install dart --devel

Create your first App

Copied from here and here

Create the starter Flutter app

$ flutter create starter
$ cd starter

Run Flutter App on the Web

$ flutter config --enable-web
$ flutter config --enable-web
$ flutter build web

Run Flutter App on Android Emulator

$ flutter devices
$ flutter run [--verbose]
$ flutter emulators
5 available emulators:

Android_Accelerated_Oreo
Nexus_5X_API_28_x86      • Nexus 5X      • Google • Nexus 5X API 28 x86
Pixel_3_API_28           • pixel_3       • Google • Pixel 3 API 28
Pixel_XL_API_28          • pixel_xl      • Google • Pixel XL API 28
apple_ios_simulator      • iOS Simulator • Apple

To run an emulator, run 'flutter emulators --launch <emulator id>'.
To create a new emulator, run 'flutter emulators --create [--name xyz]'.
$ flutter emulators --launch apple_ios_simulator

Read More

Official websitehttps://flutter.io/ will supply from step by step to install and start with the simple example.

Dart language

Flutter training online

Google CodeLab: https://codelabs.developers.google.com/?cat=Flutter

Flutter Samples: https://github.com/flutter/samples

Flutter Cookbook: https://flutter.dev/docs/cookbook

Github Awesome-Flutter

Flutter challenge series has been building by Matt Carroll who is owners of Fluttery (Youtube channel https://www.youtube.com/fluttery)

Blogs 

App builder: It is an amazing tool to build the Flutter UI online that mean you only need choose your UI widget and drag to screen -> You can get the source code for your app.

The Flutter Pub is a medium publication to bring you the latest and amazing resources such as articles, videos, codes, podcasts, etc. about this great

What’s next

  • Learn Dart
    Go to Dart guides and see a preview of the four most visited websites. Initially, these two are worth focusing on: Language tour and Language samples. A complete and detailed Dart course supported by examples can also be found here.
  • Install Flutter SDK – Prepare IDE
    The entire process is described step by step depending on the system on which we want to install Flutter.
  • Study Material Design Concept
    If we want to create user-friendly interfaces, it is important to read material design rules. 
  • Widgets
    Widgets are an indispensable part of Flutter. You can browse them alphabetically.
  • API Calls and Database Integration
    The Pub provides great packages such as: http or dio to perform HTTP requests. Hive is a lightweight and blazing fast key-value database written in pure Dart. You should also consider integrating with Firebase.

Links