Home > Blockchain >  How to handle null arguments in Getx Routing
How to handle null arguments in Getx Routing

Time:11-28

So I'm Using Getx's routing in Flutter.

I have a Product class that accepts an argument of the type Product

  const Produkt({
    required this.product,
  });

I handle the navigation through GetPages, like:

  GetPage(
    name: Produkt.route,
    page: () => Produkt(
      product: Get.arguments['product'],
    ),
  ),

But of course, this only works when the arguments aren't null. How could I redirect to an error page when the arguments are null?

CodePudding user response:

you can set a simple condition inside the build() method of your Produkt widget like this:

class Produkt extends StatelessWidget {
  const Produkt({
    super.key,
    required this.product,
  });
  final product;
  @override
  Widget build(BuildContext context) {
    if (product == null) {
      return YourErrorScreenWidget();
    }
    return WidegtOfProdukt();
  }
}

now based on product value, you can implement a YourErrorScreenWidget() if it's null, and your specific WidegtOfProdukt() when it's not.

CodePudding user response:

another solution is that you can make a check in the constructor to navigate to another screen when it's null, otherwise it will just work fine

 class Produkt extends StatelessWidget {
  Produkt({
    super.key,
    required this.product,
  }) {
    if (product == null) {
      Get.off(YourErrorScreenWidget());
    }
  }
  final product;
  @override
  Widget build(BuildContext context) {
    return WidegtOfProdukt();
  }
}

Note: you could also call the Get.off() to navigate to another screen from the build() method, but I guess there is no point of getting inside the build() method since you're going to navigate anyway.

  • Related