You can create the providing on current route, but to access it, you need to separate the context.
return ChangeNotifierProvider<Counter>(
create: (_) => Counter(),
child: Builder(
builder: (context) {
// we cant accass the context of the provider within same context while context
return Scaffold(
Now to pass the current provider on next route
final value = context.read<Counter>();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider<Counter>.value(
value: value,
builder: (context, child) {
return const NextPage();
},
),
),
);
Test snippet
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class Counter extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<Counter>(
create: (_) => Counter(),
child: Builder(
builder: (context) {
// we cant accass the context of the provider within same context while context
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Consumer<Counter>(
builder: (context, Counter counter, child) {
return Text("Count: ${counter.count}");
},
),
ElevatedButton(
onPressed: () {
context.read<Counter>().increment();
},
child: const Text("Increment"),
),
ElevatedButton(
onPressed: () {
final value = context.read<Counter>();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider<Counter>.value(
value: value,
builder: (context, child) {
return const NextPage();
},
),
),
);
},
child: const Text("Next Page"),
),
],
),
));
},
),
);
}
}
class NextPage extends StatelessWidget {
const NextPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Next Page"),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Consumer<Counter>(
builder: (context, Counter counter, child) {
return Text("Count: ${counter.count}");
},
),
ElevatedButton(
onPressed: () {
context.read<Counter>().increment();
},
child: const Text("Increment"),
),
],
),
),
);
}
}