Press "Enter" to skip to content

Flutter : Create Simple Number Counter

As a Flutter beginner, working with button, Text labels, data types are important. This tutorial explains how to program a simple number counter with Flutter dart code.

Here is a text, labeled as ‘0’ at beginning and a button which is clickable which increases the label text number one by one.

Program Code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Simple Counter';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: SimpleCounter(),
      ),
    );
  }
}
class SimpleCounter extends StatefulWidget {
  @override
  _SimpleCounterState createState() => _SimpleCounterState();
}

class _SimpleCounterState extends State<SimpleCounter> {
  int number = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  GestureDetector(
                    child: new Text(number.toString(),
                        style: TextStyle(
                          fontSize: 100,
                        )),
                  ),
                  RaisedButton(
                    child: Text("+",
                      style: TextStyle(fontSize: 75),),
                    onPressed : () {
                      setState(() {
                        number = number + 1;
                      });
                    },
                  ),
                ],
              ),
           ],
          ),
    );
  }
}

Explanation:

We have designed the layout using Row, Column, Text and RaisedButton tools. RaisedButton has an event of onPressed which increase the number by one on previous number.

Sample Output:

Flutter Create Simple Number Counter

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *