Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

fcreate simple eye test game

a simple eye test game, powered by flutter custompainter.

a simple android application built with using flutter. this application is taking part in flutter create competition. that’s why it has limited capabilities, built using only 5112 bytes dart code. and it’s a dart only application, targets android sdk version 28.

how’s it working ?

  • execution starts with app() class, which extends statelesswidget.
  • as this application only targets android, it’s a materialapp.
  • as i’m going to add interactivity to our app, i need a statefulwidget. home() satisfies that need.
  • due to code limit, i’m restricting my application to be only running in portrait mode.
      systemchrome.setpreferredorientations([deviceorientation.portraitup]);
    
  • in the build method i’m returing a scaffold widget, which provides a sound material design skeleton.
  • body of scaffold is a stack widget, which is very good at handling hiding of overlapping widgets, depending upon certain criteria or user event, by using opacity widget as its parent.
  • well i’m also using a floatingactionbutton(), to go to game widget, from help widget and vice versa.
      floatingactionbutton: floatingactionbutton(
        onpressed: _e
            ? () {
                swap();
                // _tm holds a periodic timer, which helps us to generate a new paint widget, every 1 seconds.
                _tm = timer.periodic(duration(seconds: 1), (t) {
                  if (t.isactive)
                    setstate(() {
                      _b = random().nextint(12) + 8; // _b, holds number of columns and rows, to be drawn in paint widget
                      // which also gets updated in random fashion
                    });
                });
              }
            : () {
                swap();
                _tm.cancel(); // timer, _tm is cancelled, to avoid unnecessary periodic computational tasks.
              }, // here `e` is a boolean variable, which decides behaviour of this button
        child: icon(_e ? icons.play_arrow : icons.help), // icon also gets updated
        backgroundcolor: colors.cyanaccent,
        elevation: 16,
        tooltip: _e ? 'init' : 'help', // tooltip text is also updated as value of `e` gets updated.
      ),
    
  • so, you’ve encountered a new function swap(), it just changes opacity value of two widgets and make them either visible or invisible.
      swap() {
    var tmp = _h; // simple swapping of `_h` and `_g` is done here.
    setstate(() {
      _h = _g;
      _g = tmp;
      _e = !_e; // putting negation of `_e` into `_e`, helps us to change behaviour of floatingactionbutton.
    });
    }
    
  • you may have already found a method called setw(), which is present due to implementation of white class in _homestate.
      @override
    setw(int c) {
    if (!_tm.isactive)
      setstate(() {
        _wh = c;
      });
    else
      _wh = c; // here i'm not interested in updating the ui too, that's why assignment is put outside of setstate((){}).
      // otherwise that might collide with scheduled ui updated operation, which runs periodically using timer, and updates custompaint widget.
    }
    
  • a gesturedetector widget is used as parent of custompaint, to handle user input event. a single tap denotes, that user selects currently shown paint widget and wants to know whether he/ she has selected a widget which has atleast 50% white colored balls. in response to this event a dialog shows up to indicate status of current selection.
      ontap: () {
                  if (_tm.isactive) {
                    _tm.cancel();
                    showdialog(
                        context: context,
                        builder: (cx) => dialog(
                            elevation: 9,
                            child: padding(
                                padding: edgeinsets.all(16),
                                child: text(
                                    '$_wh/${_b * _b} white balls ${_wh >= (_b * _b) / 2 ? 'u{2714}' : 'u{2716}'}',
                                    style: textstyle(
                                        fontsize: 25, letterspacing: 2)))));
                  }
                },
    
  • now if you double click on screen, cancelled timer starts running again.
      
                ondoubletap: () {
                  if (!_tm.isactive)
                    _tm = timer.periodic(duration(seconds: 1), (t) {
                      if (t.isactive)
                        setstate(() {
                          _b = random().nextint(12) + 8;
                        });
                    });
                }
    
  • a center aligned widget is used a child of opacity, to display help page. changing opacity value reveals either help page or game page. of course parent of these opacity widget is stack widget.
      center(
                child: padding(
                    padding: edgeinsets.all(12),
                    child: column(
                        mainaxissize: mainaxissize.min,
                        children: <widget>[
                          text('an eye test game',
                              style: textstyle(
                                  fontweight: fontweight.bold,
                                  letterspacing: 3,
                                  fontsize: 30)),
                          divider(color: colors.white, height: 24),
                          text(
                              'click to reveal whether it has atleast 50% white balls. double clicking restarts loop.',
                              maxlines: 3)
                        ])))
    
  • lets talk about painter class which subclasses custompainter and mainly takes care of painting operation to be performed in custompaint widget. painter‘s constructor takes two parameters, number of balls to be placed along row and column( it’s a square ) and an instance of white class, which works as callback mechanism for updating value of white balls generated randomly during painting, stored in a variable which resides in _homestate class.
  • as per definition of custompainter, need to override paint() and shouldrepaint() methods in painter.
  • so, i’ll be drawing some circles, for that i need an offset. position along x-axis and y-axis is determined as follows.
    double y = size.height / (b * 2); // b is # of balls along x and y axis.
    double x = size.width / (b * 2); 
    
  • white ball count is determined as following one.
      w += (p.color == colors.white) ? 1 : 0; // p variable holds instance of paint(), which is instantiated just in previous line.
    
  • this is how circle is drawn in iterative fashion, using a while loop until we reach size.width along x-axis or size.height along y-axis.
      canvas.drawcircle(
            offset(x, y), min(size.height / (b * 2), size.width / (b * 2)), p); // radius of circle is decreased, so that no two circle gets overlapped.
    
  • in inner while loop of paint(), coordinate value of x is increased size.width / b in each iteration.
    x += size.width / b;
    
  • same for y too, in outer while loop.
    y += size.height / b;
    
  • after drawing is done, number of white balls drawn on screen is updated, where white abstract class plays an role.
    wh.setw(w); // wh is an instance of white, which is passed into constructor of painter.
    
  • this is it.

simple eye test game flutter

screenshot_20190407-005833

screenshot_20190407-005845


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

Comments are closed.