Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here are the steps to access sensor data stored in the Firebase realtime database and display it on a Flutter application:

  1. Set up your Firebase project and create a realtime database in it.

  2. Connect your Flutter application to the Firebase project using the Firebase package. Add the following dependencies to your pubspec.yaml file:

dependencies:
  firebase_core: ^1.10.0
  firebase_database: ^8.2.3
  1. Initialize the Firebase app with the following code in the main function of your Flutter app:
import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}
  1. In the Flutter app, you can retrieve the sensor data from the Firebase database using the Firebase database reference. For example, to get the data from a node called "sensor" in the Firebase database, use the following code:
import 'package:firebase_database/firebase_database.dart';

final databaseReference = FirebaseDatabase.instance.reference();

databaseReference.child('sensor').once().then((DataSnapshot snapshot) {
  print('Data : ${snapshot.value}');
});
  1. To display the sensor data on the Flutter app, you can use any widget such as Text or ListView depending on how you want to display the data. For example, to display the sensor data in a Text widget, modify the above code as follows:
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';

final databaseReference = FirebaseDatabase.instance.reference();

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Sensor Data"),
      ),
      body: Center(
        child: FutureBuilder(
          future: databaseReference.child('sensor').once(),
          builder: (BuildContext context, AsyncSnapshot<DataSnapshot> snapshot) {
            if (snapshot.hasData) {
              return Text('Sensor Data: ${snapshot.data!.value}');
            } else {
              return CircularProgressIndicator();
            }
          },
        ),
      ),
    );
  }
}
  1. Run the application to view the sensor data from the Firebase database displayed on the app.