Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Provider new route example
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: FirstPage(),
);
}
}
class CounterState extends ChangeNotifier {
int _counter = 0;
int get counter => _counter;
void incrementCounter() {
_counter++;
notifyListeners();
}
void decrementCounter() {
_counter--;
notifyListeners();
}
}
class FirstPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => CounterState(),
builder: (context, child) {
return Scaffold(
body: Center(
child: Text('Counter: ${context.watch<CounterState>().counter}'),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
final _counter = context.read<CounterState>();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider.value(
value: _counter,
child: SecondPage(),
),
),
);
},
label: Text('Go to second page'),
),
);
},
);
}
}
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final _counter = context.read<CounterState>();
return Scaffold(
appBar: AppBar(),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () => _counter.decrementCounter(),
child: Text('Decrement counter'),
),
SizedBox(width: 10),
ElevatedButton(
onPressed: () => _counter.incrementCounter(),
child: Text('Increment counter'),
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment