The ValueListenableBuilder widget in Flutter is used to rebuild a subtree of widgets when the value of a ValueNotifier changes. It's particularly useful when you want to rebuild a portion of your UI in response to changes in a value without having to manage the subscription manually.
Attributes:
valueListenable (ValueListenable<T>):
- The ValueListenable whose value is being observed for changes.
builder (Widget Function(BuildContext, T, Widget?)):
- A builder function that returns a widget tree based on the current value of the ValueListenable. It takes three arguments: the BuildContext, the current value of the ValueListenable, and the previous child widget.
Example:
import 'package:flutter/material.dart';
class Counter extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
class ValueListenableBuilderExample extends StatelessWidget {
final Counter counter = Counter();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ValueListenableBuilder Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ValueListenableBuilder<int>(
valueListenable: counter,
builder: (context, count, child) {
return Text(
'Counter: $count',
style: TextStyle(fontSize: 18),
);
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
counter.increment();
},
child: Text('Increment'),
),
],
),
),
);
}
}
void main() {
runApp(MaterialApp(
home: ValueListenableBuilderExample(),
));
}
Explanation:
In this example, a Counter class is defined that extends ChangeNotifier. It has an integer _count which is incremented when increment method is called and notifies the listeners.
The ValueListenableBuilder widget observes the Counter object for changes in its value using valueListenable attribute.
Inside the builder function, a Text widget is returned that displays the current count value.
When the button is pressed, the increment method of Counter is called, which updates the count value and triggers a rebuild of the ValueListenableBuilder, updating the displayed count.