Output Screenshot
SOLUTION
1. The computeLuminance() method from the Color class.
Text(
'Hello',
style: TextStyle(
fontSize: 80,
color: _backgroundColor.computeLuminance() > 0.5
? Colors.black
: Colors.white),
),
2. The estimateBrightnessForColor() method from the ThemeData class.
Text(
'Hello',
style: TextStyle(
fontSize: 80,
color: ThemeData.estimateBrightnessForColor(_bgColor) ==
Brightness.light
? Colors.black
: Colors.white),
),
The Complete Code
// main.dart
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
// Remove the debug banner
debugShowCheckedModeBanner: false,
title: 'Kindacode.com',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
// Background color of the box
// In the beginning, it is blue
Color _bgColor = Colors.blue;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Kindacode.com'),
),
body: Column(
children: [
const SizedBox(
height: 50,
),
Container(
width: 300,
height: 300,
color: _bgColor,
child: Center(
child: Text(
'Hello',
style: TextStyle(
fontSize: 80,
color: _bgColor.computeLuminance() > 0.5
? Colors.black
: Colors.white),
),
),
),
const SizedBox(
height: 50,
),
// The buttons below used to change the box color
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
// Green Acent
MaterialButton(
onPressed: () {
setState(() {
_bgColor = Colors.greenAccent;
});
},
color: Colors.greenAccent,
),
// Orange
MaterialButton(
onPressed: () {
setState(() {
_bgColor = Colors.orange;
});
},
color: Colors.orange,
),
// Yellow
MaterialButton(
onPressed: () {
setState(() {
_bgColor = Colors.yellow;
});
},
color: Colors.yellow,
),
// Black
MaterialButton(
onPressed: () {
setState(() {
_bgColor = Colors.black;
});
},
color: Colors.black,
)
],
)
],
),
);
}
}
Full Summary:
Step1: assign variable
` Color _bgColor = Colors.blue;
@override
Widget build(BuildContext context) `
Step2:For upper image
body: Column----Container---child: Center-----child: Text
Step3:For below image
row(MainAxisAlignment.spaceAround)---children---four materialButton---
step 4:inside materialButton---set _bgColor = Colors.yellow
Refrence
Click here
Top comments (0)