I am using provider as state management. To use value between multiple files i create a provider like this
class globalProvider with ChangeNotifier, DiagnosticableTreeMixin {
String uuID = "";
String get _uuID => uuID;
void changeuuID(id) {
uuID = id;
notifyListeners();
}
}
I am updating value like this
final uuidUpdate = Provider.of<globalProvider>(context, listen: false);
uuidUpdate.changeuuID(user.uid);
Now on other page I need to print uuID value. I try to do like this
print(Provider.of<globalProvider>(context).uuID);
But its showing error Tried to listen to a value exposed with provider, from outside of the widget tree.
main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => globalProvider()),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: LoginPage(),
),
),
);
}
CodePudding user response:
you need to add your state up in your widgets tree like:
ChangeNotifierProvider(
create: (context) => globalProvider (),
builder: (context, _) {
return theRestOfTheTreeWidgets();}
)
CodePudding user response:
in your main.dart add ChangeNotifierProvider.value(value: GlobalProvider) in MultiProvider widget,
Make sure that your class starts with capital letter and let me know if arrow still exists.
CodePudding user response:
please use below code .. if its help you ..please upvote my answer and mark as accepted..if you find and problem please let me know and use this package
get_it: ^7.2.0
class GlobalProvider with ChangeNotifier, DiagnosticableTreeMixin {
String _uuID = "";
String get uuID => _uuID;
void changeuuID(id) {
_uuID = id;
notifyListeners();
}
}
in your main.dart .please must use Upper cast and paste the below code in main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await di.init();
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => di.sl<GlobalProvider >()),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: LoginPage(),
),
),
);
}
make a new dart file and paste this code
final sl = GetIt.instance;
Future<void> init() async {
sl.registerFactory(() => GlobalProvider ());
}
and I use this init() function in main file already ..just import library