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 | Working with the DartCommand Line

Introduction

Dart Command Line

To show all commands, just run dart

❯ dart
A command-line utility for Dart development.

Usage: dart <command|dart-file> [arguments]

Global options:
-h, --help                 Print this usage information.
-v, --verbose              Show additional command output.
    --version              Print the Dart SDK version.
    --enable-analytics     Enable analytics.
    --disable-analytics    Disable analytics.

Available commands:
  analyze    Analyze Dart code in a directory.
  compile    Compile Dart to various formats.
  create     Create a new Dart project.
  devtools   Open DevTools (optionally connecting to an existing application).
  doc        Generate API documentation for Dart projects.
  fix        Apply automated fixes to Dart source code.
  format     Idiomatically format Dart source code.
  migrate    Perform null safety migration on a project.
  pub        Work with packages.
  run        Run a Dart program.
  test       Run tests for a project.

Create a Dart project

❯ dart create
Create a new Dart project.

Usage: dart create [arguments] <directory>
-h, --help                       Print this usage information.
-t, --template                   The project template to use.

          [console] (default)    A command-line application.
          [package]              A package containing shared Dart libraries.
          [server-shelf]         A server app using package:shelf.
          [web]                  A web app that uses only core Dart libraries.

    --[no-]pub                   Whether to run 'pub get' after the project has been created.
                                 (defaults to on)
    --force                      Force project generation, even if the target directory already exists.

Create a Server App

Create the Project

❯ dart create app_server -t server-shelf
Creating app_server using template server-shelf...

  .gitignore
  analysis_options.yaml
  CHANGELOG.md
  pubspec.yaml
  README.md
  Dockerfile
  .dockerignore
  test\server_test.dart
  bin\server.dart

Running pub get...
  Resolving dependencies...
  Downloading lints 2.0.0...
  Downloading shelf_router 1.1.3...
  Downloading http_methods 1.1.0...
  Downloading test 1.21.2...
  Downloading test_core 0.4.14...
  Downloading test_api 0.4.10...
  Downloading glob 2.1.0...
  Downloading frontend_server_client 2.1.3...
  Downloading analyzer 4.1.0...
  Downloading _fe_analyzer_shared 40.0.0...
  Downloading coverage 1.3.2...
  Changed 49 dependencies!

Created project app_server in app_server! In order to get started, run the following commands:

  cd app_server
  dart run bin/server.dart

Run the App

❯ cd app_server
❯ dart run bin/server.dart

Create a Web App

Create the Project

❯ dart create app_web -t web
Creating app_web using template web...

  .gitignore
  analysis_options.yaml
  CHANGELOG.md
  pubspec.yaml
  README.md
  web\index.html
  web\main.dart
  web\styles.css

Running pub get...
  Resolving dependencies...
  Downloading build_web_compilers 3.2.3...
  Downloading protobuf 2.1.0...
  Downloading build_modules 4.0.5...
  Downloading build_runner 2.1.11...
  Downloading matcher 0.12.12...
  Downloading build 2.3.0...
  Downloading dart_style 2.2.3...
  Downloading build_resolvers 2.0.9...
  Changed 58 dependencies!

Created project app_web in app_web! In order to get started, run the following commands:

  cd app_web
  dart pub global activate webdev
  webdev serve

Run the App

❯ cd app_web
❯ dart pub global activate webdev
Package webdev is currently active at version 2.7.9.
Resolving dependencies...
The package webdev is already activated at newest available version.
To recompile executables, first run `dart pub global deactivate webdev`.
Installed executable webdev.
Activated webdev 2.7.9.
❯ webdev serve

Serve with different Port as the default port 8080

❯ webdev serve web:10000
[INFO] Building new asset graph completed, took 11.2s
[INFO] Checking for unexpected pre-existing outputs. completed, took 13ms
[INFO] Serving `web` on http://127.0.0.1:10000
[WARNING] No actions completed for 51.9s, waiting on:
  - build_web_compilers:entrypoint on web/main.dart

[INFO] Generating SDK summary completed, took 49.3s
[WARNING] No actions completed for 15.0s, waiting on:
  - build_web_compilers:sdk_js on asset:build_web_compilers/$package$
  - build_web_compilers:entrypoint on web/main.dart

[WARNING] No actions completed for 15.0s, waiting on:
  - build_web_compilers:sdk_js on asset:build_web_compilers/$package$
  - build_web_compilers:entrypoint on web/main.dart

[INFO] Running build completed, took 1m 40s
[INFO] Caching finalized dependency graph completed, took 1.7s
[INFO] Succeeded after 1m 42s with 15 outputs (1363 actions)
[INFO] ---------------------------------------------------------------------

Create a Command-line App

Create the Project

❯ dart create app_console -t console
Creating app_console using template console...

  .gitignore
  analysis_options.yaml
  CHANGELOG.md
  pubspec.yaml
  README.md
  bin\app_console.dart
  lib\app_console.dart
  test\app_console_test.dart

Running pub get...
  Resolving dependencies...
  Changed 46 dependencies!

Created project app_console in app_console! In order to get started, run the following commands:

  cd app_console
  dart run

Run the App

❯ cd app_console
❯ dart run
Building package executable...
Built app_console:app_console.
Hello world: 42!

Build an executable for Windows

❯ dart compile exe .\bin\main.dart
Info: Compiling with sound null safety
Generated: ...\app_console\bin\main.exe
❯ dir bin

    Directory: D:\CLOUD\Programmier-Workshops\Kurse\Dart\Einsteiger\Overview\app_console\bin

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---          21.06.2022    10:28            329 main.dart
-a---          21.06.2022    10:33        5025280 main.exe

❯ .\bin\main.exe
Hello world: 42!

Use a different App Name as Executable:

  • Use option -o with dart compile
❯ dart compile exe .\bin\main.dart -o starter.exe
❯ .\bin\starter.exe
  • configure name in pubspec.yaml
executables:
  github_activity: gh_activity

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.

WSL | Cookbook

Configuration

wsl.conf

Sample wsl.conf

[boot]
systemd=true

[network]
hostname = playground
generateHosts = false

Basics

Run specify distribution

 wsl --distribution Ubuntu-22.04
 wsl -d Ubuntu-22.04

Run Distribution and login as root

wsl -d Debian -u root

Change root password

 wsl.exe --user root --distribution Alpine passwd

Running X Apps

https://nickjanetakis.com/blog/using-wsl-and-mobaxterm-to-create-a-linux-dev-environment-on-windows

export DISPLAY="$(/sbin/ip route | awk '/default/ { print $3 }'):0"

Boot Configuration

systemd

Set the systemd flag set in your WSL distro settings

You will need to edit the wsl.conf file to ensure systemd starts up on boot.

Add these lines to the /etc/wsl.conf (note you will need to run your editor with sudo privileges, e.g: sudo nano /etc/wsl.conf):

[boot]
systemd=true

And close out of the nano editor using CTRL+O to save and CTRL+X to exit.

Final Check

Close your WSL distro Windows and run wsl.exe --shutdown from PowerShell to restart your WSL instances. Upon launch you should have systemd running. You can check this with

systemctl list-unit-files --type=service

Change Hostname

Edit /etc/wsl.conf

[network]
hostname = wsl2
generateHosts = false

Change the hostname in /etc/hosts and /etc/hostname

# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateHosts = false
127.0.0.1      localhost
127.0.1.1      wsl2.localdomain        wsl2

Shutdown wsl

wsl --shutdown

Distributions

Create a new Distribution

Export a distribution

wsl --export Ubuntu-22.02 ubuntu.tar

Import with new name

wsl --import MyUbuntu D:\WSL\Distributions\MyUbuntu ubuntu.tar

Daily: Running Microsoft SQL-Server in Docker

Introduction

Using Docker is an effortless way to launch and run an application/server software without annoying installation hassles: Just run the image and you’re done.

Even if it’s quite an uncomplicated way of looking at it, in many cases it works just like that.

So, let’s start with using Microsoft SQL Server as a database backend. We will use a docker image from Microsoft. Look here to find out more.

docker	run                                       \
			--name mssql-server       \
			--memory 4294967296       \	
			-e "ACCEPT_EULA=Y"        \
			-e "SA_PASSWORD=secret"   \
			-p 1433:1433              \
			mcr.microsoft.com/mssql/server:2019-latestles

FAQ

Error: program requires a machine with at least 2000 megabytes of memory

Start the docker container as described on the Docker Hub Page: How to use this Image

❯ docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=secret" -p 1433:1433 mcr.microsoft.com/mssql/server:2022-latest

Depending on how your docker environment is configured, this could bring up an error:

SQL Server 2019 will run as non-root by default.
This container is running as user mssql.
To learn more visit https://go.microsoft.com/fwlink/?linkid=2099216.
sqlservr: This program requires a machine with at least 2000 megabytes of memory.
/opt/mssql/bin/sqlservr: This program requires a machine with at least 2000 megabytes of memory.

As the error message states, the MS SQL server needs at least 2g of RAM. So, you must assign your Docker VMs more memory. This is configured in the Docker Dashboard.

Hint: Docker has two ways of running containers:

  • using Windows Container
  • using WSL (Windows Subsystem for Linux)

You can change the way with the context menu of the docker symbol in the task bar:

With Linux Containers (using WSL as backend), you must configure the containers via a file .wslconfig.

This file is in the folder defined by the environment variable

To open the file, run the command:

From Command Promptnotepad

Edit the content and change the memory setting

[wsl2]
memory=3GB

Restart WSL with the new settings.

❯ wsl --shutdown

Start Container again, now everything should work

❯ docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=secret" -p 1433:1433 mcr.microsoft.com/mssql/server:2022-latest
Copyright © 2024 | Powered by WordPress | Aasta Blog theme by ThemeArile