Created
April 24, 2020 13:27
-
-
Save happyharis/ffecfcf6e3b5030af21ec662a5e60854 to your computer and use it in GitHub Desktop.
Provider 4.1 sneek peak on context extension and watch, read and select methods.
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(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
visualDensity: VisualDensity.adaptivePlatformDensity, | |
), | |
home: MultiProvider( | |
providers: [ | |
ChangeNotifierProvider<Counter>(create: (_) => Counter()), | |
Provider<Like>( | |
create: (BuildContext context) => Like(context.read), | |
) | |
], | |
child: MyHomePage(title: 'Provider 4.1 Sneak Peek'), | |
), | |
); | |
} | |
} | |
class MyHomePage extends StatelessWidget { | |
MyHomePage({Key key, this.title}) : super(key: key); | |
final String title; | |
@override | |
Widget build(BuildContext context) { | |
final _counter = context.watch<Counter>(); | |
// final _increment = context.select((Counter counter) => counter.increment); | |
final _add = context.select((Like value) => value.add); | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(title), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
Text( | |
'You have liked providers this many times:', | |
), | |
Text( | |
_counter.value.toString(), | |
style: Theme.of(context).textTheme.headline4, | |
), | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: _add, | |
tooltip: 'Increment', | |
child: Icon(Icons.thumb_up), | |
), | |
); | |
} | |
} | |
class Counter extends ChangeNotifier { | |
int _value = 0; | |
int get value => _value; | |
void increment() { | |
_value++; | |
notifyListeners(); | |
} | |
} | |
class Like { | |
Like(this._locator); | |
final Locator _locator; | |
void add() { | |
_locator<Counter>().increment(); | |
_locator<Counter>().increment(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment