Skip to main content

Dart Programming (String, Boolen,List,Map)

 

Dart Programming



Dart Programming - String



The String data type represents a sequence of characters. A Dart string is a sequence of UTF 16 code units.

String values in Dart can be represented using either single or double or triple quotes. Single line strings are represented using single or double quotes. Triple quotes are used to represent multi-line strings.

The syntax of representing string values in Dart is as given below −

Syntax

String  variable_name = 'value'  

OR  

String  variable_name = ''value''  

OR  

String  variable_name = '''line1 
line2'''  

OR  

String  variable_name= ''''''line1 
line2''''''

The following example illustrates the use of String data type in Dart.

void main() { 
   String str1 = 'this is a single line string'; 
   String str2 = "this is a single line string"; 
   String str3 = '''this is a multiline line string'''; 
   String str4 = """this is a multiline line string"""; 
   
   print(str1);
   print(str2); 
   print(str3); 
   print(str4); 
}

It will produce the following Output −

this is a single line string 
this is a single line string 
this is a multiline line string 
this is a multiline line string 

Strings are immutable. However, strings can be subjected to various operations and the resultant string can be a stored as a new value.

String Interpolation

The process of creating a new string by appending a value to a static string is termed as concatenation or interpolation. In other words, it is the process of adding a string to another string.

The operator plus (+) is a commonly used mechanism to concatenate / interpolate strings.

Example 1

void main() { 
   String str1 = "hello"; 
   String str2 = "world"; 
   String res = str1+str2; 
   
   print("The concatenated string : ${res}"); 
}

It will produce the following output −

The concatenated string : Helloworld

Example 2

You can use "${}" can be used to interpolate the value of a Dart expression within strings. The following example illustrates the same.

void main() { 
   int n=1+1; 
   
   String str1 = "The sum of 1 and 1 is ${n}"; 
   print(str1); 
   
   String str2 = "The sum of 2 and 2 is ${2+2}"; 
   print(str2); 
}

It will produce the following output −

The sum of 1 and 1 is 2 
The sum of 2 and 2 is 4

String Properties

The properties listed in the following table are all read-only.

Sr.NoProperty & Description
1codeUnits

Returns an unmodifiable list of the UTF-16 code units of this string.

2isEmpty

Returns true if this string is empty.

3Length

Returns the length of the string including space, tab and newline characters.

Methods to Manipulate Strings

The String class in the dart: core library also provides methods to manipulate strings. Some of these methods are given below −

Sr.NoMethods & Description
1toLowerCase()

Converts all characters in this string to lower case.

2toUpperCase()

Converts all characters in this string to upper case.

3trim()

Returns the string without any leading and trailing whitespace.

4compareTo()

Compares this object to another.

5replaceAll()

Replaces all substrings that match the specified pattern with a given value.

6split()

Splits the string at matches of the specified delimiter and returns a list of substrings.

7substring()

Returns the substring of this string that extends from startIndex, inclusive, to endIndex, exclusive.

8toString()

Returns a string representation of this object.

9

codeUnitAt()

Returns the 16-bit UTF-16 code unit at the given index.






Dart Programming - Boolean




Dart provides an inbuilt support for the Boolean data type. The Boolean data type in DART supports only two values – true and false. The keyword bool is used to represent a Boolean literal in DART.

The syntax for declaring a Boolean variable in DART is as given below −

bool var_name = true;  
OR  
bool var_name = false 

Example

void main() { 
   bool test; 
   test = 12 > 5; 
   print(test); 
}

It will produce the following output −

true 

Example

Unlike JavaScript, the Boolean data type recognizes only the literal true as true. Any other value is considered as false. Consider the following example −

var str = 'abc'; 
if(str) { 
   print('String is not empty'); 
} else { 
   print('Empty String'); 
} 

The above snippet, if run in JavaScript, will print the message ‘String is not empty’ as the if construct will return true if the string is not empty.

However, in Dart, str is converted to false as str != true. Hence the snippet will print the message ‘Empty String’ (when run in unchecked mode).

Example

The above snippet if run in checked mode will throw an exception. The same is illustrated below −

void main() { 
   var str = 'abc'; 
   if(str) { 
      print('String is not empty'); 
   } else { 
      print('Empty String'); 
   } 
}

It will produce the following output, in Checked Mode −

Unhandled exception: 
type 'String' is not a subtype of type 'bool' of 'boolean expression' where 
   String is from dart:core 
   bool is from dart:core  
#0 main (file:///D:/Demos/Boolean.dart:5:6) 
#1 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261) 
#2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)

It will produce the following output, in Unchecked Mode −

Empty String

Note − The WebStorm IDE runs in checked mode, by default.



Dart Programming - Lists



A very commonly used collection in programming is an array. Dart represents arrays in the form of List objects. A List is simply an ordered group of objects. The dart:core library provides the List class that enables creation and manipulation of lists.

The logical representation of a list in Dart is given below −

Logical Representation of a List
  • test_list − is the identifier that references the collection.

  • The list contains in it the values 12, 13, and 14. The memory blocks holding these values are known as elements.

  • Each element in the List is identified by a unique number called the index. The index starts from zero and extends up to n-1 where n is the total number of elements in the List. The index is also referred to as the subscript.

Lists can be classified as −

  • Fixed Length List
  • Growable List

Let us now discuss these two types of lists in detail.

Fixed Length List

A fixed length list’s length cannot change at runtime. The syntax for creating a fixed length list is as given below −

Step 1 − Declaring a list

The syntax for declaring a fixed length list is given below −

var list_name = new List(initial_size)

The above syntax creates a list of the specified size. The list cannot grow or shrink at runtime. Any attempt to resize the list will result in an exception.

Step 2 − Initializing a list

The syntax for initializing a list is as given below −

lst_name[index] = value;

Example

 Live Demo
void main() { 
   var lst = new List(3); 
   lst[0] = 12; 
   lst[1] = 13; 
   lst[2] = 11; 
   print(lst); 
}

It will produce the following output −

[12, 13, 11]

Growable List

A growable list’s length can change at run-time. The syntax for declaring and initializing a growable list is as given below −

Step 1 − Declaring a List

var list_name = [val1,val2,val3]   
--- creates a list containing the specified values  
OR  
var list_name = new List() 
--- creates a list of size zero 

Step 2 − Initializing a List

The index / subscript is used to reference the element that should be populated with a value. The syntax for initializing a list is as given below −

list_name[index] = value;

Example

The following example shows how to create a list of 3 elements.

 Live Demo
void main() { 
   var num_list = [1,2,3]; 
   print(num_list); 
}

It will produce the following output −

[1, 2, 3]

Example

The following example creates a zero-length list using the empty List() constructor. The add() function in the List class is used to dynamically add elements to the list.

 Live Demo
void main() { 
   var lst = new List(); 
   lst.add(12); 
   lst.add(13); 
   print(lst); 
} 

It will produce the following output −

[12, 13] 

List Properties

The following table lists some commonly used properties of the List class in the dart:core library.

Sr.NoMethods & Description
1first

Returns the first element in the list.

2isEmpty

Returns true if the collection has no elements.

3isNotEmpty

Returns true if the collection has at least one element.

4length

Returns the size of the list.

5last

Returns the last element in the list.

6reversed

Returns an iterable object containing the lists values in the reverse order.

7Single

Checks if the list has only one element and returns it.



Dart Programming - Map


The Map object is a simple key/value pair. Keys and values in a map may be of any type. A Map is a dynamic collection. In other words, Maps can grow and shrink at runtime.

Maps can be declared in two ways −

  • Using Map Literals
  • Using a Map constructor

Declaring a Map using Map Literals

To declare a map using map literals, you need to enclose the key-value pairs within a pair of curly brackets "{ }".

Here is its syntax −

var identifier = { key1:value1, key2:value2 [,…..,key_n:value_n] }

Declaring a Map using a Map Constructor

To declare a Map using a Map constructor, we have two steps. First, declare the map and second, initialize the map.

The syntax to declare a map is as follows −

var identifier = new Map()

Now, use the following syntax to initialize the map −

map_name[key] = value

Example: Map Literal

void main() { 
   var details = {'Usrname':'tom','Password':'pass@123'}; 
   print(details); 
}

It will produce the following output −

{Usrname: tom, Password: pass@123}

Example: Adding Values to Map Literals at Runtime

void main() { 
   var details = {'Usrname':'tom','Password':'pass@123'}; 
   details['Uid'] = 'U1oo1'; 
   print(details); 
} 

It will produce the following output −

{Usrname: tom, Password: pass@123, Uid: U1oo1}

Example: Map Constructor

void main() { 
   var details = new Map(); 
   details['Usrname'] = 'admin'; 
   details['Password'] = 'admin@123'; 
   print(details); 
} 

It will produce the following output −

{Usrname: admin, Password: admin@123}

Note − A map value can be any object including NULL.

Map – Properties

The Map class in the dart:core package defines the following properties −

Sr.NoProperty & Description
1Keys

Returns an iterable object representing keys

2Values

Returns an iterable object representing values

3Length

Returns the size of the Map

4isEmpty

Returns true if the Map is an empty Map

5isNotEmpty

Returns true if the Map is an empty Map

Map - Functions

Following are the commonly used functions for manipulating Maps in Dart.

Sr.NoFunction Name & Description
1addAll()

Adds all key-value pairs of other to this map.

2clear()

Removes all pairs from the map.

3remove()

Removes key and its associated value, if present, from the map.

4forEach()

Applies f to each key-value pair of the map.

Comments

All Post

When to Use Waterfall vs. Agile

  We compare the benefits and drawbacks of using two well-known software development methodologies, Waterfall and Agile, and lay out when it might be more suitable to use one over the other – or combine practices of both – for your product initiative. When developing a new software product, your team will need to navigate which development methodology is right for your initiative. In the world of managing  software development  projects, the topic of Agile vs Waterfall is widely debated. Many thought leaders and Agile enthusiasts in the industry have argued Waterfall is dead, however, traditional organizational environments and processes have led to it still being widely used today. A 2017 report from the Project Management Institute shows that  51% of the organizations surveyed use Waterfall either often or always . The reality is, each software development project poses its own unique challenges and requirements. It’s not a matter of deciding which development meth...

Flutter form validation: Full guide for you to make Flutter form

  Flutter form validation Getting started with form validation in Flutter The Flutter SDK provides us with an out-of-the-box widget and functionalities to make our lives easier when using form validation. In this article, we’ll cover two approaches to form validation: the form widget and the Provider package. You can find more information on these two approaches in the official Flutter docs. Creating a form in Flutter First, we are going to create a simple login page that has the following fields: Email Name Phone number Password For the validation, we want the users of our app to fill in the correct details in each of these fields. The logic will be defined as such: First, for the name field, we want the user to enter a valid first name and last name, which can be accompanied by initials. For the email field, we want a valid email that contains some characters before the “@” sign, as well as the email domain at the end of the email. For phone number validation, the user is expecte...

How to change the language on Android at runtime and don’t go mad

  How to change the language on Android at runtime and don’t go mad TL;DR There is a library called Lingver that implements the presented approach with just a few lined of code.  Check it out! Introduction The topic is old as the hills, but still is being actively discussed among developers due to frequent API and behavior changes. The goal of this post is to gather all tips and address all pitfalls while implementing this functionality. Disclaimer Changing the language on Android at runtime was never officially encouraged or documented. The resource framework automatically selects the resources that best match the device. Such behavior is enough for common applications, so just make sure you have strict reasons to change it before proceeding further. There are a ton of articles and answers on Stack Overflow but they usually lack enough of explanation. As a result, when this functionality gets broken, developers can’t easily fix it due to the messy API and lots of deprecated t...

7 Key Android Concepts

  Although the Android platform is open and customizable, Android users have become accustomed to constructs developed by Google for Android devices. Although the Android platform is open and customizable, Android users have become accustomed to constructs developed by Google for Android devices. Moreover, the use of these Android concepts is vital in developing an application quickly – custom Android designs can take up to 10 times longer! Android UI Controls Android provides a number of standard UI controls that  enable a rich user experience . Designers and developers should thoroughly understand all of these controls for the following reasons: They are faster to implement. It can take up to ten times longer to develop a custom control than to implement a user interface with standard Android controls. They ensure good performance. Custom controls rarely function as expected in their first implementation. By implementing standard controls, you can eliminate the need to test,...

Clean Code and the Art of Exception Handling

  Clean Code and the Art of Exception Handling Exceptions are as old as programming itself. An unhandled exception may cause unexpected behavior, and results can be spectacular. Over time, these errors have contributed to the impression that exceptions are bad. But exceptions are a fundamental element of modern programming. Rather than fearing exceptions, we should embrace them and learn how to benefit from them. In this article, we will discuss how to manage exceptions elegantly, and use them to write clean code that is more maintainable. Exceptions are as old as programming itself. Back in the days when programming was done in hardware, or via low-level programming languages, exceptions were used to alter the flow of the program, and to avoid hardware failures. Today, Wikipedia  defines exceptions as: anomalous or exceptional conditions requiring special processing – often changing the normal flow of program execution specialized programming language constructs or computer h...

How to them the background of the Android options menu items

  “What we’ve got here is… failure to theme. Some views you just can’t reach. So you get what we had here last project, which is the way Android wants it… well, it gets it. I don’t like it any more than you men.” – Captain, Road Prison 36 Some of you might recognize the previous paragraph as the introduction of Guns ‘N Roses’ Civil War or from the movie Cold Hand Luke starring Paul Newman. This is the feeling I get when I try to create a custom theme for an application on Android. The Android SDK does permit some level of theming, which is not really well documented to start with. Other things are hard-coded, “so you get what we had here last project”. Now, one of the things your application will most likely use is the Options menu, which is the menu you see when you press the hard menu key. It is kind of… orange. In our last project, we had to completely remove the orange in favor of our customer’s color scheme, which is on the blue side. I couldn’t find a way to change the menu i...

Android Jetpack Compose

  Jetpack Compose Tutorial for Android: Getting Started Jetpack Compose is Android’s modern toolkit for building native UI. It simplifies and accelerates UI development on Android. Quickly bring your app to life with less code, powerful tools, and intuitive Kotlin APIs. At Google I/O 2019, Google first announced  Jetpack Compose . Jetpack Compose is Google’s response to the declarative UI framework trend, which the Android team is developing to fundamentally change the way developers create UI, making it easier and faster to write, and more performant to run. It is a part of the Jetpack suite of libraries and as such should provide compatibility throughout platform versions, removing the need to avoid certain features, because you’re targeting lower-end devices or older versions of Android. Although it’s still in an alpha , Compose is already making big waves in the Android community. If you want to stay up-to-date on the latest and greatest technology, read on! In this tutor...

Loops in Dart 💪💪💪😎😎😎

       Loops in Dart   💪💪💪😎😎😎 Dart Loops In Programming, loops are used to repeat a block of code until certain conditions are not completed. For, e.g., if you want to print your name 100 times, then rather than typing print(“your name”); 100 times, you can use a loop. There are different types of loop in Dart. They are: For Loop For Each Loop While Loop Do While Loop Info Note : The primary purpose of all loops is to repeat a block of code. Print Your Name 10 Times Without Using Loop Let’s first print the name 10 times without using a loop. void main() { print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); } Show Output ...

MVVM architecture, ViewModel and LiveData (Part 1)

  MVVM architecture, ViewModel and LiveData (Part 1) During Google I/O, Google introduced  architecture components  which includes  LiveData  and  ViewModel  which facilitates developing Android app using MVVM pattern. This article discusses how can these components serve an android app that follows MVVM. Quick Definition of MVVM If you are familiar with MVVM, you can skip this section completely. MVVM is one of the architectural patterns which enhances separation of concerns, it allows separating the user interface logic from the business (or the back-end) logic. Its target (with other MVC patterns goal) is to achieve the following principle  “Keeping UI code simple and free of app logic in order to make it easier to manage” . MVVM has mainly the following layers: Model Model represents the data and business logic of the app. One of the recommended implementation strategies of this layer, is to expose its data through observables to be decoupled ...