Флаттер: просмотр страницы с таймером - PullRequest
0 голосов
/ 27 апреля 2020

Я работаю над 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,
              ),
            ],
          )
        ],
      ),
    );
  }
}

но когда я запускаю и отлаживаю. эти ошибки и предупреждения отображаются на моей консоли отладки. Debug Console Image

эти ошибки / предупреждения вызывают утечки памяти, которые могут замедлить работу приложения? или это нормально? Что может вызвать такие ошибки / предупреждения?

Любые альтернативные решения или помощь очень ценится. Спасибо!

1 Ответ

0 голосов
/ 27 апреля 2020

Вы пробовали flutter_swiper ? У него есть параметр autoplay, и мне кажется, что он должен соответствовать вашим потребностям.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...