Dive into Dart — Data Types & Variables
Dart for absolute beginners.
Table of Contents:
- Introduction.
- What are the Data Types & Variables?
- Basic Data Types in Dart.
- Break Down of each Data Type.
- Literals.
- String Interpolation & Concatenation.
- Method to Manipulate String Variables.
Introduction
Dart is a programming language used to develop Flutter applications. It’s an excellent option for building mobile apps on multiple platforms. I’ve previously written tutorial articles on Flutter widgets and plan to continue doing so. However, I also want to write about Dart programming, starting with the basics to help absolute beginners. This tutorial series will begin with Data Types and Variables, which are essential building blocks of any programming language. I’ll cover the fundamentals in a few articles before moving on to more advanced topics in Dart programming.
What are the Data Types and Variables in Dart?
Data types define the type of information a variable can hold. Consider variables as containers that store data; data types determine the data type they can keep. For example, a variable can have a number, a word, or even a collection of values.
type variableName = value;
// a variable has been explicitly declared with data type and initialised.
String name = "Bob";
// a variable has been explicitly declared with data type but not intialised.
String name;
// a variable has not been explicitly declared with data type nor initialised
var name;
// a variable has not been explicitly declared with data type but initialised
var name = "John Doe";
“String” and “var” are data types, and “name” is the variable and whatever comes after the equal sign is the value that is being stored in the variable. In the above case, “Bob” and “John Doe” are values being held in the variable called “name” with the data type String. Dart also has a feature known as Type Inference. This means if you use “var” and initialise the variable, Dart automatically recognises the value, understands it and assigns the data type to it accordingly.
void main(){
// here Dart understand that this is a String
var shopName = "amazon";
// here Dart understands that this is an integer
var age = 10;
}
The conventional way of declaring a variable name is to use lowerCaseCamel. It means you should capitalise each word’s first letter except the first word and use no separators. Also, you should name the variables as descriptively as possible.
Here are some of the basic data types in Dart:
- Numbers
- Doubles
- Strings
- Booleans
- Lists
- Maps
To further break down each data type in Dart.
Numbers:
- int: Stores whole numbers like 1, 10, or -100.
- double: Stores decimal numbers like 3.14, 5.0, or -2.5.
- num: Represents both integers and doubles.
Strings:
A sequence of characters enclosed in single (‘ ’) or double (“ ”) quotes.
Examples: “Hello world!”, ‘This is a string’, ‘123’
Booleans:
Represent truth values: true or false. Used for making decisions and controlling program flow.
Lists:
Ordered collections of values are enclosed in square brackets []. It can hold elements of the same or different data types.
Example: [‘apple’, ‘banana’, 1, 2.5]
Maps:
Unordered collections of key-value pairs enclosed in curly braces {}. Keys are unique identifiers (often strings), and values can be of any data type.
Example: {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}
Here ‘name’ is the key, and “John” is the value.
Literals:
Consider yourself a painter. You mix colours from basic primary colours to create your masterpiece. In programming, literals are the “primary colours” of data types. They represent fixed values directly within your code.
// integer literal
int numberTen = 10;
// double literal
double floatNumber = 10.2;
// String literal
String firstName = "John";
//boolean literal
bool trueOrFalse = true;
In the above example, 10 is an integer literal, 10.2 is a double literal, “John” is a string literal, and true is a boolean literal. These literals are used to initialise variables with specific data.
Now let us look at String data type in detail. It’s properties and methods to manipulate it.
String Interpolation & Concatenation
String Interpolation or String Concatenation mean the joining of two String variables. The only difference between the two is how it is executed. String Interpolation is executed while returning a value using a dollar sign $. If there is more than one variable of different data types, you must use two curly brackets {}. In String Interpolation, the compiler automatically converts the values into the toString() method.
String Concatenation is executed using the plus + sign between two Strings.
void main () {
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + lastName;
print('My name with String Concatenation $fullName');
print('My name with String Interpolation $firstName $lastName');
}
Output:Console
My name with String Concatenation JohnDoe
My name with String Interpolation John Doe
Method to Manipulate String Variables.
Apostrophe:
If you want an apostrophe between a String value, use a backslash before adding an apostrophe.
// tip: to avoid confusion, always use double quotes when using apostrophes.
String message = "It\'s me in the car";
print(message);
Output:Console
It's me in the car
Quoted Text:
If you want a quoted text, a word or a sentence in the String value, you need to use a backslash before and after the quoted text.
/* tip: if String value is in between double quotes and your
quoted text in single quotes you do not need to
add back-slash and vice versa.
*/
String message = " 'This is a quoted text'. "
String newMessage = ' "This is a new Message" ';
/* if you are using double quotes or single quotes for
both then you need to use back-slash to differentiate between the two.
*/
String firstMessage = "\"This is how it is done!\" "
String secondMessage = '\'This is the second message with quotes!\' ';
Output:Console
'This is a quoted text'.
"This is a new Message"
"This is how it is done!"
'This is the second message with quotes!'
Multi-Line String:
Use three quotes, either double or single, at the start and end of the String value to create a multi-line String.
var sqlQuery = """select users
from users_collection
where userName =?""";
print(sqlQuery);
Output:Console
select users
from users_collection
where userName =?
String multiLineString = """
This is the First Line
This is the Second Line
This is the third line
""";
print("This is also multi line String $multiLineString");
Output:Console
This is also multi line String This is the First Line
This is the Second Line
This is the third line
Getting the length of a String value:
You need to use the length property and the variable name to get the String value’s length.
String singleWord = "flutter";
print("The length of this word is : ${singleWord.length}");
Output:Console
The length of this word is : 7
If you look closely at the above example, we have used string interpolation by using the curly braces to return the string value’s length.
Check for empty String?
If you want to check whether the String value is empty, use a boolean isEmpty and isNotEmpty property.
String emptyString = ' ';
String notEmpty = 'BlahBlah';
// this will return true
print(emptyString.isEmpty);
// this will return false
print(emptyString.isNotEmpty);
// this will return false
print(notEmpty.isEmpty);
// this will return true
print(notEmpty.isNotEmpty);
Output:Console
true
false
false
true
Convert to Lower Case & Upper Case.
Use String.toLowerCase() or String.toUpperCase() to convert all characters of the String value to lower-case or upper-case, respectively.
String toUpperCaseStr = "abcd";
String toLowerCaseStr = "HELLO";
// converts the string to upper-case characters
print(toUpperCaseStr.toUpperCase());
// converts the string to lower-case characters
print(toLowerCaseStr.toLowerCase());
Output:Console
ABCD
hello
Accessing individual character.
You can use brackets [] with its index to access individual characters in a String value. Remember that indexing is zero-based. It means the first character starts with zero, the next character is one and so on.
String characters = "flutter";
print(characters[0]);
print(characters[1]);
print(characters[2]);
print(characters[3]);
print(characters[4]);
print(characters[5]);
print(characters[6]);
Output:Console
f
l
u
t
t
e
r
Replace a substrings with a new value:
replaceAll(Pattern from, String replace) property replaces all the substrings that match the specified pattern with the given new value.
The parameters inside the replaceAll() property:
Pattern from: the String that needs to be replaced
String replace: the new value
String replaceStr = "Flutter World";
print("New String: ${replaceStr.replaceAll('World','For All')}");
Output:Console
New String: Flutter For All
Split String Method:
It splits the String value and returns a list of substrings.
String splitStr = "Today is Friday";
print("Split String : ${splitStr.split(" ")}");
Output:Console
Split String : [Today, is, Friday]
The toString() method:
This is the most common method used in programming. It converts any other data type in a value into a String value.
int age = 12;
var res = age.toString();
print("My Age is : ${res}");
Output:Console
My Age is : 12
Conclusion:
By exploring the most commonly used String methods and their properties, you are taking a significant step towards improving your programming skills. Whether you are an absolute beginner or a seasoned developer, this guide will be a valuable reference. As you navigate through the challenges of programming, remember that guides like this can provide you with the necessary tools to overcome any obstacle. If you found this article helpful, leave a comment and show some appreciation. Keep pushing yourself to experiment with Dart and Flutter, and remember that discovery requires experimentation.