Home > database >  How to use GridView to optimize my code? - Flutter
How to use GridView to optimize my code? - Flutter

Time:10-05

I would like to organize this code using GridView (I think it's the best option in this case) but I'm having trouble with it. I have 16 results named from result1, result2 ... result16 and I would like to organize it like 4x4 just like the image below:

enter image description here

Here's a small part of the code:

child: RichText(
            text: TextSpan(
              children: [
                TextSpan(
                  text: widget.result1   '  ',
                  style: TextStyle(
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold,
                    color: checkdominantA(widget.predominant, widget.result1),
                    height: 2.5,
                    letterSpacing: 0.7,
                  ),

                    // ...

                  TextSpan(
                  text: widget.result16   '  ',
                  style: TextStyle(
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold,
                    color: checkdominantA(widget.predominant, widget.result16),
                    height: 2.5,
                    letterSpacing: 0.7,
                  ),
                ),
                  
                ),
              ],
            ),
          ),

CodePudding user response:

Building Gridview is quite straight forward, just follow this tutorial, GridView:

GridView.builder(
  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
    mainAxisSpacing: 5.0,
    crossAxisSpacing: 5.0,
    crossAxisCount: 4,
    childAspectRatio: 1,
  ),
  itemCount: 16,
  itemBuilder: (BuildContext context, int index) {
    return Text(
              '$index',
              style: TextStyle(
                fontSize: 20.0,
                fontWeight: FontWeight.bold,
                height: 2.5,
                letterSpacing: 0.7,
              );
  }
),

CodePudding user response:

Per the GridView documentation:

GridView.count(
  primary: false,
  padding: const EdgeInsets.all(20),
  crossAxisSpacing: 10,
  mainAxisSpacing: 10,
  crossAxisCount: 4,  // 4 tiles horizontally
  children: <Widget>[
    TextSpan(text: widget.result1   '  '),
    TextSpan(text: widget.result2   '  ')
    // ...
  ],
)
  • Related