Write a typing test module with a paragraph, timer, text accuracy, and result code in Flutter




 Typing test module with a paragraph, timer, text accuracy,

import 'dart:async';

import 'package:flutter/material.dart';


class TypingTest extends StatefulWidget {

  @override

  _TypingTestState createState() => _TypingTestState();

}


class _TypingTestState extends State<TypingTest> {

  String paragraph = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed egestas lacus in enim congue, a commodo ipsum varius. Integer bibendum velit vel accumsan hendrerit. Nunc malesuada lacus vel velit facilisis consectetur. Sed bibendum erat euismod, fringilla nulla eu, tempor libero. Nam congue, magna id tincidunt feugiat, lectus eros blandit mi, sit amet congue ante odio a risus.";

  int timer = 60;

  String typing = "";

  double accuracy = 0;

  String result = "";

  Timer _timer;


  void startTimer() {

    _timer = Timer.periodic(Duration(seconds: 1), (timer) {

      setState(() {

        this.timer--;

        if (this.timer == 0) {

          _timer.cancel();

          result = "Time's up! Your typing accuracy was ${(accuracy * 100).toStringAsFixed(2)}%.";

        }

      });

    });

  }


  void calculateAccuracy() {

    setState(() {

      accuracy = typing.split("").fold(0, (prev, current) {

        int index = paragraph.indexOf(current, prev);

        return index >= 0 ? index + 1 : prev;

      }) / paragraph.length;

    });

  }


  @override

  void initState() {

    super.initState();

    startTimer();

  }


  @override

  Widget build(BuildContext context) {

    return Container(

      padding: EdgeInsets.all(16),

      child: Column(

        children: <Widget>[

          Text(paragraph),

          TextField(

            onChanged: (value) {

              setState(() {

                typing = value;

              });

              calculateAccuracy();

              if (typing == paragraph) {

                _timer.cancel();

                result = "Finished! Your typing accuracy was ${(accuracy * 100).toStringAsFixed(2)}%.";

              }

            },

          ),

          Text("Time remaining: $timer"),

          Text("Accuracy: ${(accuracy * 100).toStringAsFixed(2)}%"),

          Text(result),

        ],

      ),

    );

  }

}




Explanations: This code creates a typing test module with a paragraph, timer, text accuracy, and result. The paragraph, timer, typing, accuracy, and result are stored as class variables. A startTimer function is used to start a timer that decrements the timer variable every second. The calculateAccuracy function is used to calculate the accuracy as the ratio of correct characters typed to

Post a Comment

Previous Post Next Post
© 2023 Developed and Design By
NILESH NISHAD