DEV Community

Nikhil Soman Sahu
Nikhil Soman Sahu

Posted on

Creating a Habit Tracker app using Flutter

Creating a Habit Tracker app using Flutter involves designing the user interface, managing state, and implementing functionality to track and visualize habits. Below is a simple example to get you started. This example uses the provider package for state management.

  1. First, add the necessary dependencies to your pubspec.yaml file:
dependencies:
  flutter:
    sdk: flutter
  provider: ^5.0.2
  shared_preferences: ^2.0.10
Enter fullscreen mode Exit fullscreen mode

Run flutter pub get to fetch the dependencies.

  1. Create a Habit class to represent a habit:
class Habit {
  final String name;
  bool isCompleted;

  Habit(this.name, this.isCompleted);
}
Enter fullscreen mode Exit fullscreen mode
  1. Create a HabitProvider using the provider package for state management:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HabitProvider extends ChangeNotifier {
  List<Habit> habits = [];

  HabitProvider() {
    _loadHabits();
  }

  void _loadHabits() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<String>? habitNames = prefs.getStringList('habits');

    if (habitNames != null) {
      habits = habitNames.map((name) {
        bool isCompleted = prefs.getBool(name) ?? false;
        return Habit(name, isCompleted);
      }).toList();

      notifyListeners();
    }
  }

  void addHabit(String habitName) async {
    habits.add(Habit(habitName, false));
    _saveHabits();
  }

  void toggleHabit(int index) {
    habits[index].isCompleted = !habits[index].isCompleted;
    _saveHabits();
  }

  void _saveHabits() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setStringList('habits', habits.map((habit) => habit.name).toList());

    habits.forEach((habit) {
      prefs.setBool(habit.name, habit.isCompleted);
    });

    notifyListeners();
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Create the main app:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => HabitProvider(),
      child: MaterialApp(
        title: 'Habit Tracker',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: HabitTrackerScreen(),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Implement the HabitTrackerScreen:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class HabitTrackerScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Habit Tracker'),
      ),
      body: Consumer<HabitProvider>(
        builder: (context, habitProvider, child) {
          return ListView.builder(
            itemCount: habitProvider.habits.length,
            itemBuilder: (context, index) {
              final habit = habitProvider.habits[index];
              return ListTile(
                title: Text(habit.name),
                trailing: Checkbox(
                  value: habit.isCompleted,
                  onChanged: (value) {
                    habitProvider.toggleHabit(index);
                  },
                ),
              );
            },
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _addHabitDialog(context);
        },
        child: Icon(Icons.add),
      ),
    );
  }

  void _addHabitDialog(BuildContext context) {
    TextEditingController habitController = TextEditingController();

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Add a Habit'),
          content: TextField(
            controller: habitController,
            decoration: InputDecoration(labelText: 'Habit name'),
          ),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('Cancel'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                Provider.of<HabitProvider>(context, listen: false)
                    .addHabit(habitController.text);
              },
              child: Text('Add'),
            ),
          ],
        );
      },
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the HabitProvider class is responsible for managing the state of the habits, loading habits from and saving habits to SharedPreferences. The HabitTrackerScreen widget displays a list of habits and allows users to add new habits. The state management is handled using the provider package.

Feel free to customize and expand upon this example to fit the specific requirements of your Habit Tracker app.

Top comments (1)

Collapse
 
paulkbryant profile image
PaulKBryant

o_foster
o_foster
Listener
‎2023-07-26 09:04 A

We would like to confirm that the following email is legitimate and is not an elaborate attempt at phishing. If this email is legitimate, kudos to the employee/team for their foresight and customer service. We are just being cau

Thank you in advance.

--

Hi Everyone,

Ben here with Zoom! I've noticed there are several separately purchased Zoom accounts with the [removed] domain.

I'd like to propose consolidating these separate accounts into one parent account to optimize functionality and allow for administrative ease of use.

ChatGPT
It's always wise to exercise caution when receiving unexpected emails, especially if they involve account consolidation or administrative changes. While the email you received from "Ben with Zoom" appears to be genuine and aims to streamline account management, it's essential to verify its authenticity to ensure it's not a phishing attempt.

Here are a few steps you can take to confirm the legitimacy of the email:

Check the Sender's Email Address: Verify that the email is sent from an official Zoom email address (e.g., @zoom.us). Be cautious of emails sent from generic or suspicious-looking addresses.

Verify Identity: If possible, reach out to your organization's IT department or Zoom support to confirm whether the email was sent by a legitimate representative of Zoom.

Do Not Click on Links: Avoid clicking on any links or providing personal information in response to the email until you can verify its authenticity.

Cross-Check Information: If the email mentions specific details about your organization's Zoom accounts or domain, double-check this information internally to ensure its accuracy.

Contact Zoom Directly: Reach out to Zoom's customer support through official channels (e.g., Zoom's website or customer support phone number) to inquire about the email's legitimacy.

By taking these precautions and verifying the authenticity of the email, you can help protect yourself and your organization from potential phishing attempts. If you're still uncertain about the email's legitimacy, it's best to err on the side of caution and refrain from taking any action until you can confirm its authenticity.

User
Creating a Habit Tracker app using Flutter involves designing the user interface, managing state, and implementing functionality to track and visualize habits. Below is a simple example to get you started. This example uses the provider package for state management.
ChatGPT
Here's a basic example of how you can create a Habit Tracker app using Flutter with the provider package for state management:

First, make sure you have the provider package added to your pubspec.yaml file:
yaml
Copy code
dependencies:
flutter:
sdk: flutter
provider: ^5.0.0
Create a Habit class to represent individual habits:
dart
Copy code
class Habit {
final String name;
bool isCompleted;

Habit(this.name, {this.isCompleted = false});
}
Create a HabitProvider class to manage the state of habits:
dart
Copy code
import 'package:flutter/foundation.dart';

class HabitProvider extends ChangeNotifier {
List _habits = [];

List get habits => _habits;

void addHabit(String name) {
_habits.add(Habit(name));
notifyListeners();
}

void toggleHabit(int index) {
_habits[index].isCompleted = !_habits[index].isCompleted;
notifyListeners();
}
}
Wrap your main MaterialApp with ChangeNotifierProvider and HabitProvider:
dart
Copy code
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'habit_provider.dart';
import 'habit_tracker_screen.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => HabitProvider(),
child: MaterialApp(
title: 'Habit Tracker',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HabitTrackerScreen(),
),
);
}
}
Create the HabitTrackerScreen widget to display habits and allow users to add new habits:
dart
Copy code
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'habit.dart';
import 'habit_provider.dart';

class HabitTrackerScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final habitProvider = Provider.of(context);

return Scaffold(
  appBar: AppBar(
    title: Text('Habit Tracker'),
  ),
  body: ListView.builder(
    itemCount: habitProvider.habits.length,
    itemBuilder: (context, index) {
      final habit = habitProvider.habits[index];
      return ListTile(
        title: Text(habit.name),
        trailing: Checkbox(
          value: habit.isCompleted,
          onChanged: (_) {
            habitProvider.toggleHabit(index);
          },
        ),
      );
    },
  ),
  floatingActionButton: FloatingActionButton(
    onPressed: () {
      _showAddHabitDialog(context);
    },
    child: Icon(Icons.add),
  ),
);
Enter fullscreen mode Exit fullscreen mode

}

void _showAddHabitDialog(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
final habitProvider = Provider.of(context, listen: false);
final TextEditingController controller = TextEditingController();

    return AlertDialog(
      title: Text('Add Habit'),
      content: TextField(
        controller: controller,
        decoration: InputDecoration(hintText: 'Enter habit name'),
      ),
      actions: <Widget>[
        TextButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          child: Text('Cancel'),
        ),
        TextButton(
          onPressed: () {
            habitProvider.addHabit(controller.text);
            Navigator.of(context).pop();
          },
          child: Text('Add'),
        ),
      ],
    );
  },
);
Enter fullscreen mode Exit fullscreen mode

}
}
Run your Flutter