参考juejin.cn/post/727779… 使用Getx实现了一个跑马灯效果
可以看到相比Streambuilder的方式,Getx响应式局部更新,简洁了很多 附上代码
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class TGet extends StatelessWidget {
TGet({super.key});
final sequenceList = [
{
'color': Colors.black,
},
{
'color': Colors.black,
},
{
'color': Colors.black,
},
{
'color': Colors.black,
},
{
'color': Colors.black,
},
{
'color': Colors.black,
},
{
'color': Colors.black,
},
{
'color': Colors.black,
},
{
'color': Colors.black,
},
{
'color': Colors.black,
},
].obs;
Timer? timer;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(''),
),
body: Column(
children: [
Row(
children: [
ElevatedButton(
onPressed: () {
timer = Timer.periodic(Duration(milliseconds: 20), (timer) {
int value = Random().nextInt(10);
if (sequenceList[value]['color'] == Colors.black) {
sequenceList[value]['color'] = Colors.blue;
} else {
sequenceList[value]['color'] = Colors.black;
}
sequenceList.refresh();
});
},
child: Text('开始闪烁')),
ElevatedButton(
onPressed: () {
timer!.cancel();
sequenceList.forEach((element) {
element['color'] = Colors.black;
});
sequenceList.refresh();
},
child: Text('复位')),
],
),
Obx(() => Column(
children: [
for (var item in sequenceList)
Container(
width: 20,
height: 20,
color: item['color'] as Color,
margin: EdgeInsets.only(bottom: 10),
)
],
)),
],
),
);
}
}