Want to avoid unnecessary rebuilds while using provider in flutter? Selector is what you need. With selector you can filter updates. For example to update only when name change you can do something like this
I just avoided unnecessary rendering by editing my code as the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:flutter/foundation.dart'; class MyCounter with ChangeNotifier { int _num = 0; int get num => _num; set num(int n) { _num = n; notifyListeners(); } void increament() { _num = _num + 1; notifyListeners(); } void decreament() { _num = _num - 1; notifyListeners(); } } void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { print('root build called'); return ChangeNotifierProvider( builder: (context) => MyCounter(), child: MaterialApp( title: 'MyAppJan', home: Scaffold( appBar: AppBar(title: Text('Home')), body: AllWidget(), ), theme: ThemeData(primarySwatch: Colors.orange), )); } } class AllWidget extends StatelessWidget { @override Widget build(BuildContext context) { print('state build called'); return Center( child: Column( children: <Widget>[ MyCounterText(), SizedBox(height: 10), MyIncreaseButton(), SizedBox(height: 10), MyDecreaseButton(), ], mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, ), ); } } class MyCounterText extends StatelessWidget { @override Widget build(BuildContext context) { print('MyCounterText'); return Consumer<MyCounter>( builder: (context, myCounter, _) { return Text(myCounter.num.toString()); }, ); } } class MyIncreaseButton extends StatelessWidget { @override Widget build(BuildContext context) { final _items = Provider.of<MyCounter>(context,listen: false); print('MyIncreaseButton'); return RaisedButton( child: Text('Increase ++'), onPressed: () => _items.increament(), ); } } class MyDecreaseButton extends StatelessWidget { @override Widget build(BuildContext context) { final _items = Provider.of<MyCounter>(context,listen: false); print('MyDecreaseButton'); return RaisedButton( child: Text('Decrease --'), onPressed: () => _items.decreament(), ); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.