Node JS – Troubleshooting
Error Message
ERR_OSSL_EVP_UNSUPPORTED
Solution
$ENV:NODE_OPTIONS="--openssl-legacy-provider"
Tipps und Tricks für Entwickler und IT-Interessierte
ERR_OSSL_EVP_UNSUPPORTED
$ENV:NODE_OPTIONS="--openssl-legacy-provider"
When starting storybook with npm run storybook
, you always get the error EBUSY: resource busy or locked
You can fix this by adding the following to the file .storybook/main.js
module.exports = { ... managerWebpack: (config, options) => { options.cache.set = () => Promise.resolve(); return config; } }
npm i -g powerbi-visuals-tools@latest
sumOfValues = Object.keys(node.values).map(key => +node.values[key].value).reduce((prev, curr) => prev + curr) sumOfHighlights = Object.keys(node.values).map(key => node.values[key].highlight ? +node.values[key].highlight : null).reduce((prev, curr) => curr ? prev + curr : null)
matrix.rows.levels.map( l => l.sources[0].displayName).join('/')
Im Repository TableSorter
private calculateAverage(): number { if (this.dataPoints.length === 0) { return 0; } let total = 0; this.dataPoints.forEach((value: ICustomDataPoint) => { total += <number>value.value; }); return total / this.dataPoints.length; }
"alignment": { "type": { "formatting": { "alignment": true } }, "displayName": "Horizontal Alignment" },
import DataViewObjectsParser = powerbi.DataViewObjectsParser;
import { dataViewObjectsParser } from "powerbi-visuals-utils-dataviewutils"; import DataViewObjectsParser = dataViewObjectsParser.DataViewObjectsParser;
import { textMeasurementService as tms } from "powerbi-visuals-utils-formattingutils"; import TextProperties = tms.TextProperties;
import { interfaces } from "powerbi-visuals-utils-formattingutils"; import TextProperties = interfaces.TextProperties;
import { textMeasurementService as tms } from "powerbi-visuals-utils-formattingutils"; import textMeasurementService = tms.textMeasurementService;
import { textMeasurementService } from "powerbi-visuals-utils-formattingutils";
import { valueFormatter as vf } from "powerbi-visuals-utils-formattingutils"; import IValueFormatter = vf.IValueFormatter;
wslconfig.exe /u docker-desktop
flutter create <app> cd <app> flutter run
flutter flutter run --release .\lib\go_router.dart
Press F1
, find Preferences: Open Settings (UI) then search for devtoolsbrowser
.
Change in DevTools Menu
Suppose you have a list of modules located in the folder models and you want to import all of them.
To do this
index.dart
which exports all filesindex.dart
export 'counter.dart'; export 'number.dart';
import 'data/models/index.dart';
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}) {}
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'), );
import 'package:css_colors/css_colors.dart';
new Container(color: CSSColors.orange)
MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( title: const Text('Home'), ), ), );
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(); } }
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.
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 are a language-neutral, platform-neutral extensible mechanism for serializing structured data.
Learn more in this Dart Tutorial
A Very Good Command Line Interface for Dart created by Very Good Ventures
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.
❯ 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.
❯ 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
❯ cd app_server
❯ dart run bin/server.dart
❯ 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
❯ 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] ---------------------------------------------------------------------
❯ 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
❯ cd app_console
❯ dart run Building package executable... Built app_console:app_console. Hello world: 42!
❯ 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:
❯ dart compile exe .\bin\main.dart -o starter.exe ❯ .\bin\starter.exe
executables: github_activity: gh_activity
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); }
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()); }
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); }
class CircleMock implements Circle { num area = 0; num radius = 0; }
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); }
The following is copied from the Dart Website.
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!'); }
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.
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 continue
, switch
and case
, and assert
.
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.
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.
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.
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 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.
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 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.
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.
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, Future
, Stream
, and the asynchronous loop (await for
).
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
.
Many more code samples are in the language tour and the library tour. Also see the Dart API reference, which often contains examples.
Articles
Resources
Websites
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.