How does getx realize the `.obs` thing

Issue

Learning Flutter/getx package I came across the sample code like the following:

import 'package:get/get.dart';

class MyHomePageController extends GetxController {
  final count = 0.obs;
}

The code 0.obs scares me. I mean how an integer can have a .obs attribute? what has the getx pacakge done to my code?

Solution

This is a feature of dart language called extension introduced in Dart 2.7, it is a way to add functionality to existing libraries.

You might use extension methods without even knowing it.

For example, when you use code completion in an IDE, it suggests extension methods alongside regular methods.

For example, consider the following code that parses a string into an integer:

int.parse('42')

It might be nice — shorter and easier to use with tools — to have that functionality be on String instead:

'42'.parseInt()

To enable that code, you can import a library that contains an extension of the String class:

import 'string_apis.dart';
// ···
print('42'.parseInt()); // Use an extension method.

Extensions can define not just methods, but also other members such as getter, setters, and operators. Also, extensions have names, which can be helpful if an API conflict arises. Here’s how you might implement the extension method parseInt(), using an extension (named NumberParsing) that operates on strings.

extension NumberParsing on String {
  int parseInt() {
    return int.parse(this);
  }
  // ···
}

SUMMARY

the get package use extensions behind the scene to call getter of RxInt.

Object so the attribute is not actually called upon primitive datatype

this is from the source code of the get package … you can access it by pressing ctrl+ ".obs"

extension IntExtension on int {
  /// Returns a `RxInt` with [this] `int` as initial value.
  RxInt get obs => RxInt(this);
}

Answered By – Moaid ALRazhy

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.