How can I dynamically change the background color of my Flutter app based on the last digit of the current epoch time ?
Flutter Tutorial:
Install Flutter in Win/Linux/Mac
Flutter Widgets:
Bottom Navigation Bar in Flutter
Auto Close Keyboard in Flutter
Screen size handling in Flutter
Flutter REST API
Flutter Advance
Wrap vs Builder vs OverBarFlow
Circular progress contain Icon
Flutter State management Comparison
Flutter Database
Flutter Token Expired Handling
Flutter Provider
Flutter GetX
Flutter with Native
Flutter Tips
Interview Questions
Dynamic Color Options in Flutter with respect to time
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// In this case we are using switch case which validate automatically based on seconds
Color getDynamicColor() {
int lastDigitOfEpoch = DateTime.now().millisecondsSinceEpoch % 10;// output in 0 to 9 based on that color change
// In this we use 0 to 9 cases because mod of any number with 10 lies between (0 to 9)
switch (lastDigitOfEpoch) {
case 0:
return Colors.red;
case 1:
return Colors.blue;
case 2:
return Colors.green;
case 3:
return Colors.orange;
case 4:
return Colors.purple;
case 5:
return Colors.yellow;
case 6:
return Colors.teal;
case 7:
return Colors.pink;
case 8:
return Colors.indigo;
case 9:
return Colors.brown;
default:
return Colors.black;
}
}
@override
Widget build(BuildContext context) {
// here we call methods which give output with respect to the time
final dynamicColor = getDynamicColor();
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Dynamic Color Example'),
backgroundColor: dynamicColor, // Here the background color change automatically
),
body: Center(
child: Container(
color: dynamicColor, // here container color also change
child: Text(
'Hello, Flutter!',
style: TextStyle(color: Colors.white),
),
),
),
),
);
}
}
In this, LastDigitOfEpoch is calculated by taking the last digit of the current epoch time, i.e. it checks the seconds and through mod output will be 0 to 9, then the switch statement uses this value and returns the color. Thus, the color will change depending on the last digit of the epoch time.
If you face any issue, please comment below, we will reply soon