Flutter app shows default counter instead of my custom StatefulWidget (TodoApp)


Create this file inside your lib/ folder and paste the following code. This contains the StatefulWidget, the data model, and all the logic for the AppBar, ListView, and FAB.

import 'package:flutter/material.dart';

// 1. DATA MODEL: Represents a single task
class Task {
  String name;
  bool isCompleted;

  Task({required this.name, this.isCompleted = false});
}

// 2. STATEFUL WIDGET: The main Todo App
class TodoApp extends StatefulWidget {
  const TodoApp({super.key});

  @override
  State<TodoApp> createState() => _TodoAppState();
}

class _TodoAppState extends State<TodoApp> {
  // Controller to read text from the TextField
  final TextEditingController _taskController = TextEditingController();
  
  // The list that holds all our tasks
  final List<Task> _tasks = [];

  // Always dispose controllers to prevent memory leaks
  @override
  void dispose() {
    _taskController.dispose();
    super.dispose();
  }

  // Helper method: Adds a new task to the list
  void _addTask() {
    if (_taskController.text.trim().isNotEmpty) {
      setState(() {
        _tasks.add(Task(name: _taskController.text.trim()));
        _taskController.clear(); // Clear the TextField after adding
      });
    }
  }

  // Helper method: Removes ONLY completed tasks (used by AppBar icon)
  void _removeCompletedTasks() {
    setState(() {
      _tasks.removeWhere((task) => task.isCompleted);
    });
  }

  // Helper method: Clears ALL tasks (used by FAB)
  void _clearAllTasks() {
    setState(() {
      _tasks.clear();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // APPBAR: Title and Delete Completed Icon
      appBar: AppBar(
        title: const Text('Stateful Widget Lab Exam'),
        actions: [
          IconButton(
            icon: const Icon(Icons.delete),
            onPressed: _removeCompletedTasks,
            tooltip: 'Delete Completed Tasks',
          ),
        ],
      ),
      
      // BODY: Column layout
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // Input Field
            TextField(
              controller: _taskController,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                hintText: 'Enter task name',
              ),
            ),
            const SizedBox(height: 10),
            
            // Add Task Button
            ElevatedButton(
              onPressed: _addTask,
              child: const Text('Add Task'),
            ),
            const SizedBox(height: 10),
            
            // Expanded prevents the "Column Overflow" error by giving the ListView
            // the remaining vertical space to scroll.
            Expanded(
              child: ListView.builder(
                itemCount: _tasks.length,
                itemBuilder: (context, index) {
                  final task = _tasks[index];
                  
                  // Each task is a Card containing a ListTile
                  return Card(
                    elevation: 2,
                    margin: const EdgeInsets.symmetric(vertical: 4),
                    child: ListTile(
                      // Leading Icon: Checked or Unchecked
                      leading: Icon(
                        task.isCompleted ? Icons.check_circle : Icons.circle_outlined,
                        color: task.isCompleted ? Colors.green : Colors.grey,
                      ),
                      
                      // Title: Task text with strikethrough if completed
                      title: Text(
                        task.name,
                        style: TextStyle(
                          decoration: task.isCompleted 
                              ? TextDecoration.lineThrough 
                              : TextDecoration.none,
                          color: task.isCompleted ? Colors.grey : Colors.black,
                        ),
                      ),
                      
                      // Trailing: Delete specific task
                      trailing: IconButton(
                        icon: const Icon(Icons.delete),
                        onPressed: () {
                          setState(() {
                            _tasks.removeAt(index);
                          });
                        },
                      ),
                      
                      // Tapping toggles the completion status
                      onTap: () {
                        setState(() {
                          task.isCompleted = !task.isCompleted;
                        });
                      },
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
      
      // FLOATING ACTION BUTTON: Reset / Clear all tasks
      floatingActionButton: FloatingActionButton(
        onPressed: _clearAllTasks,
        tooltip: 'Reset Application',
        child: const Icon(Icons.refresh),
      ),
    );
  }
}


 main.dart


import 'package:flutter/material.dart';
import 'todo_app.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a purple toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const TodoApp(), // <--- UPDATED THIS LINE TO RUN YOUR TODO APP
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text('You have pushed the button this many times:'),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
1
Sep 23 at 6:23 AM
User AvatarKyvin Magalona
#javascript#android#flutter#windows#state

Accepted Answer

Make sure your file name is todo_app.dart

In main.dart you should have:

import 'package:flutter/material.dart';
import 'todo_app.dart';   // ← make sure this path is correct

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Todo App',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const TodoApp(),   // ← this must be TodoApp
    );
  }
}

delete or comment the entire MyHomePage class

do a full restart (not reloading)

Hope this helps

User AvatarRoberto
Sep 23 at 9:33 AM
1