Getx: Obx does not work on appBar

Created on 8 Oct 2020  路  2Comments  路  Source: jonataslaw/getx

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

void main() {
  Get.put(Ic());

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Index(),
    );
  }
}

class Index extends StatelessWidget {
  final controller = Get.find<Ic>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Obx(
        () => AppBar(
          actions: [if (controller.changed.value) IconButton(icon: Icon(Icons.publish), onPressed: controller.uploadData)],
        ),
      ),
      floatingActionButton: IconButton(icon: Icon(Icons.cached), onPressed: controller.changed),
    );
  }
}

class Ic extends GetxController {
  final changed = RxBool(false);

  void change() {
    changed.value = true;
  }

  void uploadData() {
    changed.value = false;
  }
}

invalid

Most helpful comment

First, there is an error here
floatingActionButton: IconButton(icon: Icon(Icons.cached), onPressed: controller.changed)
This correct is:
floatingActionButton: IconButton(icon: Icon(Icons.cached), onPressed: controller.change)

Second, appBar does not accept Obx, as it is not a subtype of PreferredSizeWidget, so you can do this:

appBar: AppBar(
  actions: [
    Obx(() {
      if (controller.changed.value) return IconButton(icon: Icon(Icons.publish), onPressed: controller.uploadData);
      return SizedBox(); // Obx expects a widget in return
    })
  ],
)

All 2 comments

First, there is an error here
floatingActionButton: IconButton(icon: Icon(Icons.cached), onPressed: controller.changed)
This correct is:
floatingActionButton: IconButton(icon: Icon(Icons.cached), onPressed: controller.change)

Second, appBar does not accept Obx, as it is not a subtype of PreferredSizeWidget, so you can do this:

appBar: AppBar(
  actions: [
    Obx(() {
      if (controller.changed.value) return IconButton(icon: Icon(Icons.publish), onPressed: controller.uploadData);
      return SizedBox(); // Obx expects a widget in return
    })
  ],
)

As answered by Eduardo, appBar only accepts widgets of the PreferredSizeWidget subtype.
As this question has nothing to do with Getx, but as a basic knowledge of Flutter, I'm closing it.

Was this page helpful?
0 / 5 - 0 ratings