Want to make a Random color generator Background in Flutter? If you want to change the color when button is pressed, you have to use a StatefulWidget. A simple example is like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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], ), ); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.