0

这是我在这里的第一个问题。(所以如果出现任何问题,请告诉我。)

我对 Flutter 很陌生,并试图GridView.count在我的应用程序中应用,但发生了以下错误。

Unhandled Exception: RangeError (index): Invalid value: Not in inclusive range 0..4: 5

我看到ListView有类似的问题,从解决方案中,我试图找到类似的东西itemCountchildCount但没有找到类似的东西。

所以我的代码如下。主要GridView.count是这样调用的:

body: GridView.count(
        crossAxisCount: 2, 
        children: buttons,
      )

和小部件列表,buttonsgetButtonList()功能设置:

List<Widget> buttons = [];

void getButtonList() async { 
List<Map> list = await database.rawQuery('SELECT * FROM test WHERE mom > 2');
for (int i = 0; i < list.length; i++) {
  //print(list[i]['name']);                 //this seems ok
  setState(() {
    buttons.add(RaisedButton(
        onPressed: () {},
        child: Text(list[i]['name']),
      ),
    );
  });
}



// and later in Floating Action Button callback like this

floatingActionButton: FloatingActionButton(
    onPressed: () {
      getButtonList();
    },
  ),

我还尝试从浮动操作按钮返回一个临时列表getButtonList()并将其包裹起来,如下所示:setState

List<Widget> buttons = [];

Future<List<Widget>> getButtonList() async {
List<Widget> temp = [];
List<Map> list = await database.rawQuery('SELECT * FROM test WHERE mom > 2');
for (int i = 0; i < list.length; i++) {
  //print(list[i]['name']);     
  setState(() {
    temp.add(
      RaisedButton(
        onPressed: () {},
        child: Text(list[i]['name']),
      ),
    );
  });
}
return temp;
}



// and Floating Action Button callback like this

floatingActionButton: FloatingActionButton(
  onPressed: () async {
    List<Widget> temp = await getButtonList();
      setState(() {
        buttons = temp;
      });
    },
  ),

仍然显示相同的错误消息。

4

1 回答 1

0

我设法使它工作。我所做的是宣布一个temp列表并更新了该列表。稍后在 setStatetemp中传递给原始buttons.

我认为应该有更好的方法。

无论如何,我目前的工作代码如下:

List<Widget> buttons = [];
List<Widget> temp = [];

void getButtonList() async {
List<Map> list = 
                await database.rawQuery('SELECT * FROM test WHERE mom > 2');
for (int i = 0; i < list.length; i++) {
  print(list[i]['name']);
  buttons.add(
    RaisedButton(
      onPressed: () {},
      child: Text(list[i]['name']),
    ),
  );
}


// and Floating Action Button callback like this

floatingActionButton: FloatingActionButton(
    onPressed: () {
      getButtonList();
      setState(() {
        buttons = temp;
      });
    },
  ),
于 2020-12-16T11:55:06.717 回答