如何将ToggleButtons放置在GridView中

问题描述

我创建了一个具有ToggleButtons的GridView。我能够一次选择一个ToggleButton,但是我需要将ToggleButtons排成3行,因此总共有9个ToggleButtons。为此,我将它们放置在GridView中,但返回时出现错误提示'children.length == isSelected.length':不正确。如下所示。

enter image description here

下面是GridView和ToggleButtons的代码

class Backgrounds extends StatefulWidget {

  @override
  _Backgroundsstate createState() => _Backgroundsstate();
}

class _Backgroundsstate extends State<Backgrounds> {

  List<bool> isSelected;

  void initState() {
    isSelected = [true,false,false];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GridView.count(
      crossAxisCount: 2,children: <Widget> [
        Image.asset('images/image1.png'),Image.asset('images/image2.png'),Image.asset('images/image3.png'),Image.asset('images/image4.png'),Image.asset('images/image5.png'),Image.asset('images/image6.png'),Image.asset('images/image7.png'),Image.asset('images/image8.png'),Image.asset('images/image9.png')
        ].asMap().entries.map((widget) {
    Container(
    height: 100,width: 107,child: ToggleButtons(
    children: [widget.value],onpressed: (int index) {
    setState(() {
    for (int i = 0; i < isSelected.length; i++) {
    isSelected[i] = i == index;
    }
    });
    },isSelected: (isSelected),selectedBorderColor: Color(0xff2244C7),borderWidth: 3,borderRadius: BorderRadius.all(Radius.circular(8)
    ),),);
    }).toList(),);
  }
}

我已附上解决方案的图片

enter image description here

解决方法

您应该在import pulp as p import numpy as np a1=np.array([1000,2000,3000,7000,8000,13000,223000,32000,35000,369000,38000,3885000]) x=p.LpVariable('x',lowBound=5000,cat='Continuous') y=p.LpVariable('y',lowBound=8000,cat='Continuous') Lp_prob=(((y-x)*1.3+x)*0.014428)+((a1-y)*1.5*0.014428) Lp_prob.solve() 的子级中放置9个小部件。切换按钮的子项应具有与isSelected长度相同的小部件数量。另一个问题是,当您在此代码中使用ToggleButtons时,它将生成81个切换按钮,而每9个按钮都位于顶部。我为您提供了以下代码:

GridView