Data binding in Flutter refers to the mechanism of establishing a connection between the user interface (UI) and the underlying data model. It allows for automatic synchronization and updates between the data and the UI, ensuring that any changes in the data are reflected in the UI and vice versa. more
Example Databinding in GetX
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class CounterController extends GetxController {
// Define a reactive variable using Rx
RxInt counter = 0.obs;
void increment() {
// Update the counter value
counter.value++;
}
}
class MyApp extends StatelessWidget {
// Create an instance of the counter controller
final CounterController counterController = Get.put(CounterController());
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Data Binding Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Observe the counter variable and update the UI
Obx(
() => Text(
'Counter Value: ${counterController.counter.value}',
style: TextStyle(fontSize: 24),
),
),
SizedBox(height: 16),
ElevatedButton(
onPressed: () {
// Call the increment method on button press
counterController.increment();
},
child: Text('Increment'),
),
],
),
),
),
);
}
}
void main() {
runApp(MyApp());
}
In the above example, we have a CounterController class that extends GetxController and defines a reactive variable counter using the obs extension. The increment method updates the value of counter.
In the MyApp widget, we create an instance of CounterController and assign it to counterController using Get.put. Inside the UI, we use the Obx widget to observe the counter variable from the controller and update the UI whenever it changes.
The ElevatedButton triggers the increment method on button press. Whenever the counter value changes, the Obx widget automatically rebuilds the Text widget to reflect the updated value. This demonstrates the data binding mechanism provided by GetX in Flutter.
Remember to import the necessary packages (get/get.dart in this case) and ensure that you have the GetX package added as a dependency in your pubspec.yaml file.