Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ms-access/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter “你能纠正错误吗?”;在声明局部变量之前不能使用它;可以使用异步函数解决吗?_Flutter_Sqflite - Fatal编程技术网

Flutter “你能纠正错误吗?”;在声明局部变量之前不能使用它;可以使用异步函数解决吗?

Flutter “你能纠正错误吗?”;在声明局部变量之前不能使用它;可以使用异步函数解决吗?,flutter,sqflite,Flutter,Sqflite,我有一个应用程序,当用户单击一个FAB时,它会添加一个卡小部件。有一个类型为卡的列表,显示在滑动网格中,该网格存储用户添加的卡。我想实现一个delete函数,但当我尝试时,我得到了一个错误“不能在声明局部变量之前使用它”。使用以下代码将卡添加到列表中: int _count = 0; cardList = List.generate(_count, (int i) => new Card( child: ListTile( title: Text(

我有一个应用程序,当用户单击一个FAB时,它会添加一个
小部件。有一个类型为
卡的列表
,显示在
滑动网格
中,该网格存储用户添加的
。我想实现一个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
       )
    ),