Flutter学习-定时器

import 'dart:async';

import 'package:flutter/material.dart';

//实现页面定时交替显示红黑两色的效果
class AlarmPage extends StatefulWidget {
  @override
  _AlarmPageState createState() => _AlarmPageState();
}

class _AlarmPageState extends State<AlarmPage> {
  Timer _timer;
  final _colorList = [
    Colors.red,
    Colors.black,
  ];
  int _index = 0;

  _showTimer() {
    _timer = Timer.periodic(Duration(milliseconds: 250), (t) {
    //需要执行的内容
      setState(() {
        _index++;
        if(_index==2) _index=0;
      });
      //t.cancel();		//根据需要停止定时器
    });
  }

  @override
  Widget build(BuildContext context) {
    print('in the AlarmPage');
    _showTimer();
    return Container(
        color: _colorList[_index],
    );
  }

  @override
  void dispose() {			//类似c++中的析构函数
    // TODO: implement dispose
    _timer?.cancel();		//页面销毁时取消定时器(不为null时)
    super.dispose();
  }
}

你可能感兴趣的:(Flutter)