在上篇随笔《Flutter 画圆环。增加按钮让颜色动起来》的基础上增加如下代码
import 'dart:async';
Timer? _timer; // 初始化定时器 void _initTimer() { _timer = Timer.periodic(const Duration(milliseconds: 500), (timer) { _changeColor(); }); } // 改变颜色 void _changeColor() { setState(() { _index++; }); } @override void initState() { super.initState(); _initTimer(); } @override void dispose() { _timer?.cancel(); super.dispose(); }
完整代码如下:
import 'package:flutter/material.dart'; import 'dart:async'; void main() => runApp(const My2App()); class My2App extends StatelessWidget { const My2App({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Hello World', home: CircleWidget(), ); } } class CircleWidget extends StatefulWidget { const CircleWidget({Key? key}) : super(key: key); @override _CircleWidgetState createState() => _CircleWidgetState(); } class _CircleWidgetState extends State<CircleWidget> { final _colorList = [Colors.black, Colors.red, Colors.orange, Colors.blue, Colors.white]; var _index = 0; Timer? _timer; // 初始化定时器 void _initTimer() { _timer = Timer.periodic(const Duration(milliseconds: 500), (timer) { _changeColor(); }); } // 改变颜色 void _changeColor() { setState(() { _index++; }); } @override void initState() { super.initState(); _initTimer(); } @override void dispose() { _timer?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Stack( children: [ TextButton( onPressed: _changeColor, child: const Text('变换颜色'), ), Align( alignment: AlignmentDirectional.center, child: CircleAvatar( radius: 300, backgroundColor: _colorList[(_index + 4) % 5], ), ), Align( alignment: AlignmentDirectional.center, child: CircleAvatar( radius: 250, backgroundColor: _colorList[(_index + 3) % 5], ), ), Align( alignment: AlignmentDirectional.center, child: CircleAvatar( radius: 200, backgroundColor: _colorList[(_index + 2) % 5], ), ), Align( alignment: AlignmentDirectional.center, child: CircleAvatar( radius: 150, backgroundColor: _colorList[(_index + 1) % 5], ), ), Align( alignment: AlignmentDirectional.center, child: CircleAvatar( radius: 100, backgroundColor: _colorList[(_index + 0) % 5], ), ), ], ); } }
运行效果(颜色会自动变换,每500毫秒变换一次)