Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Merrit
Created April 20, 2021 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Merrit/66a45909a701dbbf5d969221376444d8 to your computer and use it in GitHub Desktop.
Save Merrit/66a45909a701dbbf5d969221376444d8 to your computer and use it in GitHub Desktop.
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