GridView 网格布局组件

  1. import 'package:flutter/material.dart';
  2. import 'data/newList.dart';
  3. void main() => runApp(MyApp());
  4. class MyApp extends StatelessWidget {
  5. @override
  6. Widget build(BuildContext context) {
  7. return MaterialApp(
  8. home: Scaffold(
  9. appBar: AppBar(
  10. title: Text('Welcome to Flutter'),
  11. ),
  12. body: HomeContent(),
  13. ),
  14. theme: ThemeData(
  15. primaryColor: Colors.pink,
  16. ),
  17. );
  18. }
  19. }
  20. class HomeContent extends StatelessWidget {
  21. List _getData() {
  22. var tempList = listData.map((e) {
  23. return Container(
  24. child: Column(
  25. children: [
  26. Image.network(
  27. e['imageUrl'],
  28. width: 300,
  29. height: 100,
  30. fit: BoxFit.cover,
  31. ),
  32. Row(
  33. children: [
  34. Column(
  35. children: [
  36. Text(e['title']),
  37. Text(e['author'])
  38. ],
  39. ),
  40. Text(
  41. '¥400',
  42. textAlign: TextAlign.center,
  43. ),
  44. ],
  45. ),
  46. ],
  47. ),
  48. );
  49. });
  50. return tempList.toList();
  51. }
  52. @override
  53. Widget build(BuildContext context) {
  54. return GridView.count(
  55. padding: EdgeInsets.all(10),
  56. crossAxisCount: 2,
  57. // childAspectRatio: 0.5,
  58. // mainAxisSpacing: 10,
  59. crossAxisSpacing: 20,
  60. children: this._getData(),
  61. );
  62. }
  63. }

子元素的大小是通过crossAxisCountchildAspectRatio两个参数共同决定的,注意,这里的子元素指的是子组件的最大显示空间,注意确保子组件的实际大小不要超出子元素的空间。

利用 GridView.builder 实现布局:

  1. import 'package:flutter/material.dart';
  2. import 'data/newList.dart';
  3. void main() => runApp(MyApp());
  4. class MyApp extends StatelessWidget {
  5. @override
  6. Widget build(BuildContext context) {
  7. return MaterialApp(
  8. home: Scaffold(
  9. appBar: AppBar(
  10. title: Text('Welcome to Flutter'),
  11. ),
  12. body: HomeContent(),
  13. ),
  14. theme: ThemeData(
  15. primaryColor: Colors.pink,
  16. ),
  17. );
  18. }
  19. }
  20. class HomeContent extends StatelessWidget {
  21. Widget _getData(context, index) {
  22. return Container(
  23. child: Column(
  24. children: [
  25. Image.network(
  26. listData[index]['imageUrl'],
  27. width: 300,
  28. height: 100,
  29. fit: BoxFit.cover,
  30. ),
  31. Row(
  32. children: [
  33. Column(
  34. children: [
  35. Text(listData[index]['title']),
  36. Text(listData[index]['author'])
  37. ],
  38. ),
  39. Text(
  40. '¥400',
  41. textAlign: TextAlign.center,
  42. ),
  43. ],
  44. ),
  45. ],
  46. ),
  47. );
  48. }
  49. @override
  50. Widget build(BuildContext context) {
  51. return GridView.builder(
  52. gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
  53. crossAxisCount: 2,
  54. crossAxisSpacing: 10,
  55. mainAxisSpacing: 10,
  56. ),
  57. itemCount: listData.length,
  58. itemBuilder: this._getData,
  59. );
  60. }
  61. }