The Basics Flashcards
What’s the difference between Dart and Flutter
- Dart is a client optimized, object-oriented programming language. It is popular nowadays because of flutter. It is difficult to build complete apps only using Dart because you have to manage many things yourself.
- Flutter is a framework that uses dart programming language. With the help of flutter, you can build apps for android, iOS, web, desktop, etc. The framework contains ready-made tools to make apps faster.
Source: https://dart-tutorial.com/introduction-and-basics/
What is a statement?
A statement is a command that tells a computer to do something. In Dart, you can end most statements with a semicolon ;
.
Source: https://dart-tutorial.com/introduction-and-basics/
What is an expression?
An Expression is a value or something that can be calculated as a value. The expression can be numbers, text, or some other type. For E.g.
a. 52 b. 5+5 c. 'Hello World.' d. num
Source: https://dart-tutorial.com/introduction-and-basics/
What is a keyword?
Keywords are reserved words that give special meaning to the dart compiler. For E.g. int, if, var, String, const, etc.
Source: https://dart-tutorial.com/introduction-and-basics/
What is an identifier?
Identifiers are names created by the programmer to define variables, functions, classes, etc. Identifiers shouldn’t be keywords and must have a unique name. For E.g. int age =19;
, here age is an identifier. You will learn more about identifiers later in this course.
Source: https://dart-tutorial.com/introduction-and-basics/
What’s a High-level programming language?
High-Level Programming Language is easy to learn, user-friendly, and uses English-like-sentence. For E.g. dart,c,java,etc.
Source: https://dart-tutorial.com/introduction-and-basics/
What’s a Low-level Programming Language?
Low-level programming language is hard to learn, non-user friendly, and deals with computer hardware components, e.g., machine and assembly language.
Note: Low-level languages are faster than high-level but hard to understand and debug.
Source: https://dart-tutorial.com/introduction-and-basics/
What is Dart?
- Dart is a free and open-source programming language. You don’t need to pay any money to run dart programs.
- Dart is a platform-independent language and supports almost every operating system such as windows, mac, and Linux.
- Dart is an object-oriented programming language and supports all oops features such as encapsulation, inheritance, polymorphism, interface, etc.
- Dart comes with a dart2js compiler which translates dart code to javascript code that runs on all modern browsers.
- Dart is a programming language used by flutter, the world’s most popular framework for building apps.
Source: https://dart-tutorial.com/introduction-and-basics/
What is a variable?
Variables are containers used to store value in the program. There are different types of variables where you can keep different kinds of values. Here is an example of creating a variable and initializing it.
// here variable name contains value John. var name = "John";
Source: https://dart-tutorial.com/introduction-and-basics/
What are the different variable types in Dart?
- String: For storing text value. E.g. “John” [Must be in quotes]
- int: For storing integer value. E.g. 10, -10, 8555 [Decimal is not included]
- double: For storing floating point values. E.g. 10.0, -10.2, 85.698 [Decimal is included]
- num: For storing any type of number. E.g. 10, 20.2, -20 [both int and double]
- bool: For storing true or false. E.g. true, false [Only stores true or false values]
- var: For storing any value. E.g. ‘Bimal’, 12, ‘z’, true
Source: https://dart-tutorial.com/introduction-and-basics/
What is the syntax for declaring a variable in Dart?
type variableName = value;
Examples
void main() { //Declaring Variables String name = "John"; String address = "USA"; num age = 20; // used to store any types of numbers num height = 5.9; bool isMarried = false; // printing variables value print("Name is $name"); print("Address is $address"); print("Age is $age"); print("Height is $height"); print("Married Status is $isMarried"); }
Output
Name is John Address is USA Age is 20 Height is 5.9 Married Status is false
Note: Always use the descriptive variable name. Don’t use a variable name like a, b, c because this will make your code more complex.
Source: https://dart-tutorial.com/introduction-and-basics/
What are the rules for creating variables in Dart?
- Variable names are case sensitive, i.e., a and A are different.
- A variable name can consist of letters and alphabets.
- A variable name cannot start with a number.
- Keywords are not allowed to be used as a variable name.
- Blank spaces are not allowed in a variable name.
- Special characters are not allowed except for the underscore (_) and the dollar ($) sign.
Source: https://dart-tutorial.com/introduction-and-basics/
What is a constant in Dart?
Constant is the type of variable whose value never changes. In programming, changeable values are mutable and unchangeable values are immutable. Sometimes, you don’t need to change the value once declared. Like the value of PI=3.14, it never changes. To create a constant in Dart, you can use the const keyword.
void main(){ const pi = 3.14; pi = 4.23; // not possible print("Value of PI is $pi"); }
Output
Constant variables can't be assigned a value.
Source: https://dart-tutorial.com/introduction-and-basics/
What is the naming convention for variables in Dart?
It is a good habit to follow the naming convention. In Dart Variables, the variable name should start with lower-case, and every second word’s first letter will be upper-case like num1, fullName, isMarried, etc. Technically, this naming convention is called lowerCamelCase.
// Not standard way var fullname = "John Doe"; // Standard way var fullName = "John Doe"; const pi = 3.14;
Source: https://dart-tutorial.com/introduction-and-basics/
What is a data type in Dart?
Data types help you to categorize all the different types of data you use in your code. For e.g. numbers, texts, symbols, etc. The data type specifies what type of value will be stored by the variable. Each variable has its data type. Dart supports the following built-in data types :
- Numbers
- Strings
- Booleans
- Lists
- Maps
- Sets
- Runes
- Null
Source: https://dart-tutorial.com/introduction-and-basics/
What are the different built-in data types in Dart?
In Dart language, there is the type of values that can be represented and manipulated. The data type classification is as given below:
Data Type | Keyword | Description
~~~
| Numbers | int, double, num | It represents numeric values |
| Strings | String | It represents a sequence of characters |
| Booleans | bool | It represents Boolean values true and false |
| Lists | List | It is an ordered group of items |
| Maps | Map | It represents a set of values as key-value pairs |
| Sets | Set | It is an unordered list of unique values of same types |
| Runes | runes | It represents Unicode values of String |
| Null | null | It represents null value |
~~~
Source: https://dart-tutorial.com/introduction-and-basics/
What is a Number in Dart?
When you need to store numeric value on dart, you can use either int or double. Both int and double are subtypes of num. You can use num to store both int or double value.
void main() { // Declaring Variables int num1 = 100; // without decimal point. double num2 = 130.2; // with decimal point. num num3 = 50; num num4 = 50.4; // For Sum num sum = num1 + num2 + num3 + num4; // Printing Info print("Num 1 is $num1"); print("Num 2 is $num2"); print("Num 3 is $num3"); print("Num 4 is $num4"); print("Sum is $sum"); }
Output
Num 1 is 100 Num 2 is 130.2 Num 3 is 50 Num 4 is 50.4 Sum is 330.59999999999997
Source: https://dart-tutorial.com/introduction-and-basics/
How do you round a double value to 2 decimal places?
The .toStringAsFixed(2)
is used to round the double value upto 2 decimal places in dart. You can round to any decimal places by entering numbers like 2, 3, 4, etc.
void main() { // Declaring Variables double prize = 1130.2232323233233; // valid. print(prize.toStringAsFixed(2)); }
Output
1130.22
Source: https://dart-tutorial.com/introduction-and-basics/
How do you create a String in Dart?
String helps you to store text data. You can store values like I love dart, New York 2140 in String. You can use single or double quotes to store string in dart.
void main() { // Declaring Values String schoolName = "Diamond School"; String address = "New York 2140"; // Printing Values print("School name is $schoolName and address is $address"); }
Output
School name is Diamond School and address is New York 2140
Source: https://dart-tutorial.com/introduction-and-basics/
How do you create a multi-line String in Dart?
If you want to create a multi-line String in dart, then you can use triple quotes with either single or double quotation marks.
void main() { // Multi Line Using Single Quotes String multiLineText = ''' This is Multi Line Text with 3 single quote I am also writing here. '''; // Multi Line Using Double Quotes String otherMultiLineText = """ This is Multi Line Text with 3 double quote I am also writing here. """; // Printing Information print("Multiline text is $multiLineText"); print("Other multiline text is $otherMultiLineText"); }
Output
Multiline text is This is Multi Line Text with 3 single quote I am also writing here. Other multiline text is This is Multi Line Text with 3 double quote I am also writing here.
Source: https://dart-tutorial.com/introduction-and-basics/
What are some special characters in a String?
Special Character | Work
~~~
| \t | Tab |
~~~
Example usage
void main() { // Using \n and \t print("I am from \nUS."); print("I am from \tUS."); }
Output
I am from US. I am from US.
\n | New Line |
Source: https://dart-tutorial.com/introduction-and-basics/
How to you create a Raw String in Dart?
You can create a raw string in dart. Special characters won’t work here. You must write r after equal sign.
void main() { // Set prize value num prize = 10; String withoutRawString = "The value of prize is \t $prize"; // regular String String withRawString =r"The value of prize is \t $prize"; // raw String print("Without Raw: $withoutRawString"); // regular result print("With Raw: $withRawString"); // with raw result }
Output
Without Raw: The value of prize is 10 With Raw: The value of prize is \t $prize
Source: https://dart-tutorial.com/introduction-and-basics/
What is type conversion in Dart?
In dart, type conversion allows you to convert one data type to another type. For e.g. to convert String to int, int to String or String to bool, etc.
Source: https://dart-tutorial.com/introduction-and-basics/
How do you convert a String to an Int in Dart?
You can convert String to int using int.parse() method. The method takes String as an argument and converts it into an integer.
void main() { String strvalue = "1"; print("Type of strvalue is ${strvalue.runtimeType}"); int intvalue = int.parse(strvalue); print("Value of intvalue is $intvalue"); // this will print data type print("Type of intvalue is ${intvalue.runtimeType}"); }
Output
void main() { String strvalue = "1"; print("Type of strvalue is ${strvalue.runtimeType}"); int intvalue = int.parse(strvalue); print("Value of intvalue is $intvalue"); // this will print data type print("Type of intvalue is ${intvalue.runtimeType}"); }
Source: https://dart-tutorial.com/introduction-and-basics/
How do you convert a String to a Double in Dart?
You can convert String to double using double.parse() method. The method takes String as an argument and converts it into a double.
void main() { String strvalue = "1.1"; print("Type of strvalue is ${strvalue.runtimeType}"); double doublevalue = double.parse(strvalue); print("Value of doublevalue is $doublevalue"); // this will print data type print("Type of doublevalue is ${doublevalue.runtimeType}"); }
Output
Type of strvalue is String Value of doublevalue is 1.1 Type of doublevalue is double
Source: https://dart-tutorial.com/introduction-and-basics/
How do you convert an Int to a String in Dart?
You can convert int to String using the toString() method. Here is example:
void main() { int one = 1; print("Type of one is ${one.runtimeType}"); String oneInString = one.toString(); print("Value of oneInString is $oneInString"); // this will print data type print("Type of oneInString is ${oneInString.runtimeType}"); }
Output
Type of one is int Value of oneInString is 1 Type of oneInString is String
Source: https://dart-tutorial.com/introduction-and-basics/
How do you convert a Double to an Int in Dart?
You can convert double to int using the toInt() method.
void main() { double num1 = 10.01; int num2 = num1.toInt(); // converting double to int print("The value of num1 is $num1. Its type is ${num1.runtimeType}"); print("The value of num2 is $num2. Its type is ${num2.runtimeType}"); }
Output
The value of num1 is 10.01. Its type is double The value of num2 is 10. Its type is int
Source: https://dart-tutorial.com/introduction-and-basics/
What is a Boolean in Dart?
In Dart, boolean holds either true or false value. You can write the bool keyword to define the boolean data type. You can use boolean if the answer is true or false. Consider the answer to the following questions:
- Are you married?
- Is the door open?
- Does a cat fly?
- Is the traffic light green?
- Are you older than your father?
These all are yes/no questions. Its a good idea to store them in boolean.
void main() { bool isMarried = true; print("Married Status: $isMarried"); }
Output
Married Status: true
Source: https://dart-tutorial.com/introduction-and-basics/
What is a List in Dart?
The list holds multiple values in a single variable. It is also called arrays. If you want to store multiple values without creating multiple variables, you can use a list.
void main() { List<String> names = ["Raj", "John", "Max"]; print("Value of names is $names"); print("Value of names[0] is ${names[0]}"); // index 0 print("Value of names[1] is ${names[1]}"); // index 1 print("Value of names[2] is ${names[2]}"); // index 2 // Finding Length of List int length = names.length; print("The Length of names is $length"); }
Output
Value of names is [Raj, John, Max] Value of names[0] is Raj Value of names[1] is John Value of names[2] is Max The Length of names is 3
Note: List index always starts with 0. Here names[0] is Raj, names[1] is John and names[2] is Max.
Source: https://dart-tutorial.com/introduction-and-basics/
What is a Set in Dart?
An unordered collection of unique items is called set in dart. You can store unique data in sets.
Note: Set doesn’t print duplicate items.
void main() { Set<String> weekday = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; print(weekday); }
Output
{Sun, Mon, Tue, Wed, Thu, Fri, Sat}
Source: https://dart-tutorial.com/introduction-and-basics/
What is a Map in Dart?
In Dart, a map is an object where you can store data in key-value pairs. Each key occurs only once, but you can use same value multiple times.
void main() { Map<String, String> myDetails = { 'name': 'John Doe', 'address': 'USA', 'fathername': 'Soe Doe' }; print(myDetails['name']); }
Output
John Doe
Source: https://dart-tutorial.com/introduction-and-basics/
What is the var Keyword in Dart?
In Dart, var automatically finds a data type. In simple terms, var says if you don’t want to specify a data type, I will find a data type for you.
void main(){ var name = "John Doe"; // String var age = 20; // int print(name); print(age); }
Output
John Doe 20
Source: https://dart-tutorial.com/introduction-and-basics/
What is a Rune in Dart?
With runes, you can find Unicode values of String. The Unicode value of a is 97, so runes give 97 as output.
void main() { String value = "a"; print(value.runes); }
Output
(97)
Source: https://dart-tutorial.com/introduction-and-basics/
How do you check a type at runtime in Dart?
You can check runtime type in dart with .runtimeType
after the variable name.
void main() { var a = 10; print(a.runtimeType); print(a is int); // true }
Output
int true
Source: https://dart-tutorial.com/introduction-and-basics/
What is an optionally typed language?
You may have heard of the statically-typed language. It means the data type of variables is known at compile time. Similarly, dynamically-typed language means data types of variables are known at run time. Dart supports dynamic and static types, so it is called optionally-typed language.
Source: https://dart-tutorial.com/introduction-and-basics/
What is a statically typed Language?
A language is statically typed if the data type of variables is known at compile time. Its main advantage is that the compiler can quickly check the issues and detect bugs.
void main() { var myVariable = 50; // You can also use int instead of var myVariable = "Hello"; // this will give error print(myVariable); }
Output
Error: A value of type 'String' can't be assigned to a variable of type 'int'.
Source: https://dart-tutorial.com/introduction-and-basics/
What is a dynamically typed language?
A language is dynamically typed if the data type of variables is known at run time.
void main() { dynamic myVariable = 50; myVariable = "Hello"; print(myVariable); }
Output
Hello
Source: https://dart-tutorial.com/introduction-and-basics/
What are comments in Dart?
Comments are the set of statements that are ignored by the dart compiler during program execution. They are used to explain the code so that you or other people can understand it easily.
Source: https://dart-tutorial.com/introduction-and-basics/
What are some advantages of coments?
- You can describe your code.
- Other people will understand your code more clearly.
Source: https://dart-tutorial.com/introduction-and-basics/
What are the different types of comments in Dart?
- Single-Line Comment: For commenting on a single line of code. E.g. // This is a single-line comment.
- Multi-Line Comment: For commenting on multiple lines of code. E.g. /* This is a multi-line comment. */
- Documentation Comment: For generating documentation or reference for a project/software package. E.g. /// This is a documentation comment
Source: https://dart-tutorial.com/introduction-and-basics/
How do you create a single-line comment in Dart?
Single line comments start with //
in dart. You can write //
and your text.
void main() { // This is single-line comment. print("Welcome to Technology Channel."); }
Output
Welcome to Technology Channel.
Source: https://dart-tutorial.com/introduction-and-basics/
How do you create a multi-line comment in Dart?
Multi-line comments start with /*
and end with */
. You can write your comment inside /*
and */
.
void main(){ /* This is a multi-line comment. */ print("Welcome to Technology Channel."); }
Output
Welcome to Technology Channel.
Source: https://dart-tutorial.com/introduction-and-basics/
How do you create a documentation comment in Dart?
Documentation comments are helpful when you are writing documentation for your code. Documentation comments start with /// in dart.
void main(){ /// This is documentation comment print("Welcome to Technology Channel."); }
Output
Welcome to Technology Channel.
Source: https://dart-tutorial.com/introduction-and-basics/
What are operators in Dart?
Operators are used to perform mathematical and logical operations on the variables. Each operation in dart uses a symbol called the operator to denote the type of operation it performs. Before learning operators in the dart, you must understand the following things.
- Operands : It represents the data.
- Operator : It represents how the operands will be processed to produce a value.
Note: Suppose the given expression is 2 + 3. Here 2 and 3 are operands, and +
is the operator.
Source: https://dart-tutorial.com/introduction-and-basics/
What are the different types of operators in Dart?
- Arithmetic Operators
- Increment and Decrement Operators
- Assignment Operators
- Logical Operators
- Type Test Operators
Source: https://dart-tutorial.com/introduction-and-basics/
What are the different arithmetic operators?
Arithmetic operators are the most common types of operators. They perform operations like addition, subtraction, multiplication, division, etc.
Operator Symbol | Operator Name Description*
~~~
+ | Addition For adding two operands
- | Subtraction For subtracting two operands
-expr | Unary Minus For reversing the sign of the expression
* | Multiplication For multiplying two operands
/ | Division For dividing two operands and give output in double
~/ | Integer Division For dividing two operands and give output in integer
% | Modulus Remainder After Integer Division
~~~
Example
void main() { // declaring two numbers int num1=10; int num2=3; // performing arithmetic calculation int sum=num1+num2; // addition int diff=num1-num2; // subtraction int unaryMinus = -num1; // unary minus int mul=num1*num2; // multiplication double div=num1/num2; // division int div2 =num1~/num2; // integer division int mod=num1%num2; // show remainder //Printing info print("The addition is $sum."); print("The subtraction is $diff."); print("The unary minus is $unaryMinus."); print("The multiplication is $mul."); print("The division is $div."); print("The integer division is $div2."); print("The modulus is $mod."); }
Output
The addition is 13. The subtraction is 7. The unary minus is -10. The multiplication is 30. The division is 3.3333333333333335. The integer division is 3. The modulus is 1.
Source: https://dart-tutorial.com/introduction-and-basics/
What are increment and decrement operators?
With increment and decrement operators, you can increase and decrease values. If ++ is used at the beginning, then it is a prefix. If it is used at last, then it is postfix.
Operator symbol | Operator name | Description
~~~
++var | Pre Increment | Increase Value By 1. var = var + 1 Expression value is var+1
–var | Pre Decrement | Decrease Value By 1. var = var - 1 Expression value is var-1
var++ | Post Increment | Increase Value By 1. var = var + 1 Expression value is var
var– | Post Decrement | Decrease Value By 1. var = var - 1 Expression value is var
~~~
Note: ++var increases the value of operands, whereas var++ returns the actual value of operands before the increment.
Example
void main() { // declaring two numbers int num1=0; int num2=0; // performing increment / decrement operator // pre increment num2 = ++num1; print("The value of num2 is $num2"); // reset value to 0 num1 = 0; num2 = 0; // post increment num2 = num1++; print("The value of num2 is $num2"); }
Output
The value of num2 is 1 The value of num2 is 0
Source: https://dart-tutorial.com/introduction-and-basics/
What are assignment operators?
It is used to assign some values to variables. Here, we are assigning 24 to the age variable.
int age = 24;
Operator type | Description
~~~
= | Assign a value to a variable
+= | Adds a value to a variable
-= | Reduces a value to a variable
*= | Multiply value to a variable
/= | Divided value by a variable
~~~
Example
void main() { double age = 24; age+= 1; // Here age+=1 means age = age + 1. print("After Addition Age is $age"); age-= 1; //Here age-=1 means age = age - 1. print("After Subtraction Age is $age"); age*= 2; //Here age*=2 means age = age * 2. print("After Multiplication Age is $age"); age/= 2; //Here age/=2 means age = age / 2. print("After Division Age is $age"); }
Output
After Addition Age is 25.0 After Aubtraction Age is 24.0 After Multiplication Age is 48.0 After Division Age is 24.0
Source: https://dart-tutorial.com/introduction-and-basics/
What are relational operators?
Relational operators are also called comparison operators. They are used to make a comparison.
Operator symbol | Operator name | Description
~~~
> | Greater than | Used to check which operand is bigger and gives result as boolean
< | Less than | Used to check which operand is smaller and gives result as boolean
>= | Greater than or equal to | Used to check which operand is bigger or equal and gives result as boolean
<= | Less than or equal to | Used to check which operand is smaller or equal and gives result as boolean
== | Equal to | Used to check operands are equal to each other and gives result as boolean
!= | Not equal to | Used to check operand are not equal to each other and gives result as boolean
~~~
Example
void main() { int num1=10; int num2=5; //printing info print(num1==num2); print(num1<num2); print(num1>num2); print(num1<=num2); print(num1>=num2); }
Output
false false true false true
Source: https://dart-tutorial.com/introduction-and-basics/
What are logical operators?
It is used to compare values.
Operator type | Description
~~~
&& | This is ‘and’, return true if all conditions are true
|| | This is ‘or’. Return true if one of the conditions is true
! | This is ’not’. return false if the result is true and vice versa
~~~
Example
void main(){ int userid = 123; int userpin = 456; // Printing Info print((userid == 123) && (userpin== 456)); // print true print((userid == 1213) && (userpin== 456)); // print false. print((userid == 123) || (userpin== 456)); // print true. print((userid == 1213) || (userpin== 456)); // print true print((userid == 123) != (userpin== 456));//print false }
Output
true false true true false
Source: https://dart-tutorial.com/introduction-and-basics/
What are type test operators?
In Dart, type test operators are useful for checking types at runtime.
Operator symbol | Operator name | Description
~~~
is | is | Gives boolean value true if the object has a specific type
is! | is not | Gives boolean value false if the object has a specific type
~~~
Example
void main() { String value1 = "Dart Tutorial"; int age = 10; print(value1 is String); print(age is !int); }
Output
true false
Source: https://dart-tutorial.com/introduction-and-basics/
How is user input done in Dart?
Instead of writing hard-coded values, you can give input to the computer. It will make your program more dynamic. You must import the package import 'dart:io';
for user input.
Note: You won’t be able to take input from users using dartpad. You need to run a program from your computer.
Source: https://dart-tutorial.com/introduction-and-basics/
What is String user input?
They are used for storing textual user input. If you want to keep values like somebody’s name, address, description, etc., you can take string input from the user.
import 'dart:io'; void main() { print("Enter name:"); String? name = stdin.readLineSync(); print("The entered name is ${name}"); }
Output
Enter name: Raj Sharma The entered name is Raj Sharma
Source: https://dart-tutorial.com/introduction-and-basics/
What is Integer user input?
You can take integer input to get a numeric value from the user without the decimal point. E.g. 10, 100, -800 etc.
import 'dart:io'; void main() { print("Enter number:"); int? number = int.parse(stdin.readLineSync()!); print("The entered number is ${number}"); }
Output
Enter number: 50 The entered number is 50
Source: https://dart-tutorial.com/introduction-and-basics/
How can you take a Floting Point value from user input?
You can use float input if you want to get a numeric value from the user with the decimal point. E.g. 10.5, 100.5, -800.9 etc.
import 'dart:io'; void main() { print("Enter a floating number:"); double number = double.parse(stdin.readLineSync()!); print("The entered num is $number"); }
Output
Enter a floating number: 55.5 The entered num is 55.5
Source: https://dart-tutorial.com/introduction-and-basics/
What is a String in Dart?
String helps you to store text based data. In String, you can represent your name, address, or complete book. It holds a series or sequence of characters – letters, numbers, and special characters. You can use single or double, or triple quotes to represent String.
Single line String is written in single or double quotes, whereas multi-line strings are written in triple quotes. Here is an example of it:
void main() { String text1 = 'This is an example of a single-line string.'; String text2 = "This is an example of a single line string using double quotes."; String text3 = """This is a multiline line string using the triple-quotes. This is tutorial on dart strings. """; print(text1); print(text2); print(text3); }
Output
This is an example of a single-line string. This is an example of a single line string using double quotes. This is a multiline line string using the triple-quotes. This is tutorial on dart strings.
Source: https://dart-tutorial.com/introduction-and-basics/
How do you perform String concatenation in Dart?
You can combine one String with another string. This is called concatenation. In Dart, you can use the + operator or use interpolation to concatenate the String. Interpolation makes it easy to read and understand the code.
void main() { String firstName = "John"; String lastName = "Doe"; print("Using +, Full Name is "+firstName + " " + lastName+"."); print("Using interpolation, full name is $firstName $lastName."); }
Source: https://dart-tutorial.com/introduction-and-basics/
What are the Properties of a String in Dart?
- codeUnits: Returns an unmodifiable list of the UTF-16 code units of this string.
- isEmpty: Returns true if this string is empty.
- isNotEmpty: Returns false if this string is empty.
- length: Returns the length of the string including space, tab, and newline characters.
void main() { String str = "Hi"; print(str.codeUnits); //Example of code units print(str.isEmpty); //Example of isEmpty print(str.isNotEmpty); //Example of isNotEmpty print("The length of the string is: ${str.length}"); //Example of Length }
Output
[72, 105] false true The length of the String is: 2
Source: https://dart-tutorial.com/introduction-and-basics/
What are the Methods of a String?
- toLowerCase(): Converts all characters in this string to lowercase.
- toUpperCase(): Converts all characters in this string to uppercase.
- trim(): Returns the string without any leading and trailing whitespace.
- compareTo(): Compares this object to another.
- replaceAll(): Replaces all substrings that match the specified pattern with a given value.
- split(): Splits the string at matches of the specified delimiter and returns a list of substrings.
- toString(): Returns a string representation of this object.
- substring(): Returns the text from any position you want.
- codeUnitAt(): Returns the 16-bit UTF-16 code unit at the given index.
Source: https://dart-tutorial.com/introduction-and-basics/
How do you convert a String to uppercase and lowercase?
You can convert your text to lower case using .toLowerCase() and convert to uppercase using .toUpperCase() method.
//Example of toUpperCase() and toLowerCase() void main() { String address1 = "Florida"; // Here F is capital String address2 = "TexAs"; // Here T and A are capital print("Address 1 in uppercase: ${address1.toUpperCase()}"); print("Address 1 in lowercase: ${address1.toLowerCase()}"); print("Address 2 in uppercase: ${address2.toUpperCase()}"); print("Address 2 in lowercase: ${address2.toLowerCase()}"); }
Output
Address 1 in uppercase: FLORIDA Address 1 in lowercase: florida Address 2 in uppercase: TEXAS Address 2 in lowercase: texas
Source: https://dart-tutorial.com/introduction-and-basics/
How do you trim a String?
Trim is helpful when removing leading and trailing spaces from the text. This trim method will remove all the starting and ending spaces from the text. You can also use trimLeft() and trimRight() methods to remove space from left and right, respectively.
Note: The trim() method in Dart doesn’t remove spaces in the middle.
//Example of trim() void main() { String address1 = " USA"; // Contain space at leading. String address2 = "Japan "; // Contain space at trailing. String address3 = "New Delhi"; // Contains space at middle. print("Result of address1 trim is ${address1.trim()}"); print("Result of address2 trim is ${address2.trim()}"); print("Result of address3 trim is ${address3.trim()}"); print("Result of address1 trimLeft is ${address1.trimLeft()}"); print("Result of address2 trimRight is ${address2.trimRight()}"); }
Output
Result of address1 trim is USA Result of address2 trim is Japan Result of address3 trim is New Delhi Result of address1 trimLeft is USA Result of address2 trimRight is Japan
Source: https://dart-tutorial.com/introduction-and-basics/
How do you compare Strings in Dart?
In Dart, you can compare two strings. It will give the result 0 when two texts are equal, 1 when the first String is greater than the second, and -1 when the first String is smaller than the second.
//Example of compareTo() void main() { String item1 = "Apple"; String item2 = "Ant"; String item3 = "Basket"; print("Comparing item 1 with item 2: ${item1.compareTo(item2)}"); print("Comparing item 1 with item 3: ${item1.compareTo(item3)}"); print("Comparing item 3 with item 2: ${item3.compareTo(item2)}"); }
Output
Comparing item 1 with item 2: 1 Comparing item 1 with item 3: -1 Comparing item 3 with item 2: 1
Source: https://dart-tutorial.com/introduction-and-basics/
How do you perform String replacement in Dart?
You can replace one value with another with the replaceAll(“old”, “new”) method in Dart. It will replace all the “old” words with “new”. Here in this example, this will replace milk with water.
//Example of replaceAll() void main() { String text = "I am a good boy I like milk. Doctor says milk is good for health."; String newText = text.replaceAll("milk", "water"); print("Original Text: $text"); print("Replaced Text: $newText"); }
Output
Original Text: I am a good boy I like milk. Doctor says milk is good for health. Replaced Text: I am a good boy I like water. Doctor says water is good for health.
Source: https://dart-tutorial.com/introduction-and-basics/
How do you split a String in Dart?
You can use the dart split method if you want to split String by comma, space, or other text. It will help you to split String to list.
//Example of split() void main() { String allNames = "Ram, Hari, Shyam, Gopal"; List<String> listNames = allNames.split(","); print("Value of listName is $listNames"); print("List name at 0 index ${listNames[0]}"); print("List name at 1 index ${listNames[1]}"); print("List name at 2 index ${listNames[2]}"); print("List name at 3 index ${listNames[3]}"); }
Output
Value of listName is [Ram, Hari, Shyam, Gopal] List name at 0 index Ram List name at 1 index Hari List name at 2 index Shyam List name at 3 index Gopal
Source: https://dart-tutorial.com/introduction-and-basics/
How do you convert an Int to a String?
In dart, toString() represents String representation of the value/object.
//Example of toString() void main() { int number = 20; String result = number.toString(); print("Type of number is ${number.runtimeType}"); print("Type of result is ${result.runtimeType}"); }
Output
Type of number is int Type of result is String
Source: https://dart-tutorial.com/introduction-and-basics/
How do I get a substring from a String?
You can use substring in Dart when you want to get a text from any position.
//Example of substring() void main() { String text = "I love computer"; print("Print only computer: ${text.substring(7)}"); // from index 6 to the last index print("Print only love: ${text.substring(2,6)}");// from index 2 to the 6th index }
Output
Print only computer: computer Print only love: love
Source: https://dart-tutorial.com/introduction-and-basics/
How do you reverse a String?
If you want to reverse a String in Dart, you can reverse it using a different solution. One solution is here.
void main() { String input = "Hello"; print("$input Reverse is ${input.split('').reversed.join()}"); }
Output
Hello Reverse is olleH
Source: https://dart-tutorial.com/introduction-and-basics/
How do you capitalize the first letter of a String in Dart?
If you want to capitalize the first letter of a String in Dart, you can use the following code.
//Example of capitalize first letter of String void main() { String text = "hello world"; print("Capitalized first letter of String: ${text[0].toUpperCase()}${text.substring(1)}"); }
Output
Capitalized first letter of String: Hello world
Source: https://dart-tutorial.com/introduction-and-basics/