Created
April 20, 2021 13:33
-
-
Save Merrit/66a45909a701dbbf5d969221376444d8 to your computer and use it in GitHub Desktop.
Provider new route example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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