Search⌘ K

Provider Best Practices: Provider Listeners

Explore how to use Provider listeners to manage state efficiently in Flutter. Learn to reduce unnecessary widget rebuilds by splitting widgets into smaller reusable stateless components, improving app performance and code readability.

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.

Dart
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);
@override
Widget 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 name
onPressed: () => 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 widget rebuilds has been restricted in a significant way:

This time we ...