DART Built-In Types And Functions

Photo by IvanH on Unsplash

DART Built-In Types And Functions

Built-in types are defined as types found in Dart’s SDK core folder. They are termed built-in because they come by default in every Dart project. There are various built-in Dart types. We will explore some of them, like the number, boolean, and string types.

Number Types (num, int, double)

Both int and double are subclasses or types of the num class, i.e., both int and double are also numbers and can access methods from the num class. The num type can hold int and double values, and the num class's operators and methods will work on both types.

num twenty = 20;
twenty = 20.0;

Although you cannot assign a double to a variable of type int, you can perform operations performed on these types on both types, i.e., you can add a double and int and still get a result since they are both numbers with the add operation defined in the num class.

num number = 20;
int bill = 2;
double d2 = 12.3;
var sum = number + bill + d2;
print(sum);

It's best to use the num type when you want to use the functions that can be applied to both int and double.

A variable of type num can switch between int and double values during the entire execution of your program.

num switchedVar = 3;
switchedVar = 3.0;
print(switchedVar);

Some Important Functions In The Num, Int & Double Class

Use the parse() method to turn a string into a num, int, or double.

String str = '5.0';
double name = double.parse(str);
print(name);

Convert a num, int or double to a string using the toString() method.

 int ints = 5;
 String name = ints.toString();
 print(name);

The clamp() method works on the num type and is called on a value to project between a lower and upper value. Clamp() is useful for multiple incoming values that need to be set between two specific numbers.

double d = 1.3;
int integer = 4;
num n = 2;

int clampedIntOutput = integer.clamp(0, 1);
double clampedDoubleOutput = d.clamp(0.0, 2.2);
num clampedNumOutput = n.clamp(0.0, 10);
print('$clampedIntOutput $clampedDoubleOutput, $clampedNumOutput');

The ceil() method is useful for double values and returns the nearest integer not smaller than the current value.

The method round() returns the nearest int without any restriction

The floor() method returns the nearest int not greater than the current value

int d = 23.4;

int ceiledValue = d.ceil();
int floorValue = d.floor();
int roundValue = d.round();
print('''Ceilof $d = $ceiledValue \nFloorof of $d = $floorValue \nRoundof $d = $roundValue \n''');

The default division operator / returns a double. To receive only the truncate of the result, use the truncation division operator ~/

int d = 10;
int e = 4;
num div = d / e; // d ~/ e; to return truncate value of 2
print(div);

Since the division operator returns a double, a value divided by 0 will return infinity.

Using the ~/ will return an exception because the int type doesn’t support infinity or null values.

String Type

Strings are one of the most commonly used types in Dart. Strings are lists of code units or characters at their core. You can use a single 'bye' or double "sam" quote to create a string object.

Double quotes help create a string containing a single quote that needs to be in the actual string value.

String b = "He's here";

You can interpolate identifiers and expressions within a string’s content. For single identifier interpolation, precede the identifier with a $. The $ calls the toString() method and concatenates the response within the string.

const text = "I like pizza";
const topping = "with tomatoes";
const favorite = "$text $topping";
print(favorite);

String Concatenation & Displaying Strings on Multi Lines

Two strings can be concatenated by using two string literals one after the other or by using the plus operator with the string identifier.

 String e = 'Hello';
 String f = 'User';
 String simpleConcatenation = "Hello" "User";
 String plusConcatenation = e + f;

To display a piece of string on different lines, use \n to create a multi-line string or use ''' quotes and Dart will consider all break lines between the string.

To display everything in a string, including the \n, prefix the string quotation with an r.

There are also other types called collection types, which consist of types like list, set, map and queue. I’ll cover these types in another blog.

Functions

A simple function in Dart is a body of code with an optional return value. A function can be called by its name at a call site. For example, the main() function of a project

(returntype)void printWow() { //body
  print('Wow');
// return    // optional
}

Dart's lint rules permit you to create a function without specifying a return type, but it's best practice for every function to have a return type, especially in big projects.

A function without a return type is set to dynamic by default and will return null. Hence, it's best to use void than not specify a type. Also, a function of type void returns nothing and cannot be called/used.

A void function can be invoked with its result assigned to a variable.

final void value = greet();

void greet() {
  print('Greetings');
}

Named Parameters

One of the types of parameters you can pass to a function is called named parameters and is enclosed in {}. A named parameter, i.e. {String name} needs to have a default value, or has to be optional ?, and the call site doesn't have to hold a value for the parameters.

sayHelloTo();
sayHelloTo(name: 'sike');
sayHelloTo(name: null);

void sayHelloTo({String? name}) {
  print('Hello $name');
}

You can assign default values to named parameters, whether optional or not. Values of non-nullable named parameters can't be set to null.

describe(); // call a func without passing a value
describe(something: null); // call a func and set value to null
describe(something: 'Hello dart'); // call a func set a value 

void describe({String? something = 'Hello World!'}) {
  print(something);
}
// default value = hello world!

describe(); 
describe(something: null); // compile-time error
describe(something: 'Hello dart');

void describe({String something = 'Hello World!'}) {
  print(something);
}

Required Named Parameters

Named parameters in Dart can also be required. A required parameter means a parameter value has to be set at the call site of the function. Also, a required named parameter can also be optional but cannot have default values.

// doSomethingWith(); // invalid code
// doSomethingWith(name: null); // can't set a required string to null // valid if string is a required ? optional
doSomethingWith(name: 'Bingo');

void doSomethingWith({required String name}) {
  print('Hello $name');
}
// Age can't have a default value since the value hase to be parsed at call site
void doSomethingWithAge({required int? age}) {
  if (age != null) {
    final in2Years = age + 2;
    print('In 2 years you will be $in2Years years old');
  } else {
    print('You did not tell me your age');
  }
}

Positional Parameters

Positional parameters are types parsed in order and do not have names associated with them at the call site, and their values are always required and cannot have default values.

// sayGoodByeTo(); // invalid required 2 values to be parsed
// sayGoodByeTo('binz') // invalid one more value needed

 // positional arguments do not have names at call site
 sayGoodByeTo('benz', 'heinz');

// can pass null only if params are nullable ?
sayGoodByeTo(null, null)

void sayGoodByeTo(String person, String andOtherPerson) {
  print('Goodbye $person and $andOtherPerson!');
}

There are more types of parameters, but let's leave it here for now.