繁体   English   中英

在 null 上调用了 getter 'length',Flutter 中的错误

[英]The getter 'length' was called on null, Error in Flutter

我需要在 a.db 数据库中列出一个表。 当我在模拟器中运行应用程序时,会弹出错误“getter 'length' was called on null”一秒钟,然后立即显示我需要的列表。 当您在连接的智能手机上启动调试时,一切都会停止并显示错误“getter 'length' was called on null”。

可能是什么问题呢? 似乎某处没有足够的方法来等待来自数据库的数据。

I/flutter (10923): /data/user/0/com.example.test_project/databases/database.db
I/flutter (10923): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY 
╞═══════════════════════════════════════════════════════════
I/flutter (10923): The following NoSuchMethodError was thrown building 
FutureBuilder<List<Authors>>(dirty, state:
I/flutter (10923): _FutureBuilderState<List<Authors>>#3ecfd):
I/flutter (10923): The getter 'length' was called on null.
I/flutter (10923): Receiver: null
I/flutter (10923): Tried calling: length

数据库.dart

class DBProvider {
  DBProvider._();

  static final DBProvider db = DBProvider._();

  Database _database;

  Future<Database> get database async {

    _database = await initDB();
    return _database;
  }

  initDB() async {
    String path = join(await getDatabasesPath(), "database.db");
    var exists = await databaseExists(path);
    print(path);
    return await openDatabase(path);
  }

  Future<List<Authors>> getAllClients() async {
    final db = await database;
    var res = await db.query('category');
    print(res);
    List<Authors> list = [];
    list = res.map((c) => Authors.fromMap(c)).toList();
    return list;
  }
}

这是 class,其中绘制了来自数据库的元素表的 UI。

class MainTab extends StatefulWidget {
  @override
  _MainTabState createState() => _MainTabState();
}

class _MainTabState extends State<MainTab> {

  @override
  Widget build(BuildContext context) {
      return Padding(
        padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
        child: Container(
            padding: EdgeInsets.all(15),
            decoration: BoxDecoration(
                color: Theme.of(context).accentColor,
                borderRadius: BorderRadius.all(Radius.circular(30))
            ),
            child: FutureBuilder<List<Authors>>(
              future: DBProvider.db.getAllClients(),
              builder: (context, snapshot) {
                return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, index) {
                    Authors item = snapshot.data[index];
                    return ListTile(
                      title: Text(item.name),
                      leading: Icon(Icons.folder),
                      trailing: Text(item.count.toString()),
                      onTap: () {

                      },
                    );
                  },
                );
              },
            )
        ),
      );
    }
}

使用 ConnectionState https://pub.dev/documentation/flutter_for_web/latest/widgets/FutureBuilder-class.html

你必须写这样的东西:

  FutureBuilder<List<Authors>>(
                future: DBProvider.db.getAllClients(),
                builder: (context, snapshot) {
                  switch (snapshot.connectionState) {
                    case ConnectionState.waiting:
                      return Center(
                        child: CircularProgressIndicator(),
                      );
                    case ConnectionState.done:
                      {
                        if (snapshot.hasError) {
                          return Center(
                        child: Text(snapshot.error.toString()),
                         );
                        } else if (snapshot.hasData) {
                           return ListView.builder(
                  itemCount:snapshot.data==null?0: snapshot.data.length,
                  itemBuilder: (context, index) {
                    Authors item = snapshot.data[index];
                    return ListTile(
                      title: Text(item.name),
                      leading: Icon(Icons.folder),
                      trailing: Text(item.count.toString()),
                      onTap: () {

                      },
                    );
                        }
                        return Center(child: Text('No Data'));
                      }
                    default:
                      return Container();
                  }
                }),


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM