Search code examples
flutterflutter-getx

Why would wrapping a Row in Obx create an error?


I have a widget that renders as expected, but when I wrap it with Obx((){}) I get an error. The wrapped code looks like this (I can add details about variables, etc. if desired):

class KeyboardRow extends StatelessWidget {
const KeyboardRow(this.min, this.max, {super.key});

final int min;
final int max;

@override
Widget build(BuildContext context) {
// final size = MediaQuery.of(context).size;
final controller = Get.put(Controller());

Obx(
  () {
    int index = 0;

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: controller.k.entries.map(
        (e) {
          index++;
          if (index >= min && index <= max) {
            return Container(
              margin: const EdgeInsets.all(4.0),
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                borderRadius: const BorderRadius.all(Radius.circular(6.0)),
                color: e.value == AnswerStage.correct
                    ? Colors.green
                    : e.value == AnswerStage.contains
                        ? Colors.yellow
                        : Colors.grey,
              ),
              child: InkWell(
                onTap: () {
                  controller.onKeyPress(e.key);
                },
                child: Center(
                  child: Text(
                    e.key,
                    style: const TextStyle(fontSize: 20),
                  ),
                ),
              ),
            );
          } else {
            return Container();
          }
        },
      ).toList(),
    );
  },
);

} }

and the resulting error is The body might complete normally, causing 'null' to be returned, but the return type, 'Widget', is a potentially non-nullable type. Try adding either a return or a throw statement at the end.


Solution

  • Could the issue you're experiencing be because you didn't put return in front of Obx?

    return Obx(() {
        ...
      });