Currently it is a listview, I know how to normally create a listview.builder but I don't know how to connect it to firebase. Im talking about the streambuilder and context and all that stuff. Really appreciate any help, Im new to flutter so sorry if this is an obvious/dumb question.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(FireApp());
}
class FireApp extends StatefulWidget {
@override
_FireAppState createState() => _FireAppState();
}
class _FireAppState extends State<FireApp> {
final TextController = TextEditingController();
bool isChecked = false;
@override
Widget build(BuildContext context) {
CollectionReference groceries =
FirebaseFirestore.instance.collection('groceries');
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: TextField(
controller: TextController,
),
),
body: Center(
child: StreamBuilder(
stream: groceries.orderBy('name').snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
return ListView(
children: snapshot.data!.docs.map((grocery) {
return Center(
child: Row(
children: [
Container(color: Colors.red,height: 50,child: Text(grocery['name'])),
Checkbox(
materialTapTargetSize: MaterialTapTargetSize.padded,
value: isChecked,
activeColor: Colors.black,
checkColor: Colors.greenAccent,
onChanged: (bool) {
setState(() {
isChecked = !isChecked;
});
}
)],
),
);
}).toList(),
);
},
),
),
floatingActionButton: FloatingActionButton(onPressed: () {
groceries.add({
'name': TextController.text,
});
},),
),
);
}
}
CodePudding user response:
Just i shared a structure of ListView.builder
, you can follow it
ListView.builder(
itemCount: snapShot.data.length,
itemBuilder: (context, i) {
return snapShot.hasData
? ListTile( // changes required as you need
title: Text(snapShot.data[i].['name']),
)
: Container(
height: 0,
width: 0,
);
},
)
CodePudding user response:
StreamBuilder and listview.builder sample code given below
StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
stream: groceries.orderBy('name').snapshots(),
builder: (context,
AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
// your list of groceries
List groceriesList =
snapshot.data.docs.map((e) => e.data()).toList();
return ListView.builder(
itemCount: groceriesList.length,
itemBuilder: (context, i) {
// build your widget here.
return Center(
child: Row(
children: [
Container(
color: Colors.red,
height: 50,
child: Text(groceriesList[i]['name']),
),
Checkbox(
materialTapTargetSize: MaterialTapTargetSize.padded,
value: isChecked,
activeColor: Colors.black,
checkColor: Colors.greenAccent,
onChanged: (bool) {
setState(() => isChecked = !isChecked);
},
)
],
),
);
},
);
},
),