flutter组件之GridView.builder()

2021-08-02 10:33:17 浏览数 (1)

如果您的 Flutter 应用程序需要显示大量或无限数量项目的网格视图(例如,从 API 获取的产品列表),那么您应该使用GridView.builder()而不是GridView()。该生成器()只为那些确实可见,所以您的应用程序的性能将得到改善

例子

步骤:

  1. 生成一个包含 100.000 个虚拟产品的列表:
代码语言:javascript复制
final List<Map> myProducts =
      List.generate(100000, (index) => {"id": index, "name": "Product $index"})
          .toList();

通过使用GridView.builder(),我们将在渲染像这样的超大列表时摆脱滞后。

2.实现网格视图:

代码语言:javascript复制
GridView.builder(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                maxCrossAxisExtent: 200,
                childAspectRatio: 3 / 2,
                crossAxisSpacing: 20,
                mainAxisSpacing: 20),
            itemCount: myProducts.length,
            itemBuilder: (BuildContext ctx, index) {
              return Container(
                alignment: Alignment.center,
                child: Text(myProducts[index]["name"]),
                decoration: BoxDecoration(
                    color: Colors.amber,
                    borderRadius: BorderRadius.circular(15)),
              );
            }),

截屏:

完整代码

main.dart 中的完整源代码:

代码语言:javascript复制
import 'package:flutter/material.dart';
​
void main() {
  runApp(MyApp());
}
​
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomeScreen(),
    );
  }
}
​
class HomeScreen extends StatelessWidget {
  final List<Map> myProducts =
      List.generate(100000, (index) => {"id": index, "name": "Product $index"})
          .toList();
​
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: GridView.builder(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                maxCrossAxisExtent: 200,
                childAspectRatio: 3 / 2,
                crossAxisSpacing: 20,
                mainAxisSpacing: 20),
            itemCount: myProducts.length,
            itemBuilder: (BuildContext ctx, index) {
              return Container(
                alignment: Alignment.center,
                child: Text(myProducts[index]["name"]),
                decoration: BoxDecoration(
                    color: Colors.amber,
                    borderRadius: BorderRadius.circular(15)),
              );
            }),
      ),
    );
  }
}

结论

恭喜!在这一点上,您应该对在您的应用程序中实现 GridView 有更好的理解并感到更自在

0 人点赞