×

Builder Classes in Dart

Before understanding builder classes, let us understand about Flutter that makes the best use of the builder classes. Flutter is actually not a programming language, it is a software development kit (SDK) that has some in-built macros, customizable and read-to-use widgets as well as libraries and tools that can be deployed while creating cross-platform mobile applications.

In Flutter, to create a new widget we use a ' build ' widget associated with that particular widget and the framework passes the BuildContext parameter to it.

' Build ' Widget ( BuildContext context ) :

In Flutter, other than the build widget there isn't any other widget that needs the context parameter in their constructors or functions. Therefore, the context parameter has to be passed through the build widget only, otherwise there will be more than one call to the build function. To accomplish this, we make use of the ' Builder ' class that creates the child and returns it. This Builder class passes a comtext to the child. This child acts as a custom build function.

Builder class constructor :

Builder( { key key, @required WidgetBuilder builder } ) // 

this creates a widget that delegates its build to a callback.

It is mandatory to not keep the argument null.

Builder class Methods

The various methods associated with the builder class are :

  1. build( BuildContext context ) -> Widget
  2. createElement( ) -> StatelessElement
  3. debugDescribeChildren( ) -> List< DiagnosticsNode >
  4. debugFillProperties( DiagnosticPropertiesBuilder properties ) -> void
  5. noSuchMethod( Invocation invocation ) -> dynamic
  6. toString( { DiagnosticLevel minLevel : DiagnosticLevel.info } ) -> String
  7. toStringDeep( { String prefixLineOne = '', String? prefixOtherLines, DiagnosticLevel minLevel = DiagnosticLevel.debug } ) -> String
  8. toStringShallow( { String joiner = ', ', DiagnosticLevel minLevel = DiagnosticLevel.debug } ) -> String
  9. toStringShort( ) -> String

Let us consider the following example in Dart that explains the concept of the Builder class. To increase the understandability of this concept, we will be making a simple mobile application. This will app will only have a main page containing scaffold with an AppBar and a button which when tapped display a message.

Example :

import ' package:flutter/material.dart ' ;
void main( ) 
{
  runApp( MyApp( ) ) ;
}
class MyApp extends StatelessWidget 
{
// This widget is the root of your application.
  @override
  Widget build( BuildContext context ) 
{
    return MaterialApp (
      title : ' Builder App Demo ' ,
      debugShowCheckedModeBanner : false ,
      theme: ThemeData (
        primarySwatch : Colors.green ,
      ) ,
      home : Home( ) ,
    ) ;
  }
}
class Home extends StatelessWidget 
{
  @override
  Widget build( BuildContext context ) 
{
    return Scaffold (
      // appbar
      appBar : AppBar (
        title : Text( ' Assert Tutorial ' ) ,
      ) ,
      // detect gesture
      body : Center (
        child : GestureDetector (
          onTap : ( ) {
            Scaffold.of( context ).showSnackBar (
              new SnackBar (
                content : new Text( ' This is an assert Tutorial ' ) ,
              ) ,
            ) ;
          } ,
          // box styling
          Child : Container (
            margin : EdgeInsets.all( 18 ) ,
            height : 40 ,
            decoration : BoxDecoration (
              color : Colors.blueAccent ,
              borderRadius : BorderRadius.circular( 8 ) ,
            ) ,
            child : Center (
              child : Text (
                ' CLICK HERE ' ,
                style :
                TextStyle( fontWeight : FontWeight.bold, color : Colors.white ) ,
              ) ,
            ) ,
          ) ,
        ) ,
      ) ,
    ) ;
  }
}

Output :

However, this code resulted in an error because the same context is being passed to the Scaffold and the SnackBar widget. The content being passed as a parameter to the Scaffold does not actually belong to it. So, the app gives the following error.

======== Exception caught by gesture ===============================================================
The following assertion was thrown while handling a gesture:
Scaffold.of() called with a context that does not contain a Scaffold.
No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). This usually happens when the context provided is from the same StatefulWidget as that whose build function actually creates the Scaffold widget being sought.

However, on tapping the button ‘ CLICK HERE ’ the following output is being displayed :

On tapping the button one time, following output was displayed :

Handler: "onTap"
Recognizer: TapGestureRecognizer#3ed06
debugOwner: GestureDetector
state: possible
won arena
finalPosition: Offset(826.4, 387.2)
finalLocalPosition: Offset(826.4, 38.4)
button: 1
sent tap down
====================================================================================================

We have tried to resolve the error of the above code in the following program. Consider another example :

import ' package:flutter/material.dart ' ;
void main( ) {
  runApp( MyApp( ) ) ;
}
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build( BuildContext context ) {
    return MaterialApp (
      title : ' Builder Demo ' ,
      debugShowCheckedModeBanner : false ,
      theme : ThemeData (
        primarySwatch : Colors.green ,
      ) ,
      home : Home( ) ,
    ) ;
  }
}
class Home extends StatelessWidget {
  @override
  Widget build( BuildContext context ) {
    return Scaffold (
      // appbar
      appBar : AppBar (
        title : Text( ' Assert Statement ' ) ,
      ) ,
      // detect gesture
      body : Center (
        child : Builder ( builder : ( BuildContext context ) {
          return GestureDetector (
            onTap : ( ) {
              Scaffold.of( context ).showSnackBar (
                new SnackBar (
                  content : new Text( ' This is the Dart Tutorial ' ) ,
                ) ,
              ) ;
            } ,
            child : Container (
              margin: EdgeInsets.all( 18 ) ,
              height : 40 ,
              decoration : BoxDecoration (
                color : Colors.blueGrey ,
                borderRadius : BorderRadius.circular( 8 ) ,
              ) ,
              child : Center (
                child : Text (
                  ' CLICK ME ' ,
                  style : TextStyle (
                      fontWeight : FontWeight.bold, color : Colors.white ) ,
                ) ,
              ) ,
            ) ,
          ) ;
        } ) ,
      ) ,
    ) ;
  } }

Output on Console :

Launching lib\main.dart on Edge in debug mode...
Waiting for connection from debug service on Edge...
This app is linked to the debug service: ws://127.0.0.1:58278/aWUVHjHPR3o=/ws
Debug service listening on ws://127.0.0.1:58278/aWUVHjHPR3o=/ws
 Running with sound null safety 
Debug service listening on ws://127.0.0.1:58278/aWUVHjHPR3o=/ws

Output on the simulator web app:

Builder Classes in Dart

Some of its properties are :

  1. Builder -> WidgetBuilder // called to obtain the child widget
  2. hashCode -> int // obtains the hash code for the object it is invoked for
  3. key -> Key? // controls the replacing of one widget by the other
  4. runtimeType -> Type // represents the object of the runtime type

Related Topics

Dart Packages

Every programming language has some in-built functions stored inside the header files that makes the task much easier for the programmer. The Dart Packages refer to the compilation of a...

4 minutes read.

Dart Arithmetic Operators

Arithmetic Operators comprises of all the operators that are used to perform arithmetic operations such as addition, subtraction, multiplication, division, etc. They are binary operators that work upon two operands. Consider A...

2 minutes read.

Dart Recursion

Recursion is one of the most important and interesting concepts in any programming language. It can be defined as a process in which a function calls itself directly or indirectly....

5 minutes read.

Dart Equality and Relational Operators

Dart provides the functionality of checking the relationship between the values or values within the variables. These operators return the resultant value as Boolean, i.e., either ‘true’ or ‘false’. Some important points...

3 minutes read.

Dart lists data type

The most important data type in any programming language is an ordered list of elements, an array. Dart lists resemble JavaScript array lists. Example,               var...

7 minutes read.

Dart Isolates

Dart successfully supports asynchronous programming which runs our program without any hindrance. This asynchronous programming is used to achieve concurrency. Dart supports concurrent programming with features such as ‘ async-await...

9 minutes read.

Dart Bitwise and Shift Operators

The Bitwise operators are the operators that perform different operations bit by bit on the value of the two operands. List of Bitwise Operators in Dart Sr. Operators Description 1. & ( Binary AND ) It returns...

2 minutes read.

Dart Variables

Variables are used to store the value of a particular data type referred to in the whole program by a name or identifier. They refer to a memory location as...

5 minutes read.

Assert in DART

In any programming language, resolving error is the most unwanted and tedious task. At times it becomes very difficult to find the error in the large code. Dart offers an...

3 minutes read.

Dart URIs

The Uri class supports encoding and decoding of strings with the help of functions to be used in URIs ( which may also be known as URLs ). These functions...

6 minutes read.

Dart Single-Page Application Architecture

In a single page application architecture, the source code for a single web page loads the entire application. The responsibility of building the user interface and requesting data from the...

2 minutes read.

Dart Syntax

In the previous tutorial, we coded our first program in Dart on various platforms understanding the basic functionality of each line of code.  Let us understand the syntax for Dart language...

4 minutes read.

Rust vs Dart

Rust is a system-level programming language that stands next to C ++ in terms of syntax, but offers greater speed and memory security. Dart, on the other hand, is an...

2 minutes read.

Dart Types of Functions

Functions are the set of statements intended to perform a specific task. They accept some input from the user, perform the specified computation and generate the output. They are very...

4 minutes read.

Dart this Keyword

The ' this ' keyword, similar to that in Java and C#, refers to an object of the class using it. It points to the current object of the class,...

5 minutes read.

Dart HTML DOM

All web pages can be viewed as objects and exist within the browser window. We can access a web page using a web browser and it needs to be connected...

3 minutes read.

Dart Static Members

Static Members in Dart Static members are the members of the class declared using the 'static' keyword. the static members have the following characteristics :  All the objects of the class having...

3 minutes read.

Lexical Scope and Closure

Lexical Scope : Lexical scope is a very important term in any programming language. It defines the scope of the variable based on the block it is contained inside. According to...

2 minutes read.

Dart Strings

Strings data type in Dart A Dart string is a sequence of characters with an encoding of UTF-16. The text associated with string data type is enclosed withing single (‘  ’)...

3 minutes read.

Dart super keyword

The ' super ' keyword is used to refer to the immediate parent class object of the currently in-use child class. Using this keyword, we can invoke the superclass (...

6 minutes read.