vendredi 19 février 2021

Interviewer said that 25th line of code contains an issue where setState() with random color being used. Help identify an issue

Original task sounded like:

The application should: display the text "Hey there" in the middle of the screen and after tapping anywhere on the screen a background color should be changed to a random color. You can also add any other feature to the app - that adds bonus points Please do not use any external libraries for color generation

My solution (GitHub):

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: RandomBackgroundColorWidget(),
    );
  }
}

class RandomBackgroundColorWidget extends StatefulWidget {
  @override
  _RandomBackgroundColorWidget createState() => _RandomBackgroundColorWidget();
}

class _RandomBackgroundColorWidget extends State<RandomBackgroundColorWidget> {
  int _colorIndex = 0xFF42A5F5;

  void _randomColorIndexGenerator() {
    final _rng = new Random();
    setState(() => {_colorIndex = (_rng.nextInt(0xFFFFFF) + 0xFF000000)});
  }

  @override
  Widget build(BuildContext context) {
    return Stack(children: [
      Material(
        color: Color(_colorIndex),
        child: Center(
          child: Text("Hey there"),
        ),
      ),
      GestureDetector(
        onTap: () => _randomColorIndexGenerator(),
      ),
    ]);
  }
}

While reviewing my test task interviewer said that 25th line of code contains an issue.

setState(() => {_colorIndex = (_rng.nextInt(0xFFFFFF) + 0xFF000000)});

And he commented:

"It is working in a way that is not intended by you."

Help to identify an issue in 25th line of code.




Aucun commentaire:

Enregistrer un commentaire