How to Build a Basic Binary Clock with Flutter?

How to Build a Basic Binary Clock with Flutter?

In this Flutter tutorial, you'll learn Binary by building a Binary Clock with Flutter. The following lesson will teach you how to build a basic Binary clock with Flutter.

The Flutter Clock Contest is currently running with a submission deadline of Jan 20th, 2020. The following lesson will teach you how to build a basic Binary clock with Flutter.

Binary Clock Basics

We are building the binary clock shown in the demo video below. Notice how the clock ticks once-per-second and updates the highlighted boxes in the UI. The actual time is shown in big plain digits at the bottom, with the binary value for each number under it.

Each column represents a digit of time in hh:mm:ss format. Each row represents a binary value of 1, 2, 4, or 8 (or 0 if no boxes are colored). You calculate each digit in regular time by adding all the values (or bits) in a column.

Initial Setup

Create a Flutter App

Get started by creating a new Flutter app by running flutter create my_awesome_clock. The initial app will import a few dependencies and wrap the Clock widget inside of Scaffold.

main.dart

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

import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show SystemChrome, DeviceOrientation;
import 'package:intl/intl.dart' show DateFormat;

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

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

Force the App to Run in Landscape Mode

The Flutter Clock contest requires the app to run in landscape mode. You can tell Flutter to whitelist specific device orientations with the SystemChrome class. In our case, we will allow landscapeLeft or landscapeRight by updating the main function.

main.dart

void main() {
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.landscapeRight,
    DeviceOrientation.landscapeLeft,
  ]);
  runApp(MyApp());
}
Working with Time

Make the Clock Tick

The only state that ever changes on the clock is the time, which should update once-per-second. Simply create a DateTime property and update it every second with a periodic timer.

main.dart

class Clock extends StatefulWidget {
  Clock({Key key}) : super(key: key);

  @override
  _ClockState createState() => _ClockState();
}

class _ClockState extends State<Clock> {

  DateTime _now = DateTime.now(); // or BinaryTime see next step

  // Tick the clock
  @override
  void initState() {
    Timer.periodic(Duration(seconds: 1), (v) {
      setState(() {
        _now = DateTime.now(); // or BinaryTime see next step
      });
    });

    super.initState();
  }

}

Converting Integers to Binary Strings

A clock displays time on a format that looks like 14:23:55 or hh:mm:ss. In order to keep business logic out of the widget, a custom class called BinaryTime provides the values we need for the main UI.
main.dart

/// Utility class to access values as binary integers
class BinaryTime {
  List<String> binaryIntegers;

  BinaryTime() {
    DateTime now = DateTime.now();
    String hhmmss = DateFormat("Hms").format(now).replaceAll(':', '');

    binaryIntegers = hhmmss
        .split('')
        .map((str) => int.parse(str).toRadixString(2).padLeft(4, '0'))
        .toList();
  }

  get hourTens => binaryIntegers[0];
  get hourOnes => binaryIntegers[1];
  get minuteTens => binaryIntegers[2];
  get minuteOnes => binaryIntegers[3];
  get secondTens => binaryIntegers[4];
  get secondOnes => binaryIntegers[5];
}
Clock UI

Columns for Each Clock Digit

Each column in the binary clock represents a digit in normal base-10 time. The Clock widget implements six fixed columns for each digit.
main.dart

class Clock extends StatefulWidget {
  Clock({Key key}) : super(key: key);

  @override
  _ClockState createState() => _ClockState();
}

class _ClockState extends State<Clock> {
  BinaryTime _now = BinaryTime();

  // Tick the clock
  @override
  void initState() {
    Timer.periodic(Duration(seconds: 1), (v) {
      setState(() {
        _now = BinaryTime();
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(50),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // Columns for the clock
          ClockColumn(
            binaryInteger: _now.hourTens,
            title: 'H',
            color: Colors.blue,
            rows: 2,
          ),
          ClockColumn(
            binaryInteger: _now.hourOnes,
            title: 'h',
            color: Colors.lightBlue,
          ),
          ClockColumn(
            binaryInteger: _now.minuteTens,
            title: 'M',
            color: Colors.green,
            rows: 3,
          ),
          ClockColumn(
            binaryInteger: _now.minuteOnes,
            title: 'm',
            color: Colors.lightGreen,
          ),
          ClockColumn(
            binaryInteger: _now.secondTens,
            title: 'S',
            color: Colors.pink,
            rows: 3,
          ),
          ClockColumn(
            binaryInteger: _now.secondOnes,
            title: 's',
            color: Colors.pinkAccent,
          ),
        ],
      ),
    );
  }
}

Individual Clock Column

At this point, each column must be split into four cells, where a cell represents a single bit. The code below loops over the digits in a binary integer, then colors them if the cell is active (has a value of 1).
main.dart

/// Column to represent a binary integer.
class ClockColumn extends StatelessWidget {
  String binaryInteger;
  String title;
  Color color;
  int rows;
  List bits;

  ClockColumn({this.binaryInteger, this.title, this.color, this.rows = 4}) {
    bits = binaryInteger.split('');
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        ...[
          Container(
            child: Text(
              title,
              style: Theme.of(context).textTheme.display1,
            ),
          )
        ],
        ...bits.asMap().entries.map((entry) {
          int idx = entry.key;
          String bit = entry.value;

          bool isActive = bit == '1';
          int binaryCellValue = pow(2, 3 - idx);

          return AnimatedContainer(
            duration: Duration(milliseconds: 475),
            curve: Curves.ease,
            height: 40,
            width: 30,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(5)),
              color: isActive
                  ? color
                  : idx < 4 - rows
                      ? Colors.white.withOpacity(0)
                      : Colors.black38,
            ),
            margin: EdgeInsets.all(4),
            child: Center(
              child: isActive
                  ? Text(
                      binaryCellValue.toString(),
                      style: TextStyle(
                        color: Colors.black.withOpacity(0.2),
                        fontSize: 18,
                        fontWeight: FontWeight.w700,
                      ),
                    )
                  : Container(),
            ),
          );
        }),
        ...[
          Text(
            int.parse(binaryInteger, radix: 2).toString(),
            style: TextStyle(fontSize: 30, color: color),
          ),
          Container(
            child: Text(
              binaryInteger,
              style: TextStyle(fontSize: 15, color: color),
            ),
          )
        ]
      ],
    );
  }
}
Video

Flutter for Beginners 2020 - Build a Flutter App with Google's Flutter & Dart

Flutter for Beginners 2020 - Build a Flutter App with Google's Flutter & Dart

Flutter tutorial for Beginners 2020 - Build a Flutter App with Google's Flutter & Dart. Flutter Introduction for Beginners: Get Started with Flutter and learn how to build an iOS and Android app with Flutter! What is Flutter? How Flutter & Dart Code Gets Compiled? Why Choose Flutter? Flutter is Google's UI toolkit for crafting beautiful, natively compiled applications for mobile, web, and desktop from a single codebase.

Free Flutter Introduction for Beginners: Get Started with Flutter and learn how to build an iOS and Android app with Flutter!


Content:

  • Introduction 00:03
  • What is Flutter 01:50
  • Flutter's Architecture 07:44
  • How Flutter & Dart Code Gets Compiled
  • To Native Apps 12:31
  • Understanding Flutter Versions 15:44
  • Flutter macOS Setup 18:34
  • macOS Development Environment 37:24
  • Flutter Windows Setup 41:32
  • Windows Development Environment 01:00:48
  • Flutter & Material Design 01:04:34
  • Flutter Alternatives 01:05:49
  • Course Outline 01:11:56
  • How To Get The Most Out Of The
  • Course 01:18:36
  • Module Introduction 01:21:17
  • Creating a New Project 01:23:42
  • An Overview of the Generated Files &
  • Folders 01:35:57
  • Analyzing the Default App 01:44:18
  • Dart Basics 01:49:50
  • More Dart Basics 02:07:08
  • Building an App From Scratch 02:20:15
  • Running the App on an Emulator 02:31:18
  • Class Constructors & Named
  • Arguments 02:34:43
  • First Summary & Additional Syntax 02:43:13
  • Building a Widget Tree 02:51:24
  • Visible (Input / Output) & Invisible
  • (Layout / Control) Widgets 02:59:04
  • Adding Layout Widgets 03:02:17
  • Connecting Functions & Buttons 03:09:09
  • Anonymous Functions 03:16:40
  • Updating Widget Data (Or: Using
  • StatelessWidget Incorrectly) 03:20:01
  • Updating Correctly with Stateful
  • Widgets 03:26:38
  • A Brief Look Under The Hood 03:38:36
  • Using Private Properties 03:41:04
  • Creating a New, Custom Widget 03:46:21
  • First Styling & Layouting Steps 03:58:11
  • Enums & Multiple Constructors 04:06:12
  • Official Docs & The Widget Catalog 04:10:19
  • Passing Callback Functions Around 04:12:59
  • Introducing Maps 04:23:37
  • Mapping Lists to Widgets 04:29:30
  • final vs const 04:39:54
  • Introducing "if" Statements 04:50:45
  • [DART DEEP DIVE] More on "if"
  • Statements 04:57:36
  • [DART DEEP DIVE] The "null" Value 05:08:52
  • Outputting Widgets Conditionally 05:10:55
  • Splitting the App Into Widgets 05:13:16
  • Calculating a Total Score 05:23:13
  • Getters & "else-if" 05:30:59
  • Resetting the Quiz 05:37:34
  • Wrap Up 05:42:28

Flutter Tutorial for Beginners 2 - Learning Dart Basics | Basics of Dart

Flutter Tutorial for Beginners 2 - Learning Dart Basics | Basics of Dart

Flutter Tutorial for Beginners 2 - Learning Dart Basics | Basics of Dart programming language. We will learn the basics of Dart. Dart is Object Oriented Language Developed By Google which is Primarily used for building websites, servers, and mobile apps. Flutter is an open-source UI software development kit created by Google.Flutter is SDK that makes creating high-performing, modern and good looking apps. Flutter is easy and Works for both Android and iOS. Flutter is An open-source toolkit, developed by Google.

In this video we will learn the basics of Dart. Dart is Object Oriented Language Developed By Google which is Primarily used for building websites, servers, and mobile apps.
Welcome to this course on Flutter Tutorials for beginners. Flutter is an open-source UI software development kit created by Google.Flutter is SDK that makes creating high-performing, modern and good looking apps. Flutter is easy and Works for both Android and iOS. Flutter is An open-source toolkit, developed by Google.