Last active
June 18, 2025 10:12
-
-
Save lukaswhite/67325899d822357d2468f15825843d6f to your computer and use it in GitHub Desktop.
Traffic Light
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'package:flutter/material.dart'; | |
import 'package:flutter_bloc/flutter_bloc.dart'; | |
import 'package:equatable/equatable.dart'; | |
void main() => runApp(const MyApp()); | |
sealed class TrafficLightState extends Equatable { | |
@override | |
List<Object?> get props => []; | |
} | |
final class TrafficLightGo extends TrafficLightState {} | |
final class TrafficLightGetReady extends TrafficLightState {} | |
final class TrafficLightStopIfSafe extends TrafficLightState {} | |
final class TrafficLightStop extends TrafficLightState {} | |
class TrafficLightCubit extends Cubit<TrafficLightState> { | |
TrafficLightCubit() : super(TrafficLightGo()) { | |
Timer.periodic(const Duration(milliseconds: 1000), (_) { | |
if (state is TrafficLightGo) { | |
emit(TrafficLightStopIfSafe()); | |
} else if (state is TrafficLightStopIfSafe) { | |
emit(TrafficLightStop()); | |
} else if (state is TrafficLightStop) { | |
emit(TrafficLightGetReady()); | |
} else if (state is TrafficLightGetReady) { | |
emit(TrafficLightGo()); | |
} | |
}); | |
} | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Counter App', | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData(colorSchemeSeed: Colors.blue), | |
home: BlocProvider( | |
create: (context) => TrafficLightCubit(), | |
child: const MyHomePage(title: 'Traffic Light'), | |
), | |
); | |
} | |
} | |
class MyHomePage extends StatelessWidget { | |
const MyHomePage({super.key, required this.title}); | |
final String title; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: Text(title)), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
BlocBuilder<TrafficLightCubit, TrafficLightState>( | |
builder: (context, state) { | |
return Column( | |
children: [ | |
CircleAvatar( | |
radius: 30, | |
backgroundColor: (state is TrafficLightStop || state is TrafficLightGetReady) ? Colors.red : Color(0xff999999) | |
), | |
CircleAvatar( | |
radius: 30, | |
backgroundColor: (state is TrafficLightGetReady || state is TrafficLightStopIfSafe) ? Colors.amber : Color(0xff999999), | |
), | |
CircleAvatar( | |
radius: 30, | |
backgroundColor: (state is TrafficLightGo) ? Colors.green : Color(0xff999999) | |
), | |
] | |
); | |
}, | |
), | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment