What is the Difference Between Functions and Classes to Create Reusable Widgets?

· 6 min read
What is the difference between functions and classes to create reusable widgets
What is the difference between functions and classes to create reusable widgets

Flutter provides a set of built-in widgets to apply different effects to mobile applications. So, in this article, we will see What is the Difference Between Functions and Classes to Create Reusable Widgets.

Let’s get into it.

What is the Difference Between Functions and Classes to Create Reusable Widgets?

Important Difference:

It is mainly used for public widgets and can be reused. Private functions that are used only once are not important. Although it is good to understand this behavior.

There is an important difference between using functions instead of classes. That is, the framework does not know the function but can see the class.

Consider the following “widget” function:

Widget functionWidget({ Widget child}) {
  return Container(child: child);
}

You can also build it below way:

functionWidget(
  child: functionWidget(),
)

And it’s class equivalent:

class ClassWidget extends StatelessWidget {
  final Widget child;

  const ClassWidget({Key key, this.child}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: child,
    );
  }
}

Used like that:

ClassWidget(
  child: new ClassWidget(),
);

In the case of functions, the generated widget tree looks like this:

Container
  Container

While with classes, the widget tree is:

ClassWidget
  Container
    ClassWidget
      Container

This is important because it changes how the framework behaves when updating a widget.

Why does that matter?

By using functions to split your widget tree into multiple widgets, you expose yourself to bugs and miss on some performance optimizations.

There is no guarantee that you will have bugs by using functions. But by using classes, you can make sure that you will not encounter these problems.

Here are a few interactive examples on Dartpad that you can run yourself to better understand the issues:

Here’s a curated list of the differences between using functions and classes:

Classes:

  • allow performance optimization const constructor, more granular rebuild
  • ensure that switching between two different layouts correctly disposes of the resources (functions may reuse some previous state) ‎
  • ensures that hot-reload works properly using functions that could break hot-reload for showDialogs & similar.
  • are integrated into the widget inspector
  • we see ClassWidget in the widget-tree showed by the devtool, which helps to understand what is on screen.
  • we can override debugFillProperties to print what the parameters passed to a widget are.

Better Error Messages:

  • If an exception happens like ProviderNotFound, the framework will give you the name of the current building widget.
  • If you’ve split your widget tree only in functions + Builder, your errors won’t have a helpful name.
  • Can define keys
  • Can use the context API
  • Functions:
  • Have less code that can be solved using code-generation functional_widget

For Flutter Framework

Dart supports both procedural and oop. But, the flutter framework completely builds by using classes(oop). Because a large manageable framework cannot create using procedural.

  • Here create a list of reasons they use classes instead of functions for making widgets.
  • Most of the time build method (child widget) calls the number of synchronous and asynchronous functions.
  • So the build() method needs to keep in the separate class widget. Because all other methods called by the build() method can keep in one class.
  • Using widget class you can create a number of other classes without writing the same code again and again.
  • And also using inheritance(extend) and polymorphism (override) you can create your own custom class.

In the below example, let’s customize (Override) the animation by extending MaterialPageRoute (because it’s the default transition we want to customize).

class MyCustomRoute<T> extends MaterialPageRoute<T> {
  MyCustomRoute({ WidgetBuilder builder, RouteSettings settings })
      : super(builder: builder, settings: settings);

  @override                                      //Customize transition
  Widget buildTransitions(BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
      Widget child) {
    if (settings.isInitialRoute)
      return child;
    // Fades between routes. (If you don't want any animation, 
    // just return child.)
    return new FadeTransition(opacity: animation, child: child);
  }
}

Functions cannot add conditions for their parameters. But using the class widget’s constructor you can do like below:

const Scaffold({
    Key key,
    this.bottomNavigationBar,
    this.bottomSheet,
    this.backgroundColor,
    this.resizeToAvoidBottomPadding,
    this.resizeToAvoidBottomInset,
    this.primary = true,
    this.drawerDragStartBehavior = DragStartBehavior.start,
    this.extendBody = false,
    this.extendBodyBehindAppBar = false,
    this.drawerScrimColor,
    this.drawerEdgeDragWidth,
  }) : assert(primary != null),
       assert(extendBody != null),
       assert(extendBodyBehindAppBar != null),
       assert(drawerDragStartBehavior != null),
       super(key: key);

Functions cannot use const. Class Widget can use the const for their constructors (that affect the performance of the main thread).

You can create any number of independent widgets using the same class instances of a class/object. But function cannot create independent widgets instance, but reusing can.

Conclusion:

Thanks for walking with us on a Flutter Journey !!!

Keep Learning !!! Keep Fluttering !!!

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology. Daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply