Building a very basic ToDo App with Flutter

In this tutorial, we will build a simple ToDo application using the Flutter framework. The app will allow users to add and remove tasks from their to-do lists.

Prerequisites

Before we begin, make sure you have Flutter installed on your machine. You can follow the official Flutter installation guide for your operating system: Flutter Installation Guide

Setting up the Project

  1. Create a new Flutter project by running the following command in your terminal:
flutter create todo_app
  1. Open the project in your preferred code editor.

  2. Replace the contents of the lib/main.dart file with the following code:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      title: 'Testing todo application',
      theme: ThemeData(
        brightness: Brightness.dark,
        primaryColor: Colors.green,
      ),
      debugShowCheckedModeBanner: false,
      home: const MyHomePage(),
    ));

class MyHomePage extends {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final List<String> _todos = ['item1', 'item2', 'item2'];

  void _addTodos() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        String _todo = '';
        return AlertDialog(
          title: const Text('Todo task'),
          content: TextField(
            decoration: const InputDecoration(
              hintText: 'add your todos',
            ),
            onChanged: (value) {
              _todo = value;
            },
          ),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('cancel'),
            ),
            TextButton(
              onPressed: () {
                setState(() {
                  _todos.add(_todo);
                });
 Navigator.of(context).pop();
              },
              child: const Text('submit'),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('ToDo App'),
        centerTitle: true,
      ),
      body: Center(
        child: ListView.builder(
          itemCount: _todos.length,
          itemBuilder: (context, index) {
            final newTodo = _todos[index];
            return ListTile(
              title: Text(newTodo),
              subtitle: Text('You have added the new $newTodo'),
              onTap: () {
                setState(() {
                  _todos.removeAt(index);
                });
              },
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addTodos,
        child: const Icon(Icons.add),
      ),
    );
  }
}

Code Explanation

Let's go through the code and understand how our ToDo app works.

  1. We start by importing the necessary packages. In this case, we are using package:flutter/material.dart for building the UI.

  2. The main() function is the entry point of our application. It sets up the MaterialApp widget, which represents the root of our app. We provide a title, theme, and set debugShowCheckedModeBanner to false to hide the debug banner.

  3. We define a stateful widget called MyHomePage. This widget represents the home screen of our app.

  4. Inside the MyHomePage widget, we define a private list _todos to store our todo items. Initially, we populate it with some dummy data.

  5. The _addTodos() method is responsible for showing a dialog to add new to-do items. It creates an AlertDialog widget with a text field and two buttons: "cancel" and "submit". When the user taps the "submit" button, the entered to-do item is added to the _todos list.

  6. In the build() method of MyHomePage, we create a Scaffold widget that provides the basic structure for our app. It contains an AppBar with a title and a centered title.

  7. The body of the Scaffold is a Center widget that contains a ListView.builder. This builder generates a ListTile for each to-do item in the _todos list. Each ListTile displays the to-do item's title and a subtitle indicating that it is a new item. Tapping on a ListTile removes the corresponding to-do item from the list.

  8. Finally, we add a FloatingActionButton at the bottom-right corner of the screen. When pressed, it calls the _addTodos() method to show the add todo dialog.

Running the App

Save the changes and run the app using the following command:

flutter run

The app should launch on the connected device or emulator. You will see an app bar with the title "Alert Box Dialog" and a floating action button with an edit icon.

0
Subscribe to my newsletter

Read articles from Biplob Hossain Sheikh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Biplob Hossain Sheikh
Biplob Hossain Sheikh

I'm a Computer Science and Engineering graduate passionate about technology. I excel in web and mobile app development, DevOps, and cloud engineering. As a coding teacher, I love sharing knowledge and making complex concepts understandable. Skilled programmer and effective presenter, I stay up-to-date with emerging tech trends.