Provider Best Practices: Provider Listeners
Learn about the best practices for the provider library and how the state management can be more efficient by utilizing listeners.
SecondRowWidget
listens to NameChangeModel
Just like before, this time, we will press the second button to change the name “Sanjib” to “John”.
To make this change, the second-row widget will listen to the name change model.
Press + to interact
import 'package:flutter/material.dart';import 'package:provider/provider.dart';import '../model/name_change_model.dart';class SecondRowWidget extends StatelessWidget {const SecondRowWidget({Key? key,}) : super(key: key);@overrideWidget build(BuildContext context) {return Row(mainAxisSize: MainAxisSize.min,children: [Expanded(child: Padding(padding: EdgeInsets.all(20.0),child: Column(children: [//Text('The changed name will appear here!'),Text('${context.watch<NameChangeModel>().name}'),/*ElevatedButton(/// This is our another [NameChangeModel] listener/// read() will fire the event that changes the nameonPressed: () => context.read<NameChangeModel>().changeName(),child: Text('Change Name'),),*/FloatingActionButton(onPressed: () => context.read<NameChangeModel>().changeName(),tooltip: 'Change Name',child: Icon(Icons.add),),],),),),],);}}
Clearly, the Provider
helps to reduce the widget rebuilds. Even when we press the two buttons subsequently, it results in less memory usage.
The following image will demonstrate how the process of ...
Get hands-on with 1400+ tech skills courses.