WeCanCode https://wecancode.in/ A great place to start learning mobile development. Learn all the required skill you need to build a production ready app from the experienced developer and instructor Fri, 16 Feb 2024 10:08:43 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://wecancode.in/wp-content/uploads/2025/09/cropped-favicon-512x512-1-32x32.png WeCanCode https://wecancode.in/ 32 32 Keys in Flutter https://wecancode.in/keys-in-flutter/ Fri, 16 Feb 2024 10:08:36 +0000 https://mobileacademy.io/?p=945 A Key in Flutter is an identifier for a widget that helps Flutter understand its relationship to other widgets in the widget tree. It also identifies Widgets, Elements, and SemanticsNodes. It plays a key role in determining how widgets are updated and managed when the UI changes. When a widget is rebuilt, its key determines [...]

The post Keys in Flutter appeared first on WeCanCode.

]]>
A Key in Flutter is an identifier for a widget that helps Flutter understand its relationship to other widgets in the widget tree. It also identifies Widgets, Elements, and SemanticsNodes. It plays a key role in determining how widgets are updated and managed when the UI changes. When a widget is rebuilt, its key determines whether the new widget should be used to update an existing element in the widget tree. This means that if the key of the new widget matches the key of the current widget associated with an element, Flutter will update that element with the new widget. Otherwise, it will create a new element for the new widget. This mechanism is vital for maintaining the state and identity of widgets, especially in dynamic lists or complex interfaces where the structure of the widget tree changes frequently. Using keys, developers can ensure that the framework accurately tracks and updates widgets, leading to more predictable and efficient UI behavior.

In Flutter, the Widget class includes a constructor that can take a Key as an

optional parameter. Here is an example

In Flutter, several types of keys exist and they are mainly categorized into Local and Global Key.

Standard LocalKeys:

  • ValueKey: This key uses a stable value, such as a string or an integer, to uniquely identify a widget within its parent. It’s efficient and well-suited for lists, grids, or widgets with a unique identifier.
  • ObjectKey: This key relies on object reference equality to uniquely identify a widget. It’s suitable for situations where the object instance itself remains the same even if its properties change.
  • UniqueKey: While commonly used, it’s not technically a LocalKey because it generates a globally unique identifier every time it’s created. However, it can be used within a specific parent context to achieve uniqueness within that scope.

Standard GlobalKeys:

  • GlobalKey: This key provides a unique identifier across your entire app. This means you can access and manipulate a widget from anywhere in the widget tree, regardless of their location.

UniqueKey

A UniqueKey is a special type of Key that guarantees uniqueness within your entire app. This means no two UniqueKey instances will ever be the same. It’s essentially a random identifier generated Automatically when you create a new UniqueKey object.

It’s most commonly used when you need to uniquely identify widgets that are dynamically added, removed, or reordered within your UI.

ValueKey

A ValueKey is a type of Key in Flutter that uses a value to uniquely identify a widget. Unlike UniqueKey, which generates random identifiers, ValueKey relies on the provided value for uniqueness.

When you have a stable, unique identifier for your widget that does not change over time. For example:

  • Database IDs
  • User IDs

ObjectKey

ObjectKey is another type of key you can use to uniquely identify widgets. This key suits complex data structures where the widget’s identity is tied to the object’s identity. For eg. You have a widget whose properties change over time, but you want to treat it as the same widget for state management purposes. Think of a shopping cart item whose quantity changes, but it remains the same item.

Here is an example

In this example, each UserCard has an ObjectKey based on the specific User object instance. Even if the user’s age changes, the widget maintains its state (e.g., item selection) because it recognizes the object hasn’t truly changed.

GlobalKey

A GlobalKey is a powerful but sometimes tricky tool for accessing widgets throughout your app’s widget tree. It is unique across your entire app, unlike UniqueKey or ValueKey which are scoped within their parent widget trees. It enables you to directly access the state and properties of a widget from anywhere in your code, regardless of its location in the widget tree.

A practical use case is a form widget where you want to access its state from a different part of your app to perform actions like validation or data submission.

Here is an example

Do you know why do we use a GlobalKey in Form? A simple answer would be to access the Form currentState and validate.

PageStorageKey

PageStorageKey plays a crucial role in preserving widget state across navigation changes. It enables widgets within app pages to store and restore their state when the user navigates back and forth between them. For example, in Flutter it helps to preserve the scroll position of scrollable widgets. This means that when you have a scrollable widget like a ListView, and you leave the page and return back to it, the ListView will scroll back to the position where it was left.

PageStorageKey uses the PageStorage, which finds the nearest PageStorage ancestor from the widget tree and accedes storage to that widget. The PageStorage is usually introduced automatically via the MaterialPage or CupertinoPage.

Become a Job Ready Flutter developer

https://mobileacademy.io/courses/

The post Keys in Flutter appeared first on WeCanCode.

]]>
How Flutter Renders Widgets https://wecancode.in/how-flutter-renders-widgets/ Fri, 09 Feb 2024 11:02:00 +0000 https://mobileacademy.io/?p=931 How Flutter Renders Widgets? is one of the key questions to prepare for the Flutter interview. Let us try to understand the basic concept of rendering widgets Widget In Flutter, widgets are the fundamental building blocks you use to construct your app’s user interface. They are immutable descriptions of what parts of your UI should [...]

The post How Flutter Renders Widgets appeared first on WeCanCode.

]]>
How Flutter Renders Widgets? is one of the key questions to prepare for the Flutter interview. Let us try to understand the basic concept of rendering widgets

Widget

In Flutter, widgets are the fundamental building blocks you use to construct your app’s user interface. They are immutable descriptions of what parts of your UI should look like and how they should behave. Think of them as the Lego bricks or building blocks of your app’s design.

Element

An element in Flutter represents a specific instance of a widget at a particular location in the widget tree. Unlike widgets which are just blueprints, elements are the actual implementations of those blueprints in the running app. They hold additional information like the state of the widget and its location in the tree.

Render Objects

Render objects play a crucial role in taking the declarative descriptions of widgets (defined in the widget tree) and translating them into actual pixels on the screen. They handle the layout, painting, and interaction of UI elements. Unlike widgets which you interact with directly in your code, render objects operate quietly in the background, responsible for the actual rendering of your UI. Each widget in the widget tree has a corresponding render object in the render object tree. This render object takes the information from the widget (size, color, positioning) and uses it to draw the element on the screen.

Flutter utilizes three distinct trees to manage its rendering process:

Widget Tree: This is the tree you directly interact with as a developer. It represents the declarative structure of your app’s UI, composed of widgets that define how elements look and behave. Imagine the Widget Tree as a blueprint for your app’s interface.

widget tree

Element Tree: For each widget that you create in Widget Tree, the Flutter framework will create an element into Element Tree using the createElement() method. This tree acts as a bridge between the Widget Tree and the RenderObject Tree. It mirrors the Widget Tree but holds additional information like the state of each widget and its corresponding location in the UI hierarchy. Think of the Element Tree as a dynamic representation of the Widget Tree, reflecting any changes made to the widgets.

element tree

RenderObject Tree: This tree is responsible for the actual rendering of the UI on the screen. It translates the information from the Element Tree into instructions for the underlying graphics system. For each element in the Element Tree, the Flutter framework creates a RenderObject using the createRenderObject() method on a Widget. RenderObjects store basic details of widgets like child position, basic layout, paint protocols, etc.

render object tree

These three trees work together seamlessly to ensure an efficient and performant rendering process. When you make changes to your UI code, Flutter only updates the necessary parts of these trees, minimizing the amount of work required to reflect the changes on the screen.

TreePurposeKey Characteristics
Widget TreeDefines UI structureDeclarative, reflects desired UI state
Element TreeRepresents widget instancesDynamic, reflects actual UI state
RenderObject TreeHandles UI renderingTranslates UI elements into instructions for the graphics system

Understanding these three trees is crucial for writing efficient and performant Flutter apps. By knowing how they interact, you can make informed decisions about your UI structure and code optimization strategies.

Become a Job Ready Flutter developer

https://mobileacademy.io/courses/

The post How Flutter Renders Widgets appeared first on WeCanCode.

]]>
Memory Leak In Dart/Flutter https://wecancode.in/memory-leak-in-dart-flutter/ https://wecancode.in/memory-leak-in-dart-flutter/#comments Thu, 25 Jan 2024 04:56:17 +0000 https://mobileacademy.io/?p=908 In the previous article we learned about Dart Memory Management and now let us learn about the Memory Leak In Dart/Flutter. Flutter uses three types of languages When it comes to the memory used by Flutter, it refers to the sum memory of the three layers and it’s a virtual memory that is assigned to [...]

The post Memory Leak In Dart/Flutter appeared first on WeCanCode.

]]>
In the previous article we learned about Dart Memory Management and now let us learn about the Memory Leak In Dart/Flutter.

Flutter uses three types of languages

  1. The framework layer is written in Dart for application layer development.
  2. The engine layer is written in C/C++ and used for graphics rendering.
  3. The embedder layer is written in the embedding layer languages. For example, iOS uses Objective-C/swift, while Android uses Java/Kotlin.

When it comes to the memory used by Flutter, it refers to the sum memory of the three layers and it’s a virtual memory that is assigned to app, it does not have to do anything with Physical memory in your device.

dart/flutter memory

What is a Memory Leak?

In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released.

Source Wikipedia

Memory leaks happen in Dart?

As we saw previously in Dart Memory Management are done automatically using a Garbage collector but it cannot prevent all types of Memory Leak In Dart/Flutter, and developers still need to watch objects that can lead to memory leak.

How do memory leaks occur?

Memory Leak In Dart/Flutter can happen when an object is still being referenced in (heap) memory but is no longer being used. Some common cause is the presence of unused objects that remain in memory due to caching, improper use on BuildContext or failure to remove listeners when they are no longer needed.

Why can’t the garbage collector prevent all leaks?

While the garbage collector takes care of all unreachable objects, it’s the responsibility of the application to ensure that unneeded objects are no longer reachable (referenced from the root object).

So, if non needed objects are left referenced (in a global or static variable, or as a field of a long-living object), the garbage collector can’t recognize them, the memory allocation grows progressively, and the app eventually crashes with an out-of-memory error.

here is an example

In the above example we have a Timer callback but we have no way to cancel the timer once the task is completed, Timer will hang around in memory unless we cancel it, which can lead to Memory Leak.

In the above example we are passing leak object to LeakScreen(leak: leak) since we are constructing a Leak object in RowWidget class, as long as the root object has a reference to RowWidget Leak object can’t be GC which can lead to Memory Leak, we need to make sure that RowWidget is properly disposed once it’s not required.

How to Fix a above code?

Here is the example

In the above class we have added a dispose() to clean all the unwanted resource allocation

In the above example we have move the Leak class from constructor to state class and initialized it in initState method and properly dispose it in dispose method, in this way Leak object is ready for GC as soon as we dispose the LeakScreen

Here is an another example

In the example above, _MyWidgetState subscribes to someStream in its initState method. However, it does not unsubscribe from the stream when the widget is disposed. This could cause a memory leak if someStream continues to produce data even after MyWidget has been removed from the widget tree.

How to fix the above code?

In the above example we have added a dispose method in which we have cancel the Stream subscription.

How to prevent a Memory Leak in Flutter?

Here are some of the point that you can follow to prevent a Memory leak in Flutter:

  • Proper Disposal of Objects: Always dispose of objects when they are no longer needed by utilizing the disposal method in the Stateful Widget. This ensures that any associated resources are released and prevents unnecessary memory consumption.
  • Manage Streams Properly: When subscribing to a Stream, make sure to unsubscribe (cancel the subscription) when you’re done using it. This is particularly important in the case of StatefulWidgets, where you commonly subscribe in initState() and should unsubscribe in dispose().
  • Avoid Long-Lived Global Keys: If you use a GlobalKey and it’s referenced globally, this could lead to memory leaks. Instead, consider using other types of keys like LocalKey or ValueKey, or pass the context as a parameter.
  • Manage Controllers: If you’ve created any controllers (like TextEditingController, AnimationController, etc.), they should be disposed of when the widgets using them are disposed to prevent memory leaks.
  • Avoid Persisting BuildContext: Don’t persist the BuildContext in a long-lifetime object or class. The context should exist during the widget’s lifecycle and should be discarded when the widget is disposed.
  • Resolve Callbacks: If you’ve attached callbacks to a widget like Timer.periodic, and that widget gets disposed, the callback may still hang around in memory. If the callback references other objects, those will also be retained. Be sure to nullify your callbacks where appropriate.


Memory leak vs memory bloat

In a Memory leak, an application progressively uses memory, for example, by repeatedly creating a listener, but not disposing it.

Memory bloat uses more memory than is necessary for optimal performance, for example, by using overly large images or keeping streams open through their lifetime.

Both leaks and bloats, when large, cause an application to crash with an out-of-memory error. However, leaks are more likely to cause memory issues, because even a small leak, if repeated many times, leads to a crash.

Become a Job Ready Flutter developer

https://mobileacademy.io/courses/

The post Memory Leak In Dart/Flutter appeared first on WeCanCode.

]]>
https://wecancode.in/memory-leak-in-dart-flutter/feed/ 2
Introduction To Dart Memory Management https://wecancode.in/introduction-to-dart-memory-management/ https://wecancode.in/introduction-to-dart-memory-management/#comments Fri, 19 Jan 2024 10:52:41 +0000 https://mobileacademy.io/?p=877 Introduction To Dart Memory Management. In the previous post we learned about Dart Virtual Machine and Garbage Collection and in this post let us understand the basic concept on Memory Management in Dart / Flutter. To build any performant app it is crucial to understand how Memory are managed inside you app, it will help [...]

The post Introduction To Dart Memory Management appeared first on WeCanCode.

]]>
Introduction To Dart Memory Management. In the previous post we learned about Dart Virtual Machine and Garbage Collection and in this post let us understand the basic concept on Memory Management in Dart / Flutter. To build any performant app it is crucial to understand how Memory are managed inside you app, it will help you to optimize your app performance.

Introduction To Dart Memory Management

As we have learned in our previous post Introduction to Garbage Collection, Dart automatically manage memory for use using Garbage Collection, unlike other programming C, C++ where the developer have to manage memory allocate or deallocate manually. Even though Dart automatically manages the Memory it is crucial to understand how it works to build a efficient and performative app failing to do so can lead to a Memory Leak in your are app which in return can will lead to slow and buggy app.

How Dart Allocates Memory

Dart objects created using a class constructor (for example, by using MyClass()) live in a portion of memory called the heap. The memory in the heap is managed by the Dart VM (virtual machine). The Dart VM allocates memory for the object at the moment of the object creation, and releases (or deallocates) the memory when the object is no longer used

Here’s a simple example:

Object Types

Disposable object

A disposable object refers to an object that implements the Disposable pattern or a similar mechanism in order to release any resources it holds, such as file handles, network connections, database connections etc.

The purpose of the disposable pattern is to ensure that resources are properly released and not held indefinitely, preventing resource leaks which can cause a memory leak.

In Dart / Flutter, the disposable pattern is typically implemented by defining a dispose() method on the object. When you are done using the object and want to release its resources, you explicitly call the dispose() method.

Here’s an example of a disposable object in Dart:

abstract class Disposable { 
  void dispose(); 
} 
class MyDisposableObject implements Disposable { 
  // ... implementation of the object 
  @override void dispose() { 
    // Release any resources held by the object // ... 
  } 
} 
// Usage: 
void main() {
  MyDisposableObject myObject = MyDisposableObject(); 
  // Use the object... 
  // Dispose of the object when it is no longer needed 
  myObject.dispose(); 
}

Here is also a dart package that we can use to implement Disposable.
w_common | Dart Package

Memory-risky object

A memory-risky object refers to an object that can potentially consume a significant amount of memory or cause memory-related issues in a program if not managed properly.

Root Object

Every Dart application creates a root object that references, directly or indirectly, all other objects the application allocates.

These are special objects that are always accessible and could never get deleted by GC. Examples include global variables and static fields. By being an anchor point in memory, they serve as the starting point for GC to track other objects. The GC starts from the root object and track every object that’s reachable from it.

Retaining Path

The retaining path is the path from the root object that leads to a certain object. It’s a chain of pointers which starts at a root object and ends at the desired object. Any object that has a retaining path from root is considered as ‘reachable’ and won’t be cleaned up by GC.

Reachability Path

An object is said to be ‘reachable’ if there’s a way to reach it starting from a root object, or in other words, if it has a retaining path. If an object is unreachable (has no retaining paths), it implies that the program can no longer access it. Hence, GC can safely deallocate memory occupied by it.

Here’s a simple example:

Shallow size

Shallow size refers to the memory consumed by an object itself, without taking into account any objects it references. It represents the direct memory usage of the object, including its own fields or properties. Shallow size provides an estimate of the memory required to store the object without considering any additional memory usage caused by referenced objects.

Retained size

Retained size, on the other hand, refers to the memory consumed by an object and all the objects that are still reachable from it, directly or indirectly. It takes into account not only the shallow size of the object but also the memory usage of all the objects it references. Retained size provides a more comprehensive measure of memory usage, accounting for all objects that are retained and cannot be garbage-collected.

Here’s a simple example:

In this example, child1 and child2 are both shallow memory allocations, each contains an object of Child holding only their own property (name).

In this case, parent is a retained memory allocation. It contains the Person object, which includes its own properties (name and children) and the objects it references (child1 and child2).

FAQ

1. Is the instance variable memory allocated in Stack or Heap?

In Dart language, instance variables are stored in the heap.

Each object, including all of its instance variables, occupies a memory area on the heap. When you create an instance of a class, memory is allocated on the heap for a new object, and a reference to that object is returned.

Values in the heap can be accessed by any part of your application and live beyond the scope of the function they were created in, persisting for as long as there’s some part of your application holding a reference to them.

In contrast, the stack is used for static memory allocation and stores temporary information such as function call information, local primitive types and reference variables. However, the actual objects these reference variable point to would be stored in the heap.

Therefore, if you create an instance of an object – the reference to this object is stored in the stack, while the actual object and its instance variables are stored in the heap.

2. Is the static variable memory allocated in Stack or Heap?

In Dart, static variables are stored in the heap, not the stack.

A static variable is essentially bound to a class, rather than an instance of the class. It exists from the time the class is loaded until the application is terminated. Therefore, the memory allocated for static variables is available for the entire duration of the application, which is consistent with the behavior of heap-allocated memory.

Become a Job Ready Flutter developer

https://mobileacademy.io/courses/

The post Introduction To Dart Memory Management appeared first on WeCanCode.

]]>
https://wecancode.in/introduction-to-dart-memory-management/feed/ 1
Introduction To Garbage Collection in Dart https://wecancode.in/introduction-to-garbage-collection-in-dart/ Mon, 08 Jan 2024 09:06:30 +0000 https://mobileacademy.io/?p=847 In the previous post we learned about Dart VM, Garbage collection is one of the feature provided by Dart VM. Understanding garbage collector is crucial when you want to build a efficient applications. It allows you to manage memory resources effectively, preventing memory leaks and improving the overall performance and stability of your programs. What [...]

The post Introduction To Garbage Collection in Dart appeared first on WeCanCode.

]]>

In the previous post we learned about Dart VM, Garbage collection is one of the feature provided by Dart VM. Understanding garbage collector is crucial when you want to build a efficient applications. It allows you to manage memory resources effectively, preventing memory leaks and improving the overall performance and stability of your programs.

What Is Garbage Collection?

The Dart VM uses a form of automatic memory management where the garbage collector attempts to reclaim memory occupied by objects that are no longer in use by the program. Garbage collection primarily focuses is to managing dynamically allocated memory on the heap.

How is the memory allocated to heap?

In Dart, memory allocation on the heap typically occurs when you create objects using the new keyword or object constructors.

What are the steps taken by Dart Garbage Collector to free up memory?

  1. Marking:
    1. The garbage collector thoroughly scans the heap, which is the memory region where objects reside.
    2. It identifies which objects are still actively referenced by your program and marks them as “in use.”
  2. Sweeping:
    1. Once objects are marked, the garbage collector pinpoints the objects that are no longer referenced and therefore eligible for removal.
    2. These unreferenced objects are swept away, freeing up valuable memory space.
  3. Generational Approach:
    1. The Dart VM employs a generational garbage collection strategy:
      1. New objects are allocated in the new generation, which is frequently garbage collected to keep it clean and efficient.
      2. Objects that survive multiple garbage collections are promoted to the old generation, which is collected less often, reducing the overall overhead of garbage collection.
  4. Optional Compaction:
    1. Although not always performed, the garbage collector can optionally perform a compaction step.
    2. This involves rearranging the remaining objects in memory to create larger, contiguous blocks of free space.
    3. Compaction can help mitigate memory fragmentation, which can negatively impact performance over time.
  5. Continuous Process:
    1. Garbage collection is not a one-time event. It’s a continuous process that runs throughout your program’s execution to ensure efficient memory usage and optimal performance.

What is a generational approach used by Dart VM garbage collector?

The generational approach is a key strategy employed by the Dart VM’s garbage collector to optimize memory usage and improve performance. It works by dividing the heap (the memory area where objects reside) into two generations:

  1. New Generation: This generation holds recently allocated objects. It’s frequently scanned for garbage collection (typically mark-and-sweep), removing unreferenced objects swiftly. This helps prevent memory fragmentation and keeps the new generation small and efficient.
  2. Old Generation: Objects that survive multiple garbage collections in the new generation are promoted to the old generation. This generation is scanned less frequently than the new one, reducing overall garbage collection overhead. However, objects in the old generation can persist longer, potentially leading to fragmentation if they die at uneven intervals.

Memory fragmentation is when the sum of the available space in a memory heap is large enough to satisfy a memory allocation request but the size of any individual fragment (or contiguous fragments) is too small to satisfy that memory allocation request.

What are the benefits of using generational approach in Dart VM?

  • Reduced Memory Fragmentation: Frequent collection in the new generation minimizes fragmentation, meaning smaller wasted space between active objects. This allows smoother allocation of new objects without needing to search for fragmented pockets.
  • Improved Performance: Less frequent collection in the old generation reduces the overall overhead of garbage collection, boosting the program’s performance.
  • Balance Between Efficiency and Overhead: The approach balances efficient memory usage in the new generation with lower overhead in the old generation, aiming for an optimal overall performance.

However, it’s important to note that:

  • Full GC pauses can still occur: While less frequent, garbage collection in the old generation can still cause brief pauses in program execution, especially for long-lived applications with large object populations.
  • Generational approach does not eliminate fragmentation entirely: While significantly reduced, fragmentation can still occur in the old generation if object lifetimes vary greatly.

Become a Job Ready Flutter developer

https://mobileacademy.io/courses/

The post Introduction To Garbage Collection in Dart appeared first on WeCanCode.

]]>
Introduction To Dart VM https://wecancode.in/introduction-to-dart-vm/ Fri, 05 Jan 2024 09:56:32 +0000 https://mobileacademy.io/?p=841 The Dart Virtual Machine (Dart VM) is a component of the Dart platform that executes Dart bytecode. It is responsible for efficiently running Dart programs and providing a runtime environment for various Dart applications. Kernel service, which handles compilation of Dart source into Kernel binary. VM then will run resulting Kernel binary. The Dart Virtual [...]

The post Introduction To Dart VM appeared first on WeCanCode.

]]>
The Dart Virtual Machine (Dart VM) is a component of the Dart platform that executes Dart bytecode. It is responsible for efficiently running Dart programs and providing a runtime environment for various Dart applications.

dart vm

Kernel service, which handles compilation of Dart source into Kernel binary. VM then will run resulting Kernel binary.

The Dart Virtual Machine is a critical component of the Dart platform, providing a high-performance runtime environment for Dart programs. It offers a range of features, including garbage collection, concurrency support, native extensions, and profiling tools, enabling developers to build powerful and efficient applications. With its cross-platform support and seamless integration with popular IDEs, the Dart VM empowers developers to create performant Dart applications for a wide range of platforms and use cases.

The Dart VM is designed to be fast, efficient, and portable. It provides a just-in-time (JIT) compiler and an ahead-of-time (AOT) compiler for optimizing and executing Dart code. The JIT compiler allows for rapid development cycles by quickly compiling and executing code during the development process. On the other hand, the AOT compiler generates highly optimized machine code in advance, resulting in faster startup times and better performance for standalone Dart applications.

Does Flutter use Dart Virtual Machine (VM)?

Flutter uses Dart as its primary language and takes full advantage of Dart’s features, including running the Dart code in the Dart Virtual Machine (VM).

Flutter completely separates compilation to Kernel and execution from Kernel by putting them onto different devices: compilation happens on the developer machine (host) and execution is handled on the target mobile device, which receives Kernel binaries send to it by flutter tool.

Dart provides a flexible runtime through its VM that makes it possible to run both JIT (Just-In-Time) compiled code and AOT (Ahead-Of-Time) compiled code, which Flutter uses during different app life-cycle stages.

During the development phase, Dart VM runs with JIT compilation. This enables developers to make changes in the code and see them reflected in the app in real-time — a feature known as hot-reloading. The Dart VM keeps the compiled code in memory and updates it as the developer modifies the source code.

When you’re ready to release your Flutter app , the Dart VM compiles the Dart code using AOT compilation. AOT compilation converts the Dart code into machine code in advance, which results in faster app startup times and smoother execution. It’s important to note that in this phase, there’s no actual Dart VM included in the final app – the Dart code is compiled directly into native machine code for the respective platform (like ARM or x86 for mobile devices).

It’s also worth mentioning that the Dart VM provides other features to Flutter, such as garbage collection for memory management, and a rich set of core libraries for functionalities like collections, async programming, string manipulation, and more.

In summary, Flutter uses Dart VM for running Dart code efficiently with flexibility during the development and debugging stages, and it uses AOT compilation for creating a highly optimised final app binary for distribution.

When is the Dart VM Created?


The Dart Virtual Machine (Dart VM) is created when a Dart program starts running. Essentially, the Dart VM is an engine that executes Dart code in a managed runtime environment, bridging the gap between high-level Dart code and lower-level machine code.

However, in the case of Flutter, the Dart VM works bit differently. When a Flutter application is executed in development mode, the Dart VM is created and is used for JIT (Just-In-Time) compilation, enabling features like hot reload. The Dart VM is active throughout your session as you test and develop your Flutter application.

For building and releasing Flutter apps, Dart uses AOT (Ahead-Of-Time) compilation, which compiles Dart code directly into native machine code for each platform (Android, iOS, etc). So when a Flutter app is running on a device, it’s not actually using the Dart VM. Instead, it’s executing the compiled machine code directly.


Become a Job Ready Flutter developer

https://mobileacademy.io/courses/

The post Introduction To Dart VM appeared first on WeCanCode.

]]>
Exploring Flutter’s InteractiveViewer: Creating a Pinch-to-Zoom Image Experience https://wecancode.in/exploring-flutters-interactiveviewer-creating-a-pinch-to-zoom-image-experience/ Mon, 19 Jun 2023 10:47:43 +0000 https://mobileacademy.io/?p=721 Introduction: Flutter, Google’s UI toolkit for building beautiful and natively compiled applications, provides developers with a plethora of powerful widgets. One such widget is InteractiveViewer, which allows you to create interactive and dynamic user experiences. In this blog post, we will dive into the world of Flutter’s InteractiveViewer and explore how it can be used [...]

The post Exploring Flutter’s InteractiveViewer: Creating a Pinch-to-Zoom Image Experience appeared first on WeCanCode.

]]>
Introduction: Flutter, Google’s UI toolkit for building beautiful and natively compiled applications, provides developers with a plethora of powerful widgets. One such widget is InteractiveViewer, which allows you to create interactive and dynamic user experiences. In this blog post, we will dive into the world of Flutter’s InteractiveViewer and explore how it can be used to create a pinch-to-zoom image functionality. So, let’s get started!

Understanding Flutter’s InteractiveViewer Widget

InteractiveViewer is a versatile widget in Flutter that enables users to pan, zoom, and interact with its child widget(s) in a fluid and intuitive way. It provides a flexible and customizable approach to implement interactive elements such as maps, images, or any other visual content that requires user interaction.

Creating a Pinch-to-Zoom Image Experience

Let’s now delve into creating a pinch-to-zoom image feature using Flutter’s InteractiveViewer widget. Follow the steps below to implement this functionality:

Step 1: Import the Required Libraries

In your Dart file, import the necessary libraries:

import 'package:flutter/material.dart';

Step 2: Build the User Interface

In the build method of your widget, construct the user interface that includes an InteractiveViewer widget as its child. For this example, we will use an Image widget as the child:

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('Pinch-to-Zoom Image'),
    ),
    body: Center(
      child: InteractiveViewer(
        clipBehavior: Clip.none,
        minScale: 1,
        maxScale: 4,
        child: Image.asset('assets/images/my_image.jpg'),
      ),
    ),
  );
}

Make sure to replace 'assets/images/my_image.jpg' with the actual path to your image file.

Step 3: Configuring InteractiveViewer

To enable pinch-to-zoom functionality, InteractiveViewer provides various properties that can be adjusted according to your needs. Let’s take a look at some of the commonly used properties:

  • minScale: Defines the minimum scale factor for zooming.
  • maxScale: Specifies the maximum scale factor allowed. Setting it to a value 4.0 limits the zooming capability to image size x 4.

Step 4: Customize and Enhance

Feel free to explore other properties and methods provided by InteractiveViewer to customize the pinch-to-zoom image experience further. You can experiment with features like double-tap zooming, constraints, alignment, and more to match your specific requirements.

Conclusion

In this blog post, we learned about Flutter’s InteractiveViewer widget and how to create a pinch-to-zoom image functionality using it. By harnessing the power of InteractiveViewer

The post Exploring Flutter’s InteractiveViewer: Creating a Pinch-to-Zoom Image Experience appeared first on WeCanCode.

]]>
Flutter Learning Path for Beginners: A Comprehensive Guide to Kickstart Your Career in Flutter Development https://wecancode.in/flutter-learning-path-for-beginners/ Tue, 13 Jun 2023 08:51:19 +0000 https://mobileacademy.io/?p=715 Introduction Are you interested in becoming a Flutter developer? With its growing popularity and demand in the job market, Flutter offers an exciting career opportunity. Whether you’re a beginner or an experienced developer looking to transition into Flutter, having a structured learning path is essential. In this article, we’ll explore a comprehensive Flutter learning path [...]

The post Flutter Learning Path for Beginners: A Comprehensive Guide to Kickstart Your Career in Flutter Development appeared first on WeCanCode.

]]>
Introduction

Are you interested in becoming a Flutter developer? With its growing popularity and demand in the job market, Flutter offers an exciting career opportunity. Whether you’re a beginner or an experienced developer looking to transition into Flutter, having a structured learning path is essential. In this article, we’ll explore a comprehensive Flutter learning path for beginners, covering the essential topics and resources to help you embark on your journey towards becoming a proficient Flutter developer. Let’s get started!

  1. Understanding Flutter: An Overview

To begin your Flutter learning journey, it’s crucial to gain a solid understanding of what Flutter is and its key features. Start by exploring the basics of Flutter, its architecture, and how it differs from other frameworks. Familiarize yourself with the Flutter ecosystem, including Flutter SDK, Dart programming language, and Flutter’s widget-based approach for building user interfaces.

  1. Getting Started with Dart Programming

Since Flutter uses the Dart programming language, it’s essential to learn Dart fundamentals. Dive into Dart syntax, variables, data types, functions, control flow, and object-oriented concepts. Practice writing Dart code and understand how it integrates with Flutter.

  1. Setting Up Your Development Environment

Next, set up your Flutter development environment. Install Flutter SDK, VS Code / Android Studio, and necessary plugins. Configure Flutter for both iOS and Android development, ensuring you can test your apps on real devices and emulators.

  1. Building User Interfaces with Flutter Widgets

Flutter’s powerful widget system is at the core of building user interfaces. Learn about various types of widgets, including stateless and stateful widgets. Explore layout widgets for structuring UI elements and styling widgets for designing visually appealing interfaces. Practice creating responsive and interactive UIs using Flutter widgets.

  1. Managing State in Flutter

Understanding state management is crucial for building complex and interactive Flutter applications. Explore different state management techniques such as setState, Provider, BLoC (Business Logic Component), and Riverpod. Learn when and how to implement each approach based on the requirements of your app.

  1. Working with REST APIs

Integrating REST APIs is a common requirement in mobile app development. Learn how to make HTTP requests, handle responses, and parse JSON data in Flutter. Explore popular packages like Dio and http for managing API calls effectively. Practice retrieving and displaying data from a REST API in your Flutter app.

  1. Local Storage and Persistence

Learn how to incorporate local storage and persistence in your Flutter applications. Explore packages like shared_preferences , Hive, Isar, and sqflite to store and retrieve data locally on the user’s device. Understand the concepts of key-value pairs and SQLite databases for efficient data management.

  1. Creating Stunning Animations

Animations bring life to your Flutter apps, making them visually appealing and engaging. Learn how to create animations using Flutter’s animation library. Understand concepts like AnimationController, Tween, and AnimatedBuilder. Explore different animation types, including fade, slide, and scale animations. Practice incorporating animations into your Flutter UIs.

  1. Flutter Packages and Plugins

Leverage the vast ecosystem of Flutter packages and plugins to enhance your app’s functionality. Learn how to search, evaluate, and integrate third-party packages into your Flutter projects. Explore popular packages for tasks like networking, database integration, image handling, and more.

  1. Testing and Debugging Flutter Apps

Ensure the quality of your Flutter apps by mastering testing and debugging techniques. Learn how to write unit tests, widget tests, and integration tests using Flutter’s testing framework

  1. Deploying Flutter Apps

Once your Flutter app is ready, it’s time to deploy it to the app stores. Learn how to build, sign, and package your app for iOS and Android platforms. Understand the submission and review processes for App Store and Google Play Store, ensuring compliance with their guidelines.

  1. Continuing Your Learning Journey

Flutter is a rapidly evolving framework, so staying up-to-date with the latest developments is essential. Join Flutter communities, participate in forums, and follow Flutter blogs and tutorials to keep learning and expanding your Flutter skills. Consider attending Flutter conferences, meetups, and workshops to connect with industry professionals and gain valuable insights.

Conclusion

Embarking on a Flutter learning path as a beginner can be an exciting and rewarding experience. By following this comprehensive guide, you’ll have a structured roadmap to become a proficient Flutter developer. Remember to practice consistently, build projects, and seek hands-on experience to reinforce your knowledge. With dedication and perseverance, you’ll be well-equipped to kickstart your career in Flutter development and seize the abundant opportunities it offers.

The post Flutter Learning Path for Beginners: A Comprehensive Guide to Kickstart Your Career in Flutter Development appeared first on WeCanCode.

]]>
Firebase vs REST API: Choosing the Right Approach for Your Application https://wecancode.in/firebase-vs-rest-api-choosing-the-right-approach-for-your-application/ Mon, 12 Jun 2023 02:48:02 +0000 https://mobileacademy.io/?p=712 Introduction: In today’s rapidly evolving world of web and mobile applications, developers often face the dilemma of selecting the most suitable backend technology. Two popular options that frequently come up in this discussion are Firebase and REST API. While both serve the purpose of connecting client applications to server-side functionalities, they differ in their approaches [...]

The post Firebase vs REST API: Choosing the Right Approach for Your Application appeared first on WeCanCode.

]]>
Introduction: In today’s rapidly evolving world of web and mobile applications, developers often face the dilemma of selecting the most suitable backend technology. Two popular options that frequently come up in this discussion are Firebase and REST API. While both serve the purpose of connecting client applications to server-side functionalities, they differ in their approaches and use cases. In this blog post, we will compare Firebase and REST API, highlighting their strengths and guiding you on when to choose each approach.

I. Understanding Firebase: Firebase is a comprehensive backend-as-a-service (BaaS) platform offered by Google. It provides a suite of tools and services that assist in building and scaling applications quickly. Firebase encompasses features such as real-time database, authentication, cloud functions, hosting, and more. Its standout feature is the real-time database, which allows seamless data synchronization across clients.

II. Unpacking REST API: REST (Representational State Transfer) is an architectural style for designing networked applications. A REST API acts as an interface that enables communication between clients and servers using standard HTTP methods like GET, POST, PUT, and DELETE. REST APIs typically interact with databases or other data sources to perform CRUD (Create, Read, Update, Delete) operations.

III. Firebase Use Cases:

  1. Real-time Applications: Firebase excels in scenarios where real-time data updates are crucial, such as chat applications, collaborative tools, or live dashboards. Its real-time database uses WebSockets to deliver instantaneous updates to connected clients.
  2. Rapid Prototyping: If you need to develop a minimum viable product (MVP) or quickly validate an idea, Firebase’s prebuilt features and simplified setup can significantly speed up development time. It offers easy integration with popular frontend frameworks like Angular, React, or Flutter.
  3. Authentication and User Management: Firebase provides robust user authentication services out of the box, including email/password authentication, social login, and more. It handles the complexities of user management, allowing developers to focus on other aspects of their application.

IV. REST API Use Cases:

  1. Custom Backend Logic: REST APIs are a suitable choice when you require fine-grained control over your backend logic. If you need to integrate with existing databases or implement complex business rules, building a custom REST API allows for more flexibility and customization.
  2. Integration with Third-Party Services: When your application needs to interact with various external services, such as payment gateways, SMS providers, or email services, a REST API acts as a bridge, enabling seamless communication between your application and these services.
  3. Large-scale Applications: REST APIs offer scalability advantages for applications that anticipate high volumes of traffic and require advanced caching mechanisms, load balancing, or horizontal scaling. They allow for fine-tuning performance optimizations specific to your application’s requirements.

V. Choosing the Right Approach:

  1. Firebase Advantages: Consider using Firebase if you prioritize real-time updates, need a quick development turnaround, or require built-in authentication and user management. Firebase shines in scenarios where speed and simplicity are essential, and real-time data synchronization is critical.
  2. REST API Advantages: Opt for a custom REST API when you have specific business logic requirements, need integration with multiple external services, or anticipate large-scale application growth. REST APIs provide greater control, flexibility, and scalability options tailored to your application’s needs.

Conclusion: Choosing between Firebase and REST API depends on the nature of your application, its requirements, and the level of control and customization you seek. Firebase is an excellent choice for real-time applications, rapid prototyping, and simplified user management. REST APIs, on the other hand, offer flexibility, customization, and scalability options for applications requiring custom backend logic and seamless integration with external services. Carefully evaluate your project’s needs and weigh

The post Firebase vs REST API: Choosing the Right Approach for Your Application appeared first on WeCanCode.

]]>
REST API, WebSocket, GraphQL or Firebase For Job Prospective https://wecancode.in/rest-api-websocket-graphql-or-firebase-for-job-prospective/ Fri, 09 Jun 2023 03:26:52 +0000 https://mobileacademy.io/?p=708 When it comes to job prospects, it’s important to consider the current trends and demands in the industry. Each technology has its own significance and potential job opportunities. Here’s a brief overview of each: Considering the job market, it’s advisable to have a solid understanding of REST API principles, as it is a fundamental technology [...]

The post REST API, WebSocket, GraphQL or Firebase For Job Prospective appeared first on WeCanCode.

]]>
When it comes to job prospects, it’s important to consider the current trends and demands in the industry. Each technology has its own significance and potential job opportunities. Here’s a brief overview of each:

  • REST API: Representational State Transfer (REST) APIs are widely used in web and mobile development. RESTful APIs are commonly used to create client-server communication in various industries, making it a sought-after skill.
  • WebSockets: WebSockets provide real-time, bidirectional communication between clients and servers. They are often used in applications that require instant data updates, such as chat applications, collaborative tools, or real-time analytics dashboards. Knowledge of WebSockets is beneficial if you’re interested in real-time applications or working on projects that involve live data streaming.
  • GraphQL: GraphQL is a query language for APIs and a runtime for executing those queries. It offers efficient and flexible data retrieval, allowing clients to request specific data structures and reducing over-fetching or under-fetching of data. GraphQL has gained popularity due to its ability to simplify data fetching for frontend developers. Learning GraphQL can be advantageous if you’re interested in mobile development or working with modern API architectures.
  • Firebase: Firebase is a backend-as-a-service (BaaS) platform that provides a wide range of tools and services for building web and mobile applications. It includes features such as real-time database, authentication, cloud functions, and hosting. Firebase is known for its ease of use and rapid development capabilities. If you’re interested in developing applications quickly, particularly for mobile platforms, learning Firebase can be beneficial.

Considering the job market, it’s advisable to have a solid understanding of REST API principles, as it is a fundamental technology widely used in the industry. Additionally, having knowledge of WebSockets or GraphQL can be advantageous, especially if you’re interested in real-time applications or modern API architectures.

Firebase, while popular and useful for specific use cases, may be more niche compared to the broader demand for REST API skills. However, if you’re interested in mobile app development or rapid prototyping, learning Firebase can open up opportunities in those areas.

Ultimately, it’s beneficial to have a diverse skill set and stay adaptable to emerging technologies. Assess the specific job market you’re targeting, consider the industry trends, and align your learning path with the technologies in demand to enhance your job prospects.

The post REST API, WebSocket, GraphQL or Firebase For Job Prospective appeared first on WeCanCode.

]]>