Search code examples
flutterdartglobal-variablesstate-management

How do I change the variable from across page if the target page has no context?


'databaseFunctions.dart'

String path = 'path'     // a variable needed to be modified across page
Future queryALL() async {
    Database db = await openDatabase(path);
    return await db.query('all'); }

'main.dart'

// inside a stateful widget 
DropdownButton(
  value: currentValue,
  onChanged: (String newValue) {
        setState(() {
          currentValue = newValue;
          >> path = newValue << ;}}  // How can I accomplish this?

'few other pages'
// call queryALL() to build dataTable

Provider, Navigator didn't work since the page var x is in has no Widget, therefore no explicit entrance for any context. 'import' didn't work, since it only initializes var x. Any ideas?


Solution

  • I am using state management Getx for this situations. Import like this

    dependencies:
      get: ^3.8.0
    

    Define controller like this

    class DatabaseController extends GetxController{
        RxString path = 'path'.obs;
        Future queryALL() async {
            Database db = await openDatabase(path);
            return await db.query('all'); 
        }
    }
    

    If you will use this controller anywhere you should initiate when program starts. I recommend you do it in your main.dart

    DatabaseController dbController = Get.put(DatabaseController());
    

    Then you always can access this controller like this

    DatabaseController dbController = Get.find();
    

    You just need to call like this

    DropdownButton(
      value: currentValue,
      onChanged: (String newValue) {
          setState(() {
              currentValue = newValue;
              dbController.path.value = newValue;
              dbController.queryAll();
          }
      }