Flutter Stream Builder
In this blog we are going to see how to use a stream builder, what is a stream builder and how to implement it. This blog will is the continuation of the last blog I wrote on flutter Linux in which we run Linux command and get output from firebase. But in that what if we have a large team all run command and you are an administrator you have to keep an eye on the system what command users are running. So here, Stream builder come in play. I request if you have not seen that blog please go and read it first. I will provide a link below.
What is Stream Builder?
Stream builder is basically something that rebuilds itself as soon as new data comes.
Let’s understand how to implement a stream builder in our last Linux app.
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(); runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
// Firebase.initializeApp();
// Firebase.initializeApp();
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Linux APP"),
),
body:
StreamBuilder(
stream: FirebaseFirestore.instance.collection('date command').snapshots(),
builder: (context, snapshot) {
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot data = snapshot.data.documents[index];
return ListTile(
title: Text(data['output']),
);
},
);
},
)
),
);
}
}
In the above code, all things are the same, only change is in body keyword there we use StreamBuilder.
Let’s understand that
StreamBuilder(
stream: FirebaseFirestore.instance.collection('date command').snapshots(),
builder: (context, snapshot) {
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot data = snapshot.data.documents[index];
return ListTile(
title: Text(data['output']),
);
},
);
},
)
Here we set out the stream to firestore collection name date command. After that we use builder which keep track and as soon as data out will rebuild that part. Inside it we can use list view.
Now from the above code as soon as we change something in the collection date command, it changes in our app in no time.
Below is our firebase as soon as we change something in firebase it will change in the app too.
Below I am providing a Github repo that contain this code as well as the last blog code too so that one can differentiate easily.
I would like to thank Aditya Gupta with whom I have completed this task.