Flutter中await异步函数始终返回null问题求助
问题分析与解决
你的addDance函数存在核心逻辑错误——没有返回数据库事务中创建的Dance实例,导致调用方始终拿到null。
错误原因
db.transaction的回调函数里已经成功创建Dance并返回,但外层的addDance函数在执行完事务后,直接固定返回null,完全忽略了事务的返回结果。这就是为什么日志显示Dance实例已创建,但调用方拿到的还是null。
修复后的代码
修改addDance函数,接收事务的返回值并最终返回:
Future<Dance?> addDance (String name, int numDancers, List<String> positions, String note) async { debugPrint ("Add dance $name") ; Database db = (await database)! ; // 接收事务的返回结果 Dance? result = await db.transaction((txn) async { var raw = await txn.rawInsert('INSERT INTO dances (name, numPlaces, active, note) VALUES (?,?,?,?)', [name,numDancers,1,note] ) ; int id = raw.toSigned(64); if (id > 0) { StringBuffer sql = new StringBuffer ("INSERT INTO positions (dance, position, name) VALUES ") ; bool first = true ; for (int i = 0 ; i < positions.length ; ++i) { if (first) first = false ; else sql.write (", ") ; sql.write ("($id,$i,'") ; sql.write (positions[i]) ; sql.write ("')") ; } await txn.rawInsert (sql.toString ()) ; Dance d = new Dance (id, name, numDancers, true, note) ; d.positionsNames = positions ; debugPrint ("Created dance id $id") ; return d ; } else return null ; }) ; // 返回事务的结果,而不是固定返回null return result; }
额外优化
原代码中d == null ? debugPrint ("dance null") : debugPrint ("dance not null")这段判断完全多余,因为你刚刚通过new Dance()创建了实例,不可能为null,可以直接删掉。
内容的提问来源于stack exchange,提问作者Andy.L
相关产品推荐
相关产品推荐

