Terminal styling done right - now for Dart!

Related tags

Templates chalkdart
Overview

vscode debug console

windows terminal

Console/Terminal text coloring and styling library for Dart

'Terminal string styling done right'

I created this for my Dart/Flutter development logging almost 2 years ago now, and I have finally taken the time to clean it up and get it released as a package. In the mean time I added full ANSI support to the Visual Studio Code debugging console as well as just finishing full ANSI support for the Dart-Pad console as well. You can use this within your VSCode debugger to enable colorful, styled logging today. 😊

Check out example/chalkdart_example.dart for some cool examples of what it is capable of.

If you have used the Chalk.js package within the npm/node.js environment you know how nice and easy it makes text coloring and styling! This ChalkDart version can be used essentially exactly as the js version.

Full Api Dart Docs can be found here

ChalkDart API Documentation

Features and bugs

Please file feature requests and bugs at the issue tracker.

Highlights

  • Expressive API
  • Highly performant
  • Ability to nest styles
  • Supports dynamic argument list and automatically handles printing Maps, Lists, Iterables and Function closures
  • 256/Truecolor color support
  • All standard X11/CSS/SVG colors can be accessed for by name.
  • Ignores Auto-detected ANSI color support/as common Dart/Flutter IDE's report this incorrectly.
  • Not an extentension of the String class.
  • Clean and focused
  • Actively maintained

Install

$ dart pub add chalkdart

Usage

import 'package:chalkdart/chalk.dart';

print(chalk.yellow.onBlue('Hello world!'));

Chalk comes with an easy to use composable API where you just chain and nest the styles you want.

import 'package:chalkdart/chalk.dart';

// Combine styled and normal strings
print(chalk.blue('Hello') + ' World' + chalk.red('!'));

// Compose multiple styles using the chainable API
print(chalk.blue.onRed.bold('Hello world!'));

// Pass in multiple arguments
print(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));

// Nest styles
print(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));

// Nest styles of the same type even (color, underline, background)
print(chalk.green(
     'I am a green line ' +
     chalk.blue.underline.bold('with a blue substring') +
     ' that becomes green again!'
));

// use in multiline string with interpolation
print('''
      CPU: ${chalk.red('90%')}
      RAM: ${chalk.green('40%')}
      DISK: ${chalk.yellow('70%')}
   ''');

// or with inline calcs
print('''
CPU: ${chalk.red(cpu.totalPercent)}%
RAM: ${chalk.green((ram.used / ram.total * 100))}%
DISK: ${chalk.rgb(255,131,0)((disk.used / disk.total * 100))}%
''');

// Use RGB colors in debug console or terminals that support it.
print(chalk.keyword('orange')('Yay for orange colored text!'));
print(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
print(chalk.hex('#DEADED').bold('Bold gray!'));

Easily define your own themes:

import 'package:chalkdart/chalk.dart';

const error = chalk.bold.red;
const warning = chalk.keyword('orange');

print(error('Error!'));
print(warning('Warning!'));
const name = 'Tim Maffett';
print(chalk.green('Hello $name'));

//=> 'Hello Tim Maffett'

API

chalk.<style>[.<style>...](string, [string...])

Example: chalk.red.bold.underline('Hello', 'world');

Chain styles and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that chalk.red.yellow.green is equivalent to chalk.green.

String interpolation can be ised or multiple arguments can be listed and will be separated by space (or the string specified by joinWith). The arguments can be of any type, Map<>, List<>, Iterable and Functions/Function closures are also supported. By default Lists are joined together with a ' '(space), but the joinWith method can be used to specify a different join string. Up to 15 arguments can be included as arguments to a Chalk object.

Styles

Modifiers

  • reset - Resets the current color chain.
  • blink - Make text blink.
  • rapidblink - Make text blink rapidly.
  • bold - Make text bold.
  • dim - Emitting only a small amount of light.
  • italic - Make text italic.
  • underline - Make text underline.
  • doubleunderline - Thicker text underline.
  • overline - Make text overline.
  • inverse (or invert)- Inverse background and foreground colors.
  • hidden - Prints the text, but makes it invisible.
  • superscript - Make text superscript.
  • subscript - Make text subscript.
  • strikethrough - Puts a horizontal line through the center of the text.
  • visible- Prints the text only when Chalk has a color level > 0. Can be useful for things that are purely cosmetic.
  • font1-font10 - Changes the font

Some of these ANSI styles are not widely supported within all terminal emulators, but I have added COMPLETE support to the standard Visual Studio Code debug console as well as to the Dart-Pad console. Android Studio also has fairly complete support within it's debug console. See the VSCode section for info on using CSS to map fonts to the font1 through font10.

Colors

The exact RGB values for the base ANSI colors are rendered console/terminal dependent - and can be configured on some terminals such Windows Terminal - more info here

I include original JS Chalk 'xxxxBright' method names for users that may want legacy compatability with original JS Chalk).

  • black
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white
  • brightBlack      (alias blackBright, gray, grey)
  • brightRed          (alias redBright)
  • brightGreen      (alias greenBright)
  • brightYellow     (alias yellowBright)
  • brightBlue          (alias blueBright)
  • brightMagenta    (alias magentaBright)
  • brightCyan          (alias cyanBright)
  • brightWhite        (alias whiteBright)

Background colors

They are named by prefixing the color with 'on'. Chalk'Dart favors the 'onXXXXX' style of specifying background colors because the verb 'on' makes chained methods read better as a sentence (it's the Dart way). I include original Chalk 'bgXXXX' method names for users that may prefer that scheme (essentially for legacy compatability with original JS Chalk).

For example 'onBlue' and 'bgBlue' are the same, it is a matter of users preference on how they want their code to read.

  • onBlack      (alias bgBlack)
  • onRed          (alias bgRed)
  • onGreen      (alias bgGreen)
  • onYellow     (alias bgYellow)
  • onBlue         (alias bgBlue)
  • onMagenta   (alias bgMagenta)
  • onCyan         (alias bgCyan)
  • onWhite       (alias bgWhite)
  • onBrightBlack / onGray / onGrey      (alias: bgBlackBright, bgGray, bgGrey)
  • onBrightRed            (alias bgRedBright)
  • onBrightGreen        (alias bgGreenBright)
  • onBrightYellow      (alias bgYellowBright)
  • onBrightBlue          (alias bgBlueBright)
  • onBrightMagenta    (alias bgMagentaBright)
  • onBrightCyan          (alias bgCyanBright)
  • onBrightWhite        (alias bgWhiteBright)

256 and Truecolor color support

Chalk supports 256 colors and Truecolor (16 million colors) on supported terminal apps.

Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying {level: n} as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).

Examples:

  • chalk.hex('#DEADED').underline('Hello, world!')
  • chalk.keyword('orange')('Some orange text')
  • chalk.rgb(15, 100, 204).inverse('Hello!')

Background versions of these models are prefixed with bg and the first level of the module capitalized (e.g. keyword for foreground colors and bgKeyword for background colors).

  • chalk.onHex('#DEADED').underline('Hello, world!')
  • chalk.onKeyword('orange')('Some orange text')
  • chalk.onRgb(15, 100, 204).inverse('Hello!')

The following color models can be used:

  • rgb - Example: chalk.rgb(255, 136, 0).bold('Orange!')

  • hex - Example: chalk.hex('#FF8800').bold('Orange!')

  • hsl - Example: chalk.hsl(32, 100, 50).bold('Orange!')

  • hsv - Example: chalk.hsv(32, 100, 100).bold('Orange!')

  • hwb - Example: chalk.hwb(32, 0, 50).bold('Orange!')

  • xyz - Example: chalk.xyz(0.9, 0.9, 0.1).bold('Yellow!')

  • lab - Example: chalk.lab(85, 0, 108).bold('yellow-Orange!')

  • ansi - Example: chalk.ansi(31).bgAnsi(93)('red on yellowBright')

  • ansi256 - Example: chalk.onAnsi256(194)('Honeydew, more or less')

  • keyword (X11/CSS/SVG color keywords) - Example: chalk.cornFlowerBlue.onBeige or chalk.keyword('orange').bold('Orange!') The keyword table can be extended via and the new keywords can be accessed via

Chalk.addColorKeywordHex('myfavorite', 0x6495ED ); // using hex int
chalk.color.myfavorite('This is my favorite color');
Chalk.addColorKeywordHex('my2ndFavorite', '#6A5ACD' );  // or using string
chalk.color.my2ndfavorite('This is my 2nd favorite color');

or

chalk.keyword('myfavorite)('Using the keyword() method');
chalk.color.my2ndfavorite('This is my 2nd favorite color');

or import the X11 extension methods to get proper methods for each of the X11/CSS/SVG color names. With that you get code completion for available colors as well as compile time checking of color names.

import 'package:chalkdart/chalk.dart';
import 'package:chalkdart/chalk_x11.dart'; // get methods for x11/css/svg color name keywords

chalk.cornflowerBlue.onLimeGreen('Hey there!);

// without extension methods you can use the dynamic keyword lookup method:
chalk.color.cornflowerBlue.onLimeGreen('Hi Again!);
// or off x11
chalk.x11.cornflowerBlue.onLimeGreen('Hi Again!);
// or off csscolor
chalk.csscolor.cornflowerBlue.onLimeGreen('Hi Again!);

chalk.level

Specifies the level of color support.

Color support is automatically detected, but you can override it by setting the level property. You should however only do this in your own code as it applies globally to all Chalk consumers. Note dart determines VSCode debug console and Android Studio debug console do not support ansi control sequences, when in fact they do, so by default the level is set to 3 (full color/sequence support) as the default, no matter what the console/terminal reports. You must set this yourslef if you want a different value.

If you need to change this in a reusable module, create a new instance:

var chalkWithLevel0 = chalk.instance(level: 0);
// this version is provided for users of the JS version of Chalk
var chalkWithLevel0 = chalk.Instance(level: 0);
Level Description
0 All colors disabled
1 Basic color support (16 colors)
2 256 color support
3 Truecolor support (16 million colors)

IDE Support

The terminals and debug consoles in current versions of both Android Studio, IntelliJ and Visual Studio Code support 24bit/16M color ansi codes and most attributes. However, they both report that they DO NOT support ANSI codes. For this reason Chalk'Dart defaults to supporting full level 3 (24 bit) ANSI codes.

VSCode

It is possible to set the fonts that VSCode uses in the debug console. More information can be found here.

Browser support

Chrome, Firefox and Edge natively support ANSI escape codes in their respective developer consoles. From dart web code you can use window.console.log(...) to log messages to the browser's debug console.

Windows

If you're on Windows, do yourself a favor and use Windows Terminal instead of cmd.exe.

Related

  • chalk-js - The original Chalk library module for javascript which was the inspiration for this (as well as being the basis for this readme as well)!

Author/Maintainer

Other examples

Charts from chalkdart_example.dart output to windows terminal

You might also like...

Freela is a Flutter project that aims to connect people who want to work with jobs to be done.

Freela Freela is a Flutter project being developed at the university that aims to connect people who want to work with jobs to be done. Para Desenvolv

Nov 1, 2022

Simple flutter app that shows the transfer of money between multiple customers. The project is done as a part of The Sparks Foundation Internship GRIPSEPTEMPER22

Simple flutter app that shows the transfer of money between multiple customers. The project is done as a part of The Sparks Foundation Internship GRIPSEPTEMPER22

Sparks Bank 📝 Table of Contents About Packages used ScreenShots from the app Demo vedio Contributors About Basic banking system created in Flutter ba

Oct 14, 2022

Super Useful Flutter Layouts - Right in Your Pocket. 😉

Super Useful Flutter Layouts - Right in Your Pocket. 😉

Super Useful Flutter Layouts - Right in Your Pocket. 😉 Update: Flutter web app preview here: https://flutter-layouts-demo.web.app/ YouTube video walk

Jan 8, 2023

Custom bottom bar - A bottom tool bar that can be swiped left or right to expose more tools.

Custom bottom bar - A bottom tool bar that can be swiped left or right to expose more tools.

custom_bottom_bar A bottom tool bar that can be swiped left or right to expose more tools. usage Create your custom bottom bars with up to four custom

Jan 26, 2020

FLUTTER API: It's powerful navigation by gestures and taps. You can scroll from left to right or tap on the navigation icons.

FLUTTER API: It's powerful navigation by gestures and taps. You can scroll from left to right or tap on the navigation icons.

scroll_navigation My other APIs Video Viewer Video Editor Helpers Features Fancy animations. Customizable colors. Works with the back button. Scrollin

Jun 14, 2022

Flutter-context-menus - A flutter package to show context menus on right-click or long-press

context_menus A package to show context menus on right-click or long-press. 🔨 I

Jan 18, 2022

Do It Right - flutter app, simple android game to Increase Children’s Intention and Behavior About Littering

doitright "DoItRight": An Arabic Flutter Mobile App to Increase Children’s Inten

Jan 23, 2022

Sort it - Nothing is waste, but it becomes one when it is in the wrong place ,but who has the time to sort it and put it at its right place?

Sort it - Nothing is waste, but it becomes one when it is in the wrong place ,but who has the time to sort it and put it at its right place?

Sort It ✅ Nothing is waste, but it becomes one when it is in the wrong place , ?

Dec 6, 2022

This is a mason brick you can use to generate code that get's you started right up with a flutter project

flutter_brick This is a mason brick you can use to generate code that gets you started right up with a flutter project A flutter brick created with th

Sep 16, 2022
Owner
Tim Maffett
Coding, Compassion and Kindness
Tim Maffett
Creating terminal-based UIs and games in Dart should be accessible and fun!

griddle Griddle simplifies the concept of creating 2D games or UI applications within a 2D-matrix, or grid, which in turn makes it a suitable cross-pl

Matan Lurey 20 Dec 19, 2022
A simple set of terminal-based arcade games written in pure Dart.

dartcade A simple set of terminal-based arcade games written in pure Dart. Purpose I was developing some simple 2D UI libraries (such as package:gridd

Matan Lurey 7 Dec 7, 2022
Speed Share is a highly available file sharing terminal on LAN(local area network) developed by flutter framework.

速享 Language: 中文简体 | English 这是一款完全基于局域网的文件互传终端,速享不使用任何服务器,不使用您的移动流量,不收集任何用户数据,完全的点对点传输。 可以快速共享文本消息,图片或其他文件,文件夹。 适用于局域网中的文件互传,解决 QQ,微信等上传文件会经过服务器的问题,或者

null 477 Dec 31, 2022
Yet another Todo app, now using Flutter (with ScopedModel)

Flutter Todo Yet another Todo app, now using Flutter. Getting Started This Todo app is implemented using Flutter (with Scoped Model for state manageme

Tuan Nguyen 107 Jan 4, 2023
Flutter application for latest news by top newspapers . And allow for share articles with friends. Now available in night mode. Also landscape mode is available

Breaking News Latest news for almost 55 country. Feature of saving article and search ariticles. Used API https://newsapi.org/ Note: if data is not ge

null 7 Oct 24, 2022
Now UI Flutter is a fully coded app template built for Flutter which will allow you to create powerful and beautiful e-commerce mobile applications

Now UI Flutter is a fully coded app template built for Flutter which will allow you to create powerful and beautiful e-commerce mobile applications. We have redesigned all the usual components to make it look like our Now UI Design, minimalistic and easy to use.

null 12 Oct 9, 2022
Return a Stream that emits null and done event when didChangeDependencies is called for the first time.

did_change_dependencies Author: Petrus Nguyễn Thái Học Return a Stream that emits null and done event when State.didChangeDependencies is called for t

Petrus Nguyễn Thái Học 5 Nov 9, 2022
Flutter package to hide out whole application or sections if you are not paid for the job done.

not_paid Worried about your payment? Using this package you can provide a non paid version of your app to the client that consistently starts fading o

hd-motion 11 Nov 30, 2021