我写了一个Flutter ListView
演示,我希望ListView
自动滚动到最后一张图片,然后回到第一张,为演示我放了2张图片,一切都很好调试,ListView
显示无限项目。但是,当发布版本时,它会不断地构建项目。
如图所示,它确实适用于调试。
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
您没有将itemCount指定为ListView,您需要添加itemCount =非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;
}