skip to Main Content

i want to access cameras in another dart file, how can i do it, my app is complex can’t be shared through constructor, i am using Getx (i am new to getx), help is appriciated
this is my main.dart

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final cameras = await availableCameras();
  runApp(MyApp());
}

2

Answers


  1. It’s a local variable, but you can declare it globally and make a getter function for it:

    var cameras;
    
    void main(){
     // initialize cameras here
    } 
    
    getCameras()=>cameras;
    

    You can call getCameras() or cameras itself anywhere to get the value of that variable.

    Login or Signup to reply.
  2. In this case, using a service locator seems to be a proper solution. A good candidate would be get_it.

    Setup:

    After installing it in your project:

    flutter pub add get_it
    

    You could declare a global instance of it:

    GetIt getIt = GetIt.instance;
    

    The recommendation for registering classes is to have an abstraction layer. Example:

    class Camera {
      // ...
    }
    
    abstract class CamerHandler {
      List<Camera> getAvailableCameras();
    }
    
    class CameraHandlerImplementation implements CamerHandler {
      @override
      List<Camera> getAvailableCameras() {
        // ...
      }
    }
    

    Note that you can also register concrete types. The recommendation for using the abstract base classes as a registration type is to vary the implementations.

    Therefore, you could register it as:

    getIt.registerSingleton<CamerHandler>(CameraHandlerImplementation());
    

    Make sure to register your class(s) when launching – in the main before calling runApp(const MyApp());

    Usage:

    Now, you have access to it throughout your whole app’s scope!

    final cameras = getIt<CamerHandler>().getAvailableCameras();
    

    You might want to look at the different methods for registering for your class; registerSingleton should be suitable here…

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search