如何让gridview在Flutter中水平滚动时FixedCrossAxisCount适合宽度?

问题描述 投票:0回答:1
class GridViewCalendar extends StatelessWidget {
  const GridViewCalendar({super.key, required this.monthData});
  final Map<String, dynamic> monthData;

  @override
  Widget build(BuildContext context) {
    return Container(
        margin: const EdgeInsets.all(6),
        child: GridView.builder(
          // scrollDirection: Axis.horizontal,
          physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          gridDelegate: GridViewCalendarDelegate(
            monthData: monthData,
            crossAxisCount: 6,
          ), // 1 column for weekday names, 5 for dates
          itemCount: 42, // 7 * 6
          itemBuilder: (BuildContext context, index) {
            return Container(
              decoration: BoxDecoration(
                border: Border.all(width: 1, color: Colors.deepPurple),
                // color: Colors.blue[100 * ((index % 6) + 1)],
              ),
              child: Center(child: Text('$index')),
            );
          },
        ));
  }
}

class GridViewCalendarDelegate
    extends SliverGridDelegateWithFixedCrossAxisCount {
  GridViewCalendarDelegate({
    required this.monthData,
    required super.crossAxisCount,
    super.mainAxisSpacing = 3,
    super.crossAxisSpacing = 3,
    super.childAspectRatio = 1,
  });

  final Map<String, dynamic> monthData;
}

垂直滚动时,网格视图可以很好地适应屏幕宽度。 但是当我更改滚动水平时,网格视图会扩展到屏幕高度,并且某些单元格会被隐藏。

如何强制 gridview 水平滚动但仍适合屏幕宽度?我真的不关心身高。

flutter gridview
1个回答
0
投票

如果这对您有用,请尝试一下:

Widget build(BuildContext context) {
        return Column(
          children: [
            Expanded(
              child: Container(
                  margin: const EdgeInsets.all(6),
                  child: GridView.builder(
                    scrollDirection: Axis.horizontal,
                    // physics: const NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                    gridDelegate: GridViewCalendarDelegate(
                      monthData: {},
                      crossAxisCount: 6,
                    ), // 1 column for weekday names, 5 for dates
                    itemCount: 42, // 7 * 6
                    itemBuilder: (BuildContext context, index) {
                      return Container(
                        decoration: BoxDecoration(color: Colors.teal,
                          border: Border.all(width: 1, color: Colors.deepPurple),
                          // color: Colors.blue[100 * ((index % 6) + 1)],
                        ),
                        child: Center(child: Text('$index')),
                      );
                    },
                  )),
            ),
            Container(height: 390,)
          ],
        );
      }
© www.soinside.com 2019 - 2024. All rights reserved.