...

/

The GetView and GetWidget Classes

The GetView and GetWidget Classes

Learn to use GetView and GetWidget to readily access the controller.

Simplifying dependency access

GetX provides an excellent API for segregating dependency injection into multiple classes and hiding it from the presentation layer. However, we still need to use Get.find to access the dependency in the widget. GetX takes it a step further by introducing the GetView and GetWidget widgets.

GetView

GetView is a stateless widget that internally declares a controller for us. We can readily use the controller instance without calling Get.find. Just provide the type of controller we wish to access, like this:

Press + to interact
// Provide the controller type.
class HomePage extends GetView<Controller> {
@override
Widget build(BuildContext context) {
// Access controller directly.
return Text(controller.name);
}
}

GetView provides an instance of Controller, named controller. This simple widget can replace any widget that depends on a single controller.

Hands-on example

Here we have a counter app, just like Flutter's default. We create a controller to manage the state of the counter that can be incremented by pressing the FAB. Notice how we don’t use Get.find to access the controller. We access it directly with GetView's controller property.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.obx">
    <!-- The INTERNET permission is required for development. Specifically,
         the Flutter tool needs it to communicate with the running application
         to allow setting breakpoints, to provide hot reload, etc.
    -->
    <uses-permission android:name="android.permission.INTERNET"/>
</manifest>
A counter app project in which we use GetView to access the controller directly, without using Get.find

Code explanation

Below is a detailed explanation of the code:

In the controller.dart file:

...