Reputation: 256
I am trying to read the data from firebase after scanning a barcode.
This is how it should appear, but instead of barcode, it should display name and price from the database (https://m.imgur.com/gallery/lEFJZ0Q)
Code:
class ListTileModel {
String barcode;
ListTileModel(this.barcode);
}
the below code is inside the stateful widget
List<ListTileModel> _items = [];
String barcode = "";
void _add() {
_items.add(ListTileModel(barcode));
setState(() {});
}
@override
void initState(){
super.initState();
}
StreamBuiler Used:
new Container(
child: ListView(
children: _items
.map((item) => StreamBuilder(
stream: FirebaseDatabase.instance.reference().child('prd').child(item.barcode).onValue,
builder: (context, snap) {
print(item.barcode);
if(snap.hasData){
DataSnapshot snapshot = snap.data.snapshot;
Map<dynamic, dynamic> itm = snapshot.value;
return snap.data.snapshot.value == null
? SizedBox()
: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.vertical,
itemCount: 1,
itemBuilder: (context, index) {
return Row(
children: <Widget>[
ConstrainedBox(
child: Container(
child: Text(itm[index]['name'],style: TextStyle(fontSize: 20),),
),
),
SizedBox(width: 100,),
ConstrainedBox(
child: Container(
child: Text(itm[index]['price'].toString(),style: TextStyle(fontSize: 20),),
),
),
],
);
},
);
}
else {
return Center(child: CircularProgressIndicator());
}
}
),
).toList()
),
),
The Barcode Scan code:
widget:
floatingActionButton: FloatingActionButton(
onPressed: scan,
child: Icon(Icons.add_shopping_cart),
),
scan() :
Future scan() async{
try{
String barcode = await BarcodeScanner.scan();
setState(() {
this.barcode = barcode;
});
_add();
}on PlatformException catch(e) {
if(e.code == BarcodeScanner.CameraAccessDenied){
setState(() {
this.barcode = 'Access Denied';
});
}
}
I'm am getting following Error:
The following NoSuchMethodError was thrown building: The method '[]' was called on null. Receiver: null Tried calling:
Upvotes: 0
Views: 731
Reputation: 2654
Please try this and let me know if it fixes your problem you need to change
Text(itm[index]['name'],style: TextStyle(fontSize: 20),),
Text(itm[index]['price'].toString(),style: TextStyle(fontSize: 20),),
To
Text(itm['det']['name'],style: TextStyle(fontSize: 20),),
Text(itm['det']['price'].toString(),style: TextStyle(fontSize: 20),),
Let me know if this works for you. I believe the problem is the index also. right now your saying.
Upvotes: 1