Flutter: How can I make a Random color generator Background
Solution 1:
This is my way to get a random color:
Color((math.Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0)
Note:
This import is required.
import 'dart:math' as math;
Solution 2:
There is an in-built list of material colors in the Colors class. You can use it like below
Colors.primaries[Random().nextInt(Colors.primaries.length)]
example
import 'dart:math';
Icon(
Icons.account_circle,
size: 40,
color: Colors.primaries[Random().nextInt(Colors.primaries.length)],
)
Above is the simplest and fastest way to colorize your list with random colors. You don't need to maintain a list of colors.
Solution 3:
You can use Random
class to do that:
But if you want to change the color when button is pressed, you have to use a StatefulWidget
. A simple example is like below:
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
runApp(
MaterialApp(
home: MyApp(),
),
);
}
class MyApp extends StatefulWidget {
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List colors = [Colors.red, Colors.green, Colors.yellow];
Random random = new Random();
int index = 0;
void changeIndex() {
setState(() => index = random.nextInt(3));
}
@override
Widget build(BuildContext context) {
return Center(
child: RaisedButton(
onPressed: () => changeIndex(),
child: Text('Click'),
color: colors[index],
),
);
}
}
Also, there is a package called random_pk by pawankumar, that will give us random color each and every time your app's build method get called.