Flutter: How can I make a Random color generator B

2020-05-25 03:39发布

Generate random colors

return new RaisedButton(


    padding:  EdgeInsets.symmetric(vertical: 30.0),
    color: Colors.primaries random  List <blue,green>,

标签: dart flutter
9条回答
倾城 Initia
2楼-- · 2020-05-25 04:15

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.

查看更多
冷血范
3楼-- · 2020-05-25 04:19
import 'dart:math';
import 'dart:ui';

class Util {
  static Color randomColor() {
    return Color(Random().nextInt(0xffffffff));
  }
}
查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-05-25 04:22

Another way to get tons of colors is using Random class with Color.fromARGB or Color.fromRGBO:

import 'dart:math';
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: MyPage()));
}

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => new _MyPageState();
}

class _MyPageState extends State<MyPage> {
  final Random _random = Random();

  Color _color = Color(0xFFFFFFFF);

  void changeColor() {
    setState(() {
      _color = Color.fromARGB(
        //or with fromRGBO with fourth arg as _random.nextDouble(),
        _random.nextInt(256),
        _random.nextInt(256),
        _random.nextInt(256),
        _random.nextInt(256),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: InkWell(
        onTap: changeColor,
        child: Container(
          color: _color,
        ),
      ),
    );
  }
}

If you use Color.fromRGBO:

Fourth argument should be within 0.0 to 1.0 and fortunately we have _random.nextDouble() that gives a value between 0.0 to 1.0 randomly.

By the way:

  • R - Red
  • B - Blue
  • G - Green
  • O - Opacity
  • A - Alpha
查看更多
登录 后发表回答