【问题标题】:How to access data from mongodb using flutter app如何使用颤振应用程序从 mongodb 访问数据
【发布时间】:2020-01-16 16:48:25
【问题描述】:

我正在构建一个条形码阅读器,它会在扫描产品的条形码后显示产品的名称。名称和条形码存储在 mongodb 中,我编写了此代码用于连接数据库:


    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;
        }

并且我使用了future builder来显示名称:

    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,
            );
          });}
           },)

它一直显示加载文本。

【问题讨论】:

  • 嗨,Dami,您的意思是 snapshot.data enter code here == null 还是格式错误?
  • 另外,我认为这可能只是您的 prod 函数中未捕获的错误。尝试用if (snapshot.hasError) throw snapshot.error; if (!snapshot.hasData) {/* */} 替换您的if (snapshot.data == null) /* ... */,看看是否抛出错误

标签: flutter mongo-dart


【解决方案1】:

它在(windows os)之后工作: - 服务 -> MongoDB 服务器属性 -> 启动类型:将其更改为手动。 并在 cmd 中运行 mongod --bind_ip_all。 我已经将我的代码编辑为:

 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]}'),
            ]);
      }}

  )

【讨论】:

  • 您好,我也面临同样的问题。请您详细说明一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 2018-11-07
  • 2020-12-23
  • 1970-01-01
  • 2021-06-09
  • 2019-05-15
  • 1970-01-01
相关资源
最近更新 更多