1

I'm building a barcode reader, which displays the name of the product after scanning its barcode. The names and the barcodes are stored in mongodb, I wrote this code for connecting to the data base:


    Future<Map> prod() async {
        Db db = Db('mongodb://192.168.2.5:27017/database');
        await db.open();
        DbCollection coll = db.collection('products');
        var information = await coll.findOne(where.eq('code', _Barcode));
        await db.close();
        return information;
        }

and I used future builder to display the name:

    FutureBuilder(
     future: prod(),
     builder: (buildContext, AsyncSnapshot snapshot) {
       if ( snapshot.data== null){
       return Container(
           child: Center(
               child: Text("Loading..."),
                        ),
     );} else{
       return ListView.builder(
       itemCount: snapshot.data.length,
       itemBuilder: (buildContext, int index) {
       return Container(
       child:snapshot.data.name,
            );
          });}
           },)

It keeps showing loading text.

Dami Qay
  • 43
  • 1
  • 8
  • Hi Dami, did you mean to have `snapshot.data enter code here == null` or is that a formatting mistake? – Nolence Jan 16 '20 at 20:07
  • Also, I think it might just be an uncaught error inside your `prod` function. Try replacing your `if (snapshot.data == null) /* ... */` with `if (snapshot.hasError) throw snapshot.error; if (!snapshot.hasData) {/* */}` and see if you get an error thrown – Nolence Jan 16 '20 at 20:16

1 Answers1

1

It works after (windows os): - services -> MongoDB Server Properties -> Start up type: changing it to Manual. and running mongod --bind_ip_all in cmd. And I've edited my code to be:

 Future getInfo() async {
    Db db = Db('mongodb://192.168.2.5:27017/thuDb');
    await db.open();

    print('Connected to database');

    DbCollection coll = db.collection('products');
    var information = await coll.findOne(where.eq('code', _scanBarcode));
    await db.close();
    List<String> r=[information['code'],information['name']] ;
    return r;
  }
/*.......
.......*/

 FutureBuilder(
  future: getInfo(),
  builder: (buildContext, AsyncSnapshot snapshot) {
    if (snapshot.hasError) throw snapshot.error;  
          else if (!snapshot.hasData){
          return Container(
            child: Center(
              child: Text("Waiting..."),
            ),
          );
          }
  else{
    return ListView(
            children:<Widget>[
            Text('Result: ${snapshot.data[0]}'),
            Text('Result: ${snapshot.data[1]}'),
            ]);
      }}

  )
Dami Qay
  • 43
  • 1
  • 8