gpt4 book ai didi

android - ListView 无限构建项目

转载 作者:IT王子 更新时间:2023-10-29 06:58:09 25 4
gpt4 key购买 nike

我写了一个 Flutter ListView 演示,我希望 ListView 自动滚动到最后一张图片,然后返回到第一个,对于我放的演示2 张图片,调试时一切正常,ListView 显示无限项。但是,当涉及到发布版本时,它会无限地构建项目。

如其所示,它确实适用于调试。

enter image description here

import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_demo_module/screenutil.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
theme: ThemeData(
primaryColor: Colors.white,
),
home: _InfiniteGallery(),
);
}
}

class _InfiniteGallery extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new _InfiniteGalleryState();
}
}

class _InfiniteGalleryState extends State<_InfiniteGallery> {
ListView list;
ScrollController _controller;
List<Image> cache = List();

Widget _buildItem(index) {
print("build item $index");
final imageIndex = index % 2;
if (cache.length <= imageIndex) {
Image image = Image.asset(
'images/welcome_banner_$imageIndex.jpg',
height: ScreenUtil.getInstance().setWidth(367),
width: ScreenUtil.getInstance().setWidth(305),
);
cache.add(image);
}
return cache[imageIndex];
}

Widget _buildSuggestions() {
list = ListView.builder(
controller: _controller,
shrinkWrap: true,
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.all(0),
itemBuilder: (context, i) {
return _buildItem(index);
},
);
return list;
}

@override
Widget build(BuildContext context) {
ScreenUtil(width: 375).init(context);
final titleStyle = TextStyle(
fontSize: 14.0,
color: Colors.deepOrangeAccent,
);
return Scaffold(
appBar: AppBar(
brightness: Brightness.light,
title: Text(
"Startup Name Generator11",
style: titleStyle,
),
actions: <Widget>[
new IconButton(icon: const Icon(Icons.library_add), onPressed: null),
],
),
body: Column(
children: <Widget>[
Container(
height: ScreenUtil.getInstance().setWidth(367),
child: _buildSuggestions(),
),
],
),
);
}
}

这是发布日志:

I/flutter (16705): build item 43693
I/flutter (16705): build item 43694
I/flutter (16705): build item 43695...

最佳答案

添加 itemCount

您没有为 ListView 指定 itemCount,您需要添加一个 itemCount = non-null。

Widget _buildSuggestions() {
list = ListView.builder(
controller: _controller,
shrinkWrap: true,
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.all(0),

itemCount: 5,// your count here

itemBuilder: (context, i) {
return _buildItem(index);
},
);
return list;
}

关于android - ListView 无限构建项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54922412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com