Using an observable variable without a controller in Flutter GetX

Issue

Something that I didn’t completely understand about the Get package is whether it is always required to put the observable variables in a controller. For example, this case works:

import 'package:flutter/material.dart';
import 'package:get/get.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  final isTrue = true.obs;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Demo',
      theme: ThemeData(
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Scaffold(
        body: Center(
          child: Obx(
            () => FlatButton(
              color: isTrue.value ? Colors.blue : Colors.red,
              child: Text('Hey'),
              onPressed: () => isTrue.value = !isTrue.value,
            ),
          ),
        ),
      ),
    );
  }
}

But would there be leaks/problems, because of this and is a GetXController necessary in this situation?

Solution

So as @Baker explained with his comments, the obs streams should be destroyed through the GetXControllers and they will persist in memory, if used independently in a stateless widget.

Answered By – Mono Chrome

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *