我在等待 Future 结果时遇到了问题。我有一个返回 Future 的函数,我使用 await 函数调用它,但我得到的结果始终为 null,即使调试显示它不为 null。这一切都是由单击按钮驱动的。
首先是按钮:
new FilledButton(
child: Text('Copy ${Config.dance}'),
onPressed: () async
{
NamePos? np = await DancePage.getDanceName (context, dance.name + " - Copy", dance.numDancers, dance.numMusicians) ;
if (np != null && np.name.isNotEmpty && np.numPos > 0)
{
// Make a copy of the position names
List<String> pos = List<String>.filled(np.numPos + np.numMusicians, "") ;
for (int i = 0 ; i < np.numPos ; ++i)
{
if (i < dance.numDancers)
pos[i] = dance.positionsNames[i] ;
else
pos[i] = (i + 1).toString() ;
}
int m = 1 ;
int p = dance.numDancers ;
for (int i = np.numPos ; i < pos.length ; ++i, ++m, ++p)
{
if (p < dance.numPositions)
pos[i] = dance.positionsNames[p] ;
else
pos[i] = "Musician " + m.toString() ;
}
// Create a new dance based on the source one
Dance? nd = await DBServer.instance.addDance(np.name, np.numPos, pos, dance.note);
if (nd != null)
{
// copy dancer positions
debugPrint ("Copying dancers") ;
for (Dancer a in Dancer.allDancers(true, Dancer.sBoth))
{
if (a.canDoDance (dance.id))
{
DancePositions pos = new DancePositions(nd.numPositions) ;
List<int> can = a.getPositions (dance.id)!.getAllPositions () ;
for (int p = 0 ; p < nd.numPositions && p < dance.numPositions ; ++p)
{
if (can[p] > 0)
{
pos.setPosition(p, can[p]) ;
}
}
a.setPositions(nd.id, pos) ;
await DBServer.instance.addDancerPositions(a, nd.id);
}
}
}
else
debugPrint ("addDance returned null") ;
Dance.notify() ;
Navigator.of(context).pop(null);
}
}),
出错的部分是调用 addDance。这总是打印调试“addDance 返回 null”
这是 addDance 函数:
Future<Dance?> addDance (String name, int numDancers, List<String> positions, String note) async
{
debugPrint ("Add dance $name") ;
Database db = (await database)! ;
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 ("')") ;
}
// debugPrint (sql) ;
await txn.rawInsert (sql.toString ()) ;
Dance d = new Dance (id, name, numDancers, true, note) ;
d.positionsNames = positions ;
debugPrint ("Created dance id $id") ;
d == null ? debugPrint ("dance null") : debugPrint ("dance not null") ;
return d ;
}
else
return null ;
}) ;
return null ;
}
我得到的调试看起来像:
I/flutter (14661): Created dance id 36
I/flutter (14661): dance not null
D/InsetsController(14661): show(ime(), fromIme=true)
I/flutter (14661): addDance returned null
有人能指出我做错了什么吗?