Access of global variables in dart / flutter

1,896

The underscore _ before a variable name means that the variable is private. A global variable should be a public variable, a public variable on the other hand should begin without the _ By changing "final _firestore = Firestore.instance" to "final firestore = Firestore.instance" you should be able to access your variable globally.

Another way to make your private variable to be accessed on global level is by adding a getter like this: Firestore get firestore => _firestore;

Share:
1,896
user2929899
Author by

user2929899

Updated on December 22, 2022

Comments

  • user2929899
    user2929899 11 months

    I can't seem to access my global variables _firestore and loggedInUser from a different class in flutter / dart. From what I read in the documentation and online, this should be possible?

    Creating the global variables:

       import 'package:cloud_firestore/cloud_firestore.dart';
        
        final _firestore = Firestore.instance;
        FirebaseUser loggedInUser;
        
        class TheSlateScreen extends StatefulWidget {
    

    Trying to access them here:

    import 'package:theslate/screens/theslate_screen.dart';
    
    class SlateTasks extends ChangeNotifier {
    
     void addTask(String newTaskTitle) {
    
        _firestore.collection('Test').add({
          'Task': newTaskTitle,
          'User': loggedInUser.email,
        });
    
  • user2929899
    user2929899 over 3 years
    OMG... I missed the underscore. Thanks for the hint with the getter method, too!