Flutter “你能纠正错误吗?”;在声明局部变量之前不能使用它;可以使用异步函数解决吗?
我有一个应用程序,当用户单击一个FAB时,它会添加一个Flutter “你能纠正错误吗?”;在声明局部变量之前不能使用它;可以使用异步函数解决吗?,flutter,sqflite,Flutter,Sqflite,我有一个应用程序,当用户单击一个FAB时,它会添加一个卡小部件。有一个类型为卡的列表,显示在滑动网格中,该网格存储用户添加的卡。我想实现一个delete函数,但当我尝试时,我得到了一个错误“不能在声明局部变量之前使用它”。使用以下代码将卡添加到列表中: int _count = 0; cardList = List.generate(_count, (int i) => new Card( child: ListTile( title: Text(
卡小部件。有一个类型为卡的列表
,显示在滑动网格
中,该网格存储用户添加的卡
。我想实现一个delete函数,但当我尝试时,我得到了一个错误“不能在声明局部变量之前使用它”。使用以下代码将卡添加到列表中:
int _count = 0;
cardList = List.generate(_count, (int i) =>
new Card(
child: ListTile(
title: Text("project 1"),
trailing: new Listener(
key: new Key(UniqueKey().toString()),
child: new Icon(Icons.remove_circle,
color: Colors.redAccent,),
onPointerDown: (pointerEvent) {}
// deleteNoDo(), //this is the delete function
),
),
)
);
使用此代码生成卡
(此按钮在支架下定义)
:
这是删除功能:
deleteNoDo(int index) {
debugPrint("Deleted Item!");
setState(() {
cardList.removeAt(index);
});
}
这是显示卡片列表的滑动网格
:
SliverGrid(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2
),
delegate: new SliverChildBuilderDelegate((context,index) {
return cardList[index]; // this is where the cards are displayed in a list
},
childCount: cardList.length
)
),
问题:如果我使用数据库(CRUD)函数是异步的,那么“不能在声明之前使用局部变量”错误是否可以解决?问题是,您的cardList
变量是本地变量,您试图在没有访问范围的异步回调中访问它。在initState
中声明cardList
,并将其初始化为空列表和内部版本,或者在您希望分配该变量实际值的任何位置,然后在执行删除按钮操作时,您可以访问它
SliverGrid(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2
),
delegate: new SliverChildBuilderDelegate((context,index) {
return cardList[index]; // this is where the cards are displayed in a list
},
childCount: cardList.length
)
),