Home > OS >  How to generate random color dot on screen at x interval of time in Flutter
How to generate random color dot on screen at x interval of time in Flutter

Time:01-27

So I'm trying to make an app where when clicked on Play button random color dots start to appear on screen at any location but I can't get around to how to implement that in flutter any help would be appreciated.

I know that I need to use random class which is built-in method but how to generate color dots using that?

Btw one color should appear at a given time and next color should appear after X seconds

Below is an image attached to what kind of effect I want on pressing play button.

CodePudding user response:

Try this:

import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class CircleProps {
  double left;
  double top;
  Color color;

  CircleProps(this.left, this.top, this.color);
}

class _MyHomePageState extends State<MyHomePage> {
  var circles = <CircleProps>[];
  var circleSize = 20.0;

  void _addCircle() {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;

    var generatedColor = Random().nextInt(Colors.primaries.length);

    var left = Random().nextInt((width - circleSize).toInt());
    var top = Random().nextInt((height - circleSize).toInt());

    var color = Colors.primaries[generatedColor];
    circles.add(CircleProps(left.toDouble(), top.toDouble(), color));
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    Timer.periodic(const Duration(seconds: 3), (t) {
      _addCircle();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Stack(
          children: circles.isEmpty
              ? [const Center()]
              : circles
                  .map<Widget>((e) => Positioned(
                        left: e.left, // distance between this child's left edge & left edge of stack
                        top: e.top, // distance between this child's top edge & top edge of stack
                        child: Container(
                            height: circleSize,
                            width: circleSize,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(color: e.color, shape: BoxShape.circle)),
                      ))
                  .toList()),
    );
  }
}

CodePudding user response:

you can use the Random class from the dart:math library to generate random numbers for the color values of your dot. To display the dot on the screen, you can use a Container widget with a decoration property set to a BoxDecoration with a color property set to the random color. To update the dot's color at a specific interval of time, you can use the Timer class from the dart:async library to schedule a new color change.

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

class RandomColorDot extends StatefulWidget {
  @override
 _RandomColorDotState createState() => _RandomColorDotState();
}

class _RandomColorDotState extends State<RandomColorDot> {
 Color _dotColor;
 Timer _timer;

@override
void initState() {
  super.initState();
  _dotColor = _generateRandomColor();
  _timer = Timer.periodic(Duration(seconds: 5), (timer) {
    setState(() {
      _dotColor = _generateRandomColor();
    });
  });
}

@override
void dispose() {
  _timer.cancel();
  super.dispose();
}

Color _generateRandomColor() {
  final random = Random();
  return Color.fromARGB(
    random.nextInt(256),
    random.nextInt(256),
    random.nextInt(256),
    random.nextInt(256),
  );
}

@override
Widget build(BuildContext context) {
  return Container(
    width: 100,
    height: 100,
    decoration: BoxDecoration(
      color: _dotColor,
      shape: BoxShape.circle,
    ),
  );
 }
}

In the above example, the dot will change color every 5 seconds.

  • Related