How to update the Flutter Sliders value from the Firebase database?
In this article, we will explore how to access and update values in the Flutter Sliders widget from a Firebase real-time database. We'll demonstrate this with an example of retrieving BMI values from a Firebase database.
Step 1: Add Syncfusion® Flutter Sliders package to your dependencies in pubspec.yaml file.
Step 2: Create a real-time data in the firebase database. Please refer to Add Firebase to your Flutter app documentation to create a database in a firebase console and connect your Flutter app to it.
Step 3: Create a async method named _getBMIData() which returns the BMI data obtained from firebase database. In that, create a class named BMIData which is used to store the parsed data from the firebase database.
Refer to the following code example.
// Get the BMI data from database. Future<List<BMIData>> getBMIData() async { Future<DataSnapshot> _dbReference = FirebaseDatabase.instance.reference().once(); List<BMIData> _bmiData = <BMIData>[]; await _dbReference.then( (dataSnapShot) async { // Access the values from database. Map<dynamic, dynamic> jsonData = dataSnapShot.value; // Add the data into a local collection and return it. jsonData.forEach( (key, value) { BMIData data = BMIData.fromJson(key, value); _bmiData.add(BMIData( name: key, height: double.parse(data.height.toString()), weight: double.parse(data.weight.toString()), bmi: double.parse(data.bmi.toString()), category: data.category.toString())); }, ); }, ); return _bmiData; } // Class which parse the data from database class BMIData { String name; late double height; late double weight; late double bmi; late String category; BMIData( {required this.name, required this.height, required this.weight, required this.bmi, required this.category}); BMIData.fromJson(this.name, Map data) { height = data['height']; weight = data['weight']; bmi = data['bmi']; category = data['category']; } }
Step 4: Return the list of BMI data to the Future Builder widget which is the parent of our slider widget. Now use the future builders snapshot data, to update the BMI value in slider and other respective widgets.
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Padding( padding: const EdgeInsets.all(20), child: FutureBuilder( future: getBMIData(), builder: (context, snapshot) { if (snapshot.hasData) { List<BMIData> data = snapshot.data as List<BMIData>; return Column( mainAxisSize: MainAxisSize.min, children: [ const Text( 'BMI Calculator', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), // Include any widgets here. SfSlider( min: _min, max: _max, interval: 10, value: data[0].bmi, showLabels: true, showTicks: true, onChanged: null, ), // Include any widgets here. ], ); } return const Text('Loading...'); }, ), ), ), ); }
Output
Check the below links for more features in Syncfusion® Flutter Sliders,
Live samples,