Noobies CH
Noobies CH

Reputation: 21

List obs variable in GetX Controller still empty after added value in Flutter

When i add value to an obs list in GetX controller inside a function, it shows the length that the data is successfully added. But when i call the variable in another function, the list is still empty.

class ExampleController extends GetxController {
  var dataList = <dynamic>[].obs;

  void setImages(items) {
    dataList.addAll(items);
    log(dataList.length.toString()); // shows the data length after added items
  }

  void onButtonPressed() {
    log(dataList.length.toString()); // shows 0 length
  }
}

I put the controller like this ..

void main {
  runApp(const myApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Get.put(ExampleController());

    return GetMaterialApp(
      title: 'GetX Example',
      debugShowCheckedModeBanner: false,
      home: const SplashScreen(),
    );
  }
}

And this is how i instantiate the controller..

class DataPage extends StatefulWidget {
  const DataPage({Key? key}) : super(key: key);

  @override
  State<DataPage> createState() => _DataPageState();
}

class _DataPageState extends State<DataPage> {
  final _exampleController = Get.find<ExampleController>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: Center(
        child: CustomButtonIcon(
          label: 'Get Data',
          onPressed: () => _exampleController.onButtonPressed(),
          icon: Icons.arrow_back_rounded,
        ),
      )),
    );
  }
}

Upvotes: 0

Views: 1466

Answers (2)

krishnaacharyaa
krishnaacharyaa

Reputation: 24912

You have declared the setImages() function . But never called .

So the List obs variable in Controller is empty.

To work as expected. Before the onButtonPressed() function call the setImages() function

Upvotes: 1

Tasnuva Tavasum oshin
Tasnuva Tavasum oshin

Reputation: 4740

 void setImages(items) {
    dataList.addAll(items);
    log(dataList.length.toString()); // shows the data length after added items

     update(); // use this
  }

  void onButtonPressed() {

Future.delayed(const Duration(milliseconds: 500), () {
    log(dataList.length.toString()); // shows 0 length

});
  }

Upvotes: 0

Related Questions