You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter报错NoSuchMethodError:调用null的then方法,求原因及解决

解决Flutter中NoSuchMethodError: 'then' Dynamic call of null错误

你遇到的这个错误根源很明确:DatabaseService类里的verifyuser方法没有返回值(默认返回null),但你在_getLogin方法里尝试对它的返回值调用.then(),null对象自然没有then方法,所以抛出这个错误。

下面是具体的修复步骤和优化建议:

第一步:完善verifyuser方法的实现

首先要让verifyuser返回Future<bool>,因为查询数据库是异步操作,必须用Future包裹结果。修改Database.dart中的verifyuser方法:

Future<bool> verifyuser(String user, String pass) async {
  final db = await database;
  // 查询login表中是否存在匹配的用户(注意表字段是username,和你输入的email要对应,可根据实际需求调整字段名)
  final result = await db.query(
    'login',
    where: 'username = ? AND password = ?',
    whereArgs: [user, pass],
  );
  // 查询结果不为空则说明用户存在,返回true
  return result.isNotEmpty;
}

第二步:修正_getLogin方法的异步逻辑

原代码混用await和.then()容易混淆,且依赖了null的返回值,现在调整为更清晰的异步处理方式:

Future<List<Logindata>> _getLogin() async {
  // 直接await获取verifyuser的返回结果
  bool isValid = await _databaseService.verifyuser(email, pass);
  
  if (isValid) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Login successful!'),
        content: const Text('Welcome!'),
        actions: [
          TextButton(
            onPressed: () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => const HomePage()),
            ),
            child: const Text('OK'),
          ),
        ],
      ),
    );
  } else {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Error!'),
        content: const Text('Wrong Email or Password'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('OK'),
          ),
        ],
      ),
    );
  }
  return _login;
}

额外优化建议

  • FlatButton已被Flutter废弃,建议替换为ElevatedButton或TextButton,比如登录按钮可以改成:
ElevatedButton(
  onPressed: () {
    if (_formKey.currentState!.validate()) {
      email = emails.text;
      pass = password.text;
      _getLogin();
      print(email);
      print(pass);
      print('success');
    }
  },
  child: const Text("Login"),
  style: ElevatedButton.styleFrom(
    backgroundColor: Colors.deepPurple[400],
    foregroundColor: Colors.white,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(10),
    ),
    minimumSize: Size(MediaQuery.of(context).size.width, 50),
  ),
)
  • 目前_login列表是空的,后续如果需要从数据库获取用户详情,可以在verifyuser或单独的方法中查询并返回对应的Logindata对象。

内容的提问来源于stack exchange,提问作者nur wyna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:25:17