【问题标题】:Flutter error in GridView.count : Invalid value: Not in inclusive range 0..4: 5GridView.count 中的颤振错误:无效值:不在包含范围内 0..4:5
【发布时间】:2021-03-27 01:12:21
【问题描述】:

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

我是 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;
      });
    },
  ),

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

【问题讨论】:

    标签: flutter gridview


    【解决方案1】:

    我设法让它工作。我所做的是声明了一个temp 列表并更新了该列表。稍后在 setState 中将temp 传递给原来的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;
          });
        },
      ),
    

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 2019-05-26
      • 2021-10-21
      • 2019-05-11
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2021-12-23
      相关资源
      最近更新 更多