Home > other >  I want to use few variables in other dart files. In short I want them to be globally accessed
I want to use few variables in other dart files. In short I want them to be globally accessed

Time:11-04

Here there are two bool variables I want them to be used in other dart files. How can I achieve that. class EmployeeRegistrationScreen extends StatefulWidget {

  static const id = 'employee_register';

  @override
  _EmployeeRegistrationScreenState createState() => _EmployeeRegistrationScreenState();
}

class _EmployeeRegistrationScreenState extends State<EmployeeRegistrationScreen> {

  bool showSpinner = false;
  final _auth = FirebaseAuth.instance;
  String email;
  String password;
  String confirmPassword;
  bool  _passwordVisible = false;
  bool _confirmPasswordVisible = false;
  String name;

CodePudding user response:

You can take a look at state management which will help app states between widgets. A good introduction by the Flutter team here: https://flutter.dev/docs/development/data-and-backend/state-mgmt/intro

CodePudding user response:

If you are trying to access data on multiple screens, the Provider package could help you. It stores global data accessible from all classes, without the need of creating constructors.

Here are some steps to use it (there is also a lot of info online):

  • Import provider in pubspec.yaml

  • Create your provider.dart file. For example:

    class HeroInfo with ChangeNotifier{
     String _hero = 'Ironman'
    
      get hero {
       return _hero;
      }
    
      set hero (String heroName) {
        _hero = heroName;
        notifyListeners();
      }
    }
    
  • Wrap your MaterialApp (probably on main.dart) with ChangeNotifierProvider.

    return ChangeNotifierProvider(
      builder: (context) => HeroInfo(),
      child: MaterialApp(...),
    );
    
  • Use it on your application! Call the provider inside any build method and get data:

    @override
    Widget build(BuildContext context){
      final heroProvider = Provider.of<HeroInfo>(context);
    
      return Column {
        children: [
          Text(heroProvider.hero) 
        ]
      }
    }
    
  • Or set data:

    heroProvider.hero = 'Superman';
    
  • Related