4

I try refactor my flutter app and start using GetX library. I using library "flutter_form_builder", and some methods here need BuildContext argument. For example:

String? Function(T?) FormBuilderValidators.equal<T>(
  BuildContext context,
  Object value, {
  String? errorText,
})

I try add as argument Get.context, but Get.context type is BuildContext? not BuildContext Any idea how to solve it?

sosnus
  • 968
  • 10
  • 28
  • 1
    If you are sure that `Get.context` won't be null, then you could add an exclamation mark to tell Flutter that you're sure it won't be null at runtime. `Get.context!` – Stack Underflow Jan 20 '22 at 00:35
  • Thanks, it's nice Idea, so now I have two ways: `Get.context!` or `Get.context as BuildContext` What is better? – sosnus Jan 20 '22 at 00:40
  • 1
    The exclamation mark is used to explicitly tell the null-safety checks that you know for sure the value will not be null at runtime. If you do not know that for sure, then you probably should not go that route because the whole point is to prevent runtime exceptions which you would be circumventing. – Stack Underflow Jan 20 '22 at 00:42
  • I strongly recommend you avoid using Get.context because it is against flutter BuildContext concept. Try to pass context through your methods wherever you need. – Salar Arabpour Apr 14 '22 at 23:07

1 Answers1

2

you can use Get.context which comes from the Getx package when you need it outside your UI, and mark it with ! so it will be a BuildContext type:

Get.context // this is BuildContext?
Get.context! // this is BuildContext

you can also cast it directly like this:

Get.context as BuildContext // this is BuildContext

Note: using Get.context requires that you need to change MaterialApp with GetMaterialApp so it will never be null, otherwise it will throws a null error

Gwhyyy
  • 7,554
  • 3
  • 8
  • 35