我在PageView上工作时使用了一个计时器,它会在3到5秒内自动滑动每一页。下面是我使用的代码:
import 'dart:async';
import 'package:flutter/material.dart';
import '../models/mod_featured.dart';
class WidgetFeatured extends StatefulWidget {
@override
_WidgetFeaturedState createState() => _WidgetFeaturedState();
}
class _WidgetFeaturedState extends State<WidgetFeatured> {
int _currentPage = 0;
final PageController _pageController = PageController(
initialPage: 0,
);
@override
void initState() {
super.initState();
Timer.periodic(
Duration(seconds: 5),
(Timer timer) {
if (_currentPage < featuredList.length) {
_currentPage++;
} else {
_currentPage = 0;
}
_pageController.animateToPage(
_currentPage,
duration: Duration(milliseconds: 300),
curve: Curves.easeIn,
);
},
);
}
@override
void dispose() {
super.dispose();
_pageController.dispose();
}
_onPageChanged(int index) {
setState(() {
_currentPage = index;
});
}
@override
Widget build(BuildContext context) {
return Container(
height: 200,
child: PageView.builder(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
controller: _pageController,
onPageChanged: _onPageChanged,
itemBuilder: (context, index) => WidgetFeaturedItem(index),
itemCount: featuredList.length,
),
);
}
}
class WidgetFeaturedItem extends StatelessWidget {
final int indexItem;
WidgetFeaturedItem(this.indexItem);
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(20),
color: featuredList[indexItem].color,
width: double.infinity,
height: 180,
child: Stack(
children: <Widget>[
Row(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
featuredList[indexItem].header,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
Text(
featuredList[indexItem].subHeader,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
FlatButton(
onPressed: () {},
padding: const EdgeInsets.symmetric(
horizontal: 15,
vertical: 3,
),
color: Theme.of(context).primaryColor,
child: Text(
'Order now',
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w100,
),
),
),
],
),
Image.asset(
featuredList[indexItem].imgUrl,
height: 120,
width: 120,
//width: 335,
fit: BoxFit.cover,
),
],
)
],
),
);
}
}
但是当我运行和调试时,它一直在我的调试控制台上显示这些错误/警告。x1c 0d1x
这些错误/警告导致内存泄漏,可能会降低应用程序的速度?2还是这是正常的?3什么可能导致这些类型的错误/警告?
任何替代解决方案或帮助都非常感谢。谢谢!
3条答案
按热度按时间q5iwbnjs1#
你试过flutter_swiper吗?它有
autoplay
参数,在我看来应该适合你的需要。6vl6ewon2#
首先使用hasClients属性检查scrollController是否已附加到滚动视图。
sxpgvts33#
使用bloc作为状态管理,我创建了以下代码片段:
延迟定时器_定时器和int pageIndex = 0;作为全局变量