Create an app to print the multiplication table in Flutter of a given number

In this tutorial, we’ll build a multiplication table in flutter app where users can enter a number and see its multiplication table. This app will be a fantastic exercise for beginners to understand state management, text input handling, and dynamic list generation in Flutter.

Multiplication table in flutter stepwise

Step 1: Setting up multiplication table in flutter

First, create a new Flutter project. Open your terminal and run the following command:

flutter create multiplication_table_app

Navigate into your project directory:

cd multiplication_table_app

Step 2: Main Application – multiplication table in flutter

Open your project in your preferred code editor and navigate to lib/main.dart. Replace the existing code with the following:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Multiplication Table',
      home: MultiplicationTableScreen(),
    );
  }
}

In the above code, we define the MyApp widget which is the root of our application. It sets up the MaterialApp with a title and the home screen.

Step 3: Creating the Multiplication Table Screen

Next, we need to create a stateful widget to manage the multiplication table screen. This widget will handle the user input and generate the multiplication table dynamically.

class MultiplicationTableScreen extends StatefulWidget {
  @override
  _MultiplicationTableScreenState createState() => _MultiplicationTableScreenState();
}

class _MultiplicationTableScreenState extends State<MultiplicationTableScreen> {
  final _controller = TextEditingController();
  int _number = 0;
  List<String> _table = [];

  void _generateTable() {
    setState(() {
      try {
        _number = int.parse(_controller.text);
        _table = []; // Clear previous table
        for (int i = 1; i <= 10; i++) {
          _table.add("$_number x $i = ${_number * i}");
        }
      } catch (e) {
        _table = ["Invalid Input"];
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Multiplication Table'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: [
            TextField(
              controller: _controller,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                labelText: 'Enter a number',
              ),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _generateTable,
              child: Text('Generate Table'),
            ),
            Expanded(
              child: ListView.builder(
                shrinkWrap: true,
                itemCount: _table.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(_table[index]),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Step 4: Understanding the Code

  1. Stateful WidgetMultiplicationTableScreen is a stateful widget because it maintains state (the number and the generated multiplication table).
  2. TextField and Controller: The TextField widget is used to take user input. We use a TextEditingController to retrieve the text entered by the user.
  3. Generate Table Function: The _generateTable function parses the input number and generates the multiplication table. It updates the state using setState, which re-renders the UI with the new data.
  4. ListView.builder: This widget dynamically creates a scrollable list of items. It uses the _table list to generate each item in the list.

Step 5: Running the App

To see your app in action, run the following command in your terminal:

flutter run

Enter a number in the text field, click “Generate Table”, and see the multiplication table below.

Output:

Screenshot 2024 07 03 at 21.07.41

Contact Us:

Stay connected and follow us for more insights on mobile development and the latest in Flutter technology.