So I'm slowly getting the hang of the GetX package usage after just finally learning about flutter and stateless and stateful widgets.In this example i'm trying to understand how to properly create and set variables in GetX. So I'm trying to check for permissions and when I do this inside a method it works...
var cameraStatus = await Permission.camera.status;
but I want this variable in the class level not in the method so I try to create it like this above the method...
var cameraStatus = Permission.camera.status.obs;
but when I use this in the method...
cameraStatus.value = await Permission.camera.status;
I get the error "A value of type 'PermissionStatus' can't be assigned to a variable of type 'Future'. Try changing the type of the variable, or cast the right-hand type to 'Future'."
Can someone enlighten me on how I'm supposed to create variables with Getx properly please.
Keep in mind that just because you're using Getx, not everything needs to be made into observable streams with .obs
.
While you can make custom objects observable, ask yourself why you feel the need to. Usually there's gonna be an easier way that accomplish what you need.
For example what you have here:
var cameraStatus = Permission.camera.status.obs;
Personally I don't see any value into changing a custom PermissionStatus
type from an external package into an observable stream. Just use it as they show in the docs.
If you need to rebuild something based on the result of the permission request, you can use GetBuilder
from Getx or FutureBuilder
from the Flutter SDK.
Or if you want to use Obx
widget then update the value of an RxBool
based on permissions and rebuild your UI off of that. Personally if I have a project with GetX, I'm using GetBuilder
for the vast majority of any UI updates I need. It will rebuild based on the change of any type once you call update.
All the app needs to know is a simple true or false of whether it has permission or not. So my suggestion is to just keep it simple.
class PermissionController extends GetxController {
bool hasCameraPermission = false;
Future<void> checkCameraPermission() async {
final status = await Permission.camera.status;
if (status == Permission.camera.isGranted) {
hasCameraPermission = true;
update(); // only needed if you're using GetBuilder widget
return; // ending the function here because that's all you need.
}
if (status.isDenied) {
await Permission.camera.request();
}
// ...continue to handle all the possible outcomes
update();
}
}
This also saves you from errors that you're getting from comparing unequal data types like you're doing here.
cameraStatus.value = await Permission.camera.status;
Then whatever part of your UI that depends on permissions could look like this
GetBuilder<PermissionController>(
builder: (controller) {
return controller.hasCameraPermission ? SomeWidget() : SomeOtherWidget();
},
)