3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Flutter】ランダムな色を返したい

Last updated at Posted at 2022-07-04

今までリストに色情報を格納して、ランダムなインデックスを計算して返す。みたいな無駄なことをやっていたんですが、下記コードでランダムな色を返してくれるみたいです。

コード

Color((Random().nextDouble() * 0xFFFFFF).toInt() << 0,).withOpacity(1.0)

サンプル

class _RandomColorState extends State<RandomColor> {
  var randomColor = const Color(0xffffffff);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Center(
        child: Text(
          'Random',
          style: TextStyle(
            color: randomColor,
            fontSize: 30,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            randomColor = Color(
              (Random().nextDouble() * 0xFFFFFF).toInt() << 0,
            ).withOpacity(1.0);
          });
        },
      ),
    );
  }
}


以上です!

参考

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?