×

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

Soundness in Dart

What is soundness? Soundness ensures that the program never comes across any invalid state that may lead to abrupt termination of the program. As its name suggests it ensures perfect type...

4 minutes read.

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 Switch Case Statement

In the case of if-else statements, we prefer not to use the if-else ladder when there are many test conditions to be evaluated. In such a situation, it is preferable...

4 minutes read.

Typedef in Dart

In Dart, typedef is used to generate a function type that we can use as a type annotation for declaring variables and return types of the function type. An alias...

4 minutes read.

Metadata in Dart

Metadata is often referred to as the data about the data. It is a  piece of data about a basic piece of data. In the case of a Dart program,...

2 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 Assignment Operator

Assignment operators are the operators that assign value to the variables. The value on the right-hand side is assigned to the variable on the left-hand side. We can also use...

4 minutes read.

Dart Object-Oriented Concepts

Dart is a programming language that supports object-oriented programming. It is focused on the objects that are real-world entities and supports all the concepts of OOPS, such as objects, classes,...

4 minutes read.

Dart Built-in Data Types

A data type defines the type of value a variable can hold, such as integer, double, or string.  Dart supports two data types:  1. Built-in data types : These are the data...

1 minute read.

Dart If-else-if statement

If - else - if statement enables to check the set of test expressions that evaluate to Boolean True or False, and based on this true or false the particular...

2 minutes read.

Abstract Classes in Dart

Abstract classes in Dart are those classes that only contain abstract methods  (methods that do not contain any implementation). These classes are specifically designed for the purpose of inheritance. We...

4 minutes read.

C++ vs Dart

Difference between C++ and Dart C++ is an object-oriented programming language developed in 1980 by Bjarne Stroustrup. It has wide real-world applications with various in-built functions and a very vast library...

1 minute read.

Dart Objects

Apart from the built-in data types, Dart offers some other data types that have a special role to play. One of them is Objects.  Objects Objects are the foundation of the...

3 minutes read.

Dart - Control Flow Statements

The control flow statements are used to define the control on the flow of the program. Dart programs are executed in sequential order i.e., the order in which the programming...

1 minute read.

Dart Classes

Dart is an object – oriented programming language that supports all the object-oriented programming concepts such as classes, objects, inheritance, data abstraction and data encapsulation. A class can be defined as...

8 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 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 Type Test Operators

Type Test Operators in Dart These operators are used to check the types of expressions at runtime. Dart is a typed language, and we often want to assert that a value...

1 minute read.

Dart Installation Guide

There are various ways of compiling and running an application created in Dart, either by compiling the Dart code to JavaScript using the Dart2js tool or by running on the...

3 minutes read.

Dart Important Concepts

1. Anything placed in a variable is an object, and an object is an instance of a class. Numbers, functions, and null are all objects in Dart, and all these...

3 minutes read.