does anyone know how i can access variables from another class without having to pass them directly when calling a page like this "Pagetwo(data:data)" because dont need the page to open i just need the variables, i tried simply importing the class i wanted and accessing it like this " var newdata = otherclass.data" but i keep getting the error "Instance member 'data' can't be accessed using static access", not sure what to do next,been researching for a while now


Solution 1: Abhishek Ghaskata

There are two ways to do it

  1. Global (which is not recommend)
  2. state management technique (which is recommend)

there are many state management technique are there:

InheritedWidget

Scoped Model

ProviderScope

Redux

BLOC

RxVMS

MVC

rebloc

Dartea

MobX

Statelessly/Reactivity

var_widget

fish-redux

Flutter Hooks

Provider

AsyncRedux

OSAM

Get

Momentum

state_notifier (by creator of provider)

cubit (by creator of bloc)

maestro

meowchannel

no_bloc

blocstar

mvcprovider

states_rebuilder

The most popular state management technique is provider, bloc, redux, getX, InheritedWidget. if you need an example then please let me know.


Solution 2: Abhishek Ghaskata

you have to make viewModel in the provider where every variable is there.

class BaseModel extends ChangeNotifier {
  int variable = 0;
  notifyChange() {
    notifyListeners();
  }

  @override
  void dispose() {
    super.dispose();
  }
}

let's say if you have two classes and you want to access the same variable which is in ViewModel so you can use provider singleton for that.

This is the first-class which is on one page.

class BookDetail extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final BookModel bookModel = Provider.of(context);
    print(bookModel.variable);
   }
}

This is the second class which is another page.

class BookDetailPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final BookModel bookModel = Provider.of(context);
    print(bookModel.variable);
   }
}