【问题标题】:The getter 'length' was called on null, Error in Flutter在 null 上调用 getter 'length',Flutter 中的错误
【发布时间】:2020-04-23 08:20:08
【问题描述】:

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

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

这是从数据库中绘制元素表 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: () {

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

【问题讨论】:

    标签: android flutter dart apk


    【解决方案1】:

    使用连接状态 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();
                      }
                    }),
    
    
    

    【讨论】:

    • 现在屏幕上弹出这个错误:type 'SqfliteDatabaseException' is not a subtype of type 'String'
    • 对不起,我没注意到。写一个错误:SQLITE_ERROR ...没有这样的文件或目录。但是如果我在模拟器中运行调试,那么它不会因为缺少文件而发誓。 database.db 位于 assets/database.db 文件夹中。在 pubspec.yaml 中也注册了这个文件。
    • stackoverflow.com/questions/51384175/… 尝试:目录 appDocDir = await getApplicationDocumentsDirectory(); String databasePath = join(appDocDir.path, 'asset_database.db'); this.db = 等待 openDatabase(databasePath);初始化 = true;
    • 或者 var exists = await databaseExists(path);返回真?
    • Сейчас и в эмуляторе такая же ошибка "没有这样的文件或火药"
    猜你喜欢
    • 2021-08-11
    • 2021-12-10
    • 2021-05-25
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    相关资源
    最近更新 更多