Flutter Tutorial: How to use a TextField

 In this tutorial, we will learn how to use a TextField widget in Flutter Application using an example.

TextField is used to get text input from users. The default behavior of TextField is that, when you press on it, it gets focus, and a keyboard slides from the bottom of the screen. When you enter text using a keyboard, the string is displayed in the TextField.

Introduction to TextField

A TextField widget allows the collection of information from the user. The code for a basic TextField is as simple as:


This creates a basic TextField:


Retrieving information from a TextField

Since TextFields does not have an ID like in Android, text cannot be retrieved upon demand and must instead be stored in a variable on change or use a controller.

The easiest way to do this is to use the onChanged method and store the current value in a simple variable. Here is the sample code for it:

String value = "";
  onChanged: (text) {
    value = text;

2. The second way to do this is to use a TextEditingController. The controller is attached to TextField and lets us listen and control the text of TextField as well.

TextEditingController controller = TextEditingController();
  controller: controller,
The Main.dart

import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { TextEditingController nameController = TextEditingController(); String email = ''; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Flutter - Nityzeros.com'), ), body: Center(child: Column(children: <Widget>[ Container( margin: EdgeInsets.all(20), child: TextField( controller: nameController, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Email', ), onChanged: (text) { setState(() { email = text; //you can access nameController in its scope to get // the value of text entered as shown below //fullName = nameController.text; }); }, )), Container( margin: EdgeInsets.all(20), child: Text(email), ) ]))), ); } }

Dart Tutorial : Functions in Dart(Examples)

Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code.

A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.

Let’s see how functions work. This section is a basic introduction, and I will cover this topic more in-depth later when discussing methods in object-oriented programming.

Important Point:

Before writing a function, you need to remember these major points:

Define the type of a function. So, type annotation is recommended

Dart recommends type annotation, a function still works without any type declaration

Map<String, dynamic> arguments = {'John': 'Smith', 'Chicago': 42};

Alternatively, you can use var and let Dart infer the type:

var arguments = {'John': 'Smith', 'Chicago': 42}; // Map<String, Object>

the value you want to return from a function, you need to change the type of that function accordingly. If you want an integer value to return, for example, you should change the type of the function to an integer.

Simply put, for the void, nothing is returned from a function.

The Void() Function

So, whenever you use the keyword void before the function, you need to use print(object) to see what’s happening inside that function.

main(List<String> arguments){
  void ispossible(){
    print("It's possible.");
  void ispossible(){
    print("It's not possible.");

Let's see if the result differs if we avoid void()

main(List<String> arguments){
    print("It's true.");
    print("It's false.");

This gives us the same result because according to the type of the value, it is automatically inferred. Here Dart knows they, here the types, are void because we are not using any return statements.

So, type annotations do not matter in such cases, but for API building (we will cover this part at the end of this book), type annotation is necessary.

Calling Function within Function

Lets see how to call a function within another function with arguments.

main(List<String> arguments) {
  print("You reached @NintyZeros.com");
myAge(int age){
  print("My age is ${age}");

You reached in NintyZeros.com
My age is 12

Working with Return 

Lets see with an example how to use a return from a function.

void withoutReturningValue(){
  print("We cannot return any value from this function.");
int anIntegerReturnTypeFunction(){
  int num = 10;
  return num;
//using Fat Arrow
String stringReturnTypeFunction(String name, String address) => "This is $name and this is $address and we have used the Fat Arrow method.";
  var returningInteger = anIntegerReturnTypeFunction();
  print("We are returning an integer: $returningInteger");
  print(stringReturnTypeFunction("John", "Jericho Town"));

This should give a basic overview of how to work with a function in Dart. We will also see how to implement a basic object in Dart.

Dart Tutorial : Switch and Case Examples

In the previous post we are already looked into Conditional (If Else) and nested but, its not an efficient way to have a lot of nested if-else as it's cumbersome to understand.

In some cases, decision-making can be easier when you use a switch instead of if-else logic. switch statements in Dart compare integers, strings, or compile-time constants using the double equal sign (==) behind the scenes; it maintains the rule, though, that the compared objects must be instances of the same class and not of any of its subtypes. 

The General Syntax:

switch(variable_expression) { 
   case constant_expr1: { 
      // statements; 
   case constant_expr2: { 
   default: { 

The value of the variable_expression is tested against all cases in the switch. If the variable matches one of the cases, the corresponding code block is executed. If no case expression matches the value of the variable_expression, the code within the default block is associated.

The following rules apply to a switch statement −

  • There can be any number of case statements within a switch. 
  • The case statements can include only constants. 
  • It cannot be a variable or an expression. 
  • The data type of the variable_expression and the constant expression must match.
  • Unless you put a break after each block of code, the execution flows into the next block.
  • The case expression must be unique. The default block is optional.

The Example:

We are going to See a simple Example to implement a marking system using switch case.

void main() {
   var marks = "A";
   switch(marks) {
      case "A": {  print("Very Good"); }
      case "B": {  print("Good"); }
      case "C": {  print("Fair"); }
      case "D": {  print("Poor"); }
      default: { print("Fail"); }

The significance of break is that if the condition is met, the switch statement ends, and the program continues. We have used a default clause to execute the code when no case clause matches.

We have seen an alternative to the nested If else statement. The Switch cases are more easily readable and easy to understand as per the developer perspective.

Dart Tutorial: While and Do-while loops

In this part, we are learning about how to implement loops in the Dart language. In the previous post, we already looked at how to implement For and For-each loop

We are going to learn how to implement while and do-while loop in dart.

On a given Boolean condition, the while loop controls the flow and repeatedly executes the value. It loops through a block of code, as long as the specified condition is true.

The General Syntax:

Consider this simple example to understand the structure:

while (condition) {
  // code block to be executed

Here’s a simple example that prints out from 0 to 10

	int x = 0;
	while (x <= 10) {
  		print("The output: ${x}");

You can see the difference between the for and while loops.

Note: Be careful about handling the while loop. Since a while loop evaluates the condition before the loop, you must know how to stop the loop at the right time before it enters into infinity.


To understand more easily we are going to implement Factorial of number in Dart and that too using while loop.

main(List<String> arguments) {
  var num = 5;
  var factorial = 1;
  print("The value of the variable 'num' is decreasing this way:");
  while(num >=1) {
    factorial = factorial * num;
    print("'=>' ${num}");
  print("The factorial  is ${factorial}");

The while loop evaluates the condition. Since the value of the variable num is 5 and it is greater than or equal to 1, the condition is true. So, the loop begins. As the loop begins, we have also kept reducing the value of the variable num; otherwise, it would have entered into an infinite loop.

The value of the variable 'num' is decreasing this way:
'=>' 4
'=>' 3
'=>' 2
'=>' 1
'=>' 0
The factorial is 120

Do-While Loop in Dart

Lets try to implement the same code using a do-while loop

main(List<String> arguments) {
  var num = 5;
  var factorial = 1;
  do {
    factorial = factorial ∗ num;
    print("The value of the variable 'num' is decreasing to : ${num}");
    print("The factorial  is ${factorial}");
  while(num >=1);

We have slightly changed the code snippet so that it will show the reducing value of the variable, and at the same time, it will show you how the value of the factorial increases.

The value of the variable 'num' is decreasing to : 4
The factorial  is 5
The value of the variable 'num' is decreasing to : 3
The factorial  is 20
The value of the variable 'num' is decreasing to : 2
The factorial  is 60
The value of the variable 'num' is decreasing to : 1
The factorial  is 120
The value of the variable 'num' is decreasing to : 0
The factorial  is 120


we have seen the most popular loops in Dart. Once you understand the pattern of loops, you can easily choose between for, while, and do-while.

Dart Tutorial : For Loop in Dart

In computer programming, when we need to repeat a given section of code a certain number of times until a particular condition is met, we use a loop. This is a control structure that is repeated until a certain condition is met.

The for loop is an implementation of a definite loop. The for loop executes the code block a specified number of times. It can be used to iterate over a fixed set of values, such as an array.

The general syntax of the for loop looks like this:

for(var x = 0; x <= 10; x++){
  //iteration from 0 to 10 happens in between

In the previous code, the value of x starts at 0.

Then we test if the loop is going to execute (x <= 10;). 

If that expression returns true, the loop executes, and we carry out the last instruction in the for clause (x++), adding 1 to x. The for loop then tests to see whether it should run again; if it does, then x++ runs again too. This continues until x <= returns false. 

The for loop is necessary for iterating any collections of data. Here is a typical example of the for loop:

main(List<String> arguments) {
  var proverb = StringBuffer('As Dark as a Dungeon.');
  for(var x = 0; x <= 10; x++){

In the previous code, we used two built-in functions.

They are StringBuffer() and write(). We get these from Dart libraries.

The output is as follows:

As Dark as a Dungeon.!
As Dark as a Dungeon.!!
As Dark as a Dungeon.!!!
As Dark as a Dungeon.!!!!
As Dark as a Dungeon.!!!!!
As Dark as a Dungeon.!!!!!!
As Dark as a Dungeon.!!!!!!!
As Dark as a Dungeon.!!!!!!!!
As Dark as a Dungeon.!!!!!!!!!
As Dark as a Dungeon.!!!!!!!!!!
As Dark as a Dungeon.!!!!!!!!!!!

In our future discussions, we will use the for loop quite extensively, so currently, let’s stop here. 

You should understand the concept of why the exclamatory sign has increased from 0 to 10. 

It stops when a certain condition (here x=10) is met. 

I am now going to cover an interesting feature of iterating collections, namely, using Set and Map.

forEach() method

When the object you are going to iterate is Iterable, you can use the forEach() method. We are about to present two sets of collections; one is Set, and the other is Map.

main(List<String> arguments) {
  Set mySet = {1, 2, 3};
  var myProducts = {
    1 : 'TV',
    2 : 'Refrigerator',
    3 : mySet.lookup(2),
    4 : 'Tablet',
    5 : 'Computer'
  var userCollection = {"name": "John Smith", 'Email': 'john@sanjib.site'};
  myProducts.forEach((x, y) => print("${x} : ${y}"));
  userCollection.forEach((k,v) => print('${k}: ${v}'));

As you see in the previous code, there are two sets, myProducts and userCollection. 

In both sets, a key=>value pair is declared. In the first case, 1 is key, and TV is the value. 

Now, Dart has a built-in forEach(key:value) method that can be used to give the output. 

In the first instance, x is the key, and y represents the value. After that, we use string interpolation to give the output.

Here is the output:

//output of code 2.5
1 : TV
2 : Refrigerator
3 : 2
4 : Tablet
5 : Computer
name: John Smith
Email: john@sanjib.site


In this tutorial, we learnt how to implement looping in Dart using For and ForEach blocks and also tried a nested way to do it.

Dart Tutorials : If-Else Conditions in Dart

Controlling the flow of your code is important. Programmers want to control the logic of their code for many reasons; one of the main reasons is that the user of the software should have many options open to them.

You may not know the conditions beforehand, in which way your programming logic should move, though. 

You can only guess, so as a developer, you should open as many avenues for the user as possible. There are several techniques you can adopt to control the flow of the code. For example, the if-else logic is popular.

In this tutorial, you will learn about the Dart if else if Statement and its application with practical examples.

Dart if else if Statement

In Dart, if..else..if statement allows us to add an alternative set of test conditions in if..else statement using else-if and single else statements for if condition. 

In such way if..else..if statement is used to select one among several blocks of code to be executed.

Let’s look at a simple example of controlling the flow of the code. After that, we will delve deep into the logical consequences of this approach. 

An if can be followed by else if the Boolean statement tested by the if block comes out as false.

if(it is true){
The program executes
Else {
This block will not execute then
Let see a working Example on a sample If and Else block and nested if..else example.

void main()
    var a = 10;
  	var b = 10;
    print("NintyZero  - Dart Example if else if Statement");
    if(a > b){
    print("a is greater than b");
  	else if(a == b){
      print("a and b are equal");
    else {
    print("b is greater than a");

In this tutorial we learnt how to implement conditional blocks in Dart using If.Else blocks and also tried a nested way to do it.

Dart Tutorials: DataTypes in Dart

In this post, we will discuss some initial key concepts of Dart that are absolutely necessary for beginners. First, like Python, Dart is an object-oriented programming language. Everything is an object here.

You can try out all the examples using DARTPAD

Data Types

Data types are types of data that we can represent in a programming language, such as an integer is a nonfractional numerical value like 1, 2, and so on. Later when needed, we can also manipulate these values in our program.

For example, in a calculator we do lots of numerical operations such as additions, subtractions, etc. The default value of most data types is null. So, we need to mention what data type we are going to use.

Dart is statically typed, meaning that each variable in Dart has a type that must be known when you compile the code. The variable type cannot change when you run the program. C, Java, Swift and Kotlin are also statically typed.

This contrasts with languages like Python and JavaScript, which are dynamically typed. That means variables can hold different kinds of data when you run the program. You don’t need to know the type when you compile the code.

We use variables to reference those types that are actually stored in memory. Consider the following:

	int a = 1;

This means we first store the type of integer value 1 in our memory, and then we assign that value to the variable a In normal circumstances, in Dart, we mention what type we are going to use. If we use integers and strings, we write it like this:

int myAge = 12;
String myName = "John Smith";

In the previous examples, we have explicitly declared the type that should be used. In the next example, we do the same thing, but implicitly. Therefore, you can also write the same code in this way:

var myAge = 12;
var myName = "John Smith";

Built-in Types in Dart

The Dart language has special support for the following types, and you can always follow the strongly typed or duck typed pattern to initialize them:

  • Numbers 
  • Strings 
  • Booleans 
  • Lists (also known as arrays)
  • Sets 
  • Maps 
  • Runes (for expressing Unicode characters in a string) 
  • Symbols 

 Numbers(Int or double)

int and double types are subtypes of num. The num type includes basic operators such as +, -, /, and *; and they represent plus, minus, division, and multiplication, respectively. You can call them arithmetic operators.

In the below example we are going to see how to declare a num type and convert to string type

main() {
  int myNUmber = 542;
  double myDouble = 3.42;
  String numberToString = myNUmber.toString(); //allows you to convert int to string
  String doubleToString = myDouble.toString(); //allows you to convert double to string
  if ((numberToString == '542' && myNUmber.isEven) && (doubleToString == '3.42' && myDouble.isFinite)){
    print("Both have been converted from an even number ${myNUmber} and a finite double ${myDouble} to string. ");
  } else print("Number and double have not been converted to string.");

Understanding Strings

A Dart string is a sequence of UTF-16 code units. For absolute beginners, I’ll briefly describe UTF-8, UTF-16, and UTF-32. They all store Unicode but use different bytes.

Unicode support makes Dart more powerful, and you can create your mobile and web applications in any language. Let’s see one example where I have tried some Bengali script.

main(List<String> arguments) {
  String bengaliString = "বাংলা লেখা";
  String englishString = "This is some English text.";
  print("Here is some Bengali script - ${bengaliString} and some English script ${englishString}");

While handling strings, you should remember a few things. You can use both single quotes (“) and double quotes ("").

main(List<String> arguments) {
  String stringWithSingleQuote = 'I\'m a single quote';
  String stringWithDoubleQuote = "I'm a double quote.";
  print("Using delimiter in single quote - ${stringWithSingleQuote} and using delimiter in double quote - ${stringWithDoubleQuote}");

Booleans : To Be True or to Be False

You have already seen that Dart has a type called bool. The Boolean literals true and false have the type bool. They are compile-time constants.

Introduction to Collections: Arrays Are Lists in Dart

An array, or an ordered group of objects, is the most common collection in every programming language. In Dart, arrays are List objects . We will call them lists in our future discussions.

main(List<String> arguments) {
  List fruitCollection = ['Mango', 'Apple', 'Jack fruit'];

Introduction to Set 

In Dart, a Set is an unordered collection of unique items. There are small differences in syntax between List and Set. Let’s look at an example first to know more about the differences.

main(List<String> arguments) {
  var fruitCollection = {'Mango', 'Apple', 'Jack fruit'};

The Dynamic Keyword

 If you use the dynamic keyword instead of var, you get what’s effectively a dynamically typed variable:

dynamic numberOfKittens;

Here, you can set numberOfKittens to a String using quotes. You’ll learn more about the String type later in the tutorial.

numberOfKittens = 'There are no kittens!';

print(numberOfKittens); // There are no kittens!

numberOfKittens has a type, since Dart has static typing. But that type is dynamic, which means you can assign other values with other types to it. So you can assign an int value below your print statement.

numberOfKittens = 0;

print(numberOfKittens); // 0

Or, if you have a kitten in Schrödinger’s box, you could assign a double value:

numberOfKittens = 0.5;

print(numberOfKittens); // 0.5

We covered most of the topics in dart related to variables and datatype.You can try Out all the examples using the online console dartpad.

Dart Tutorials : How to write "Hello World" in Dart

At its heart, Dart is a conservative programming language. It was not designed to champion bold new ideas, but rather to create a predictable and stable programming environment. 

The language was created at Google in 2011, with the goal of unseating JavaScript as the language of the web.

JavaScript is a very flexible language, but its lack of a type system and misleadingly simple grammar can make projects very difficult to manage as they grow. 

Dart aimed to fix this by finding a halfway point between the dynamic nature of JavaScript and the class-based designs of Java and other object-oriented languages. 

The language uses a syntax that will be immediately familiar to any developer who already knows a C-style language.

Like all good programming books, we’re going to start with a program that prints “Hello, World” (kind of) to your console. In your favorite text editor, 

Create a new file in the hello_world directory called hello_world.dart. Write this code in the file:

void main() {
  print('Hello, Dart!');

Now, back in your terminal, you can execute Dart code with the CLI command dart. To follow along with these instructions, make sure you’re in the right project directory where your hello_world.dart file lives. Then, run the “Hello, Dart” example:

$ dart hello_world.dart
// => Hello, Dart!

If “Hello, Dart!” did in fact print, congrats!

You wrote your first Dart program, and you’re officially a Dart programmer!If “Hello, Dart!” did in fact print, congrats!

Let's understand how the Dart Works! 

The main function in Dart

All Dart functions look like this, but the main is special. It’s always the first code that’s executed in a Dart program. Your program must contain the main function that the Dart compiler can find.

The Void!

Notice the word void in the example. void is the return type of this function. If you haven’t used typed languages, this may look strange. 

The Print function!

Next in this example is the line that contains the print function:

print('Hello, Dart!');

print is a special function in Dart that prints text to the console.

On that same line, you have a String ('Hello, Dart!'), and you have a semicolon (;) at the end of the line. This is necessary at the end of every statement in Dart. That’s all you need to write a Dart program.

A simple way to add InputText in React Native

In this post, we are going to learn how to use text input within react native. The text input can be used for various purposes within an app. You might be looking to gather some input via forms type, looking to get card details for payment, or maybe just a password box for authentication.

We are going to learn some simple snippets to attain the same.

We are going to learn how to see how to implement the below features

Step 1: UseCase:

 A text input that accepts a string. 

This kind of text input will be needed when you are asking for an email/username from the User.

A text input that accepts only numeric and also how to enable numeric keypad by default.

These kinds of inputs are useful when we ask for a card number for payments/that a phone number as input

A password-based field that can mask the input.

These fields are mostly used when we expect a password as input or masking is needed.

Below is the demo : 


Step 2: Imorting the compoenent

Let's add a textbox or text input in react-native we need to first import the component. We can do this as follows:

import { Text, TextInput, View ,SafeAreaView} from "react-native";

Step 3: Adding the Component (TextInput)

We are going to add the text input component as :


The Final Code: This is how the App.Js looks after along with the styles

import React, { useState } from "react";
import PropTypes from "prop-types";
import { Text, TextInput, View ,SafeAreaView} from "react-native";
import { StyleSheet } from "react-native";

const UselessTextInput = () => {
  const [text, onChangeText] = React.useState("Useless Text");
  const [number, onChangeNumber] = React.useState(null);
  const [onChangePassword] = React.useState(null);

  return (
      <Text style={styles.text}> Prefilled Field</Text>
      <Text style={styles.text}> Numeric Field</Text>
        placeholder="useless placeholder"
      <Text style={styles.text}> Passsword Field</Text>
        placeholder="Password text"
        secureTextEntry = {true}

const styles = StyleSheet.create({
  input: {
    height: 40,
    margin: 12,
    borderWidth: 0.5,
    padding: 10,

export default UselessTextInput;

Conclusion: This was a simple way to work with text input in react native.We are goging to look for how to add this to a form or other UI. If you are looking to learn more about react native, Please check the other tutorials below.