skip to Main Content

First of all, there is nothing to see an error also I couldn’t find where I still did wrong.

The main error is in (homepagepass.dart)

Last view from the app:

look at this

Here are my codes and all pages:

Codes are here

———————————-first main page (main.page):

import 'package:animated_splash_screen/animated_splash_screen.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'db/db_make.dart';
import 'homepagepass.dart';
import 'notification_service.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  NotificationService().initNotification();
  await DatabaseCodes.initDb();
  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(
      themeMode: ThemeMode.dark,
      debugShowCheckedModeBanner: false,
      home: AnimatedSplashScreen(
        splash: Image.asset('images/logo.png'),
        nextScreen: HomePagePass(),
        splashIconSize: 180,
        splashTransition: SplashTransition.fadeTransition,
        backgroundColor: Colors.white,
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();

    Future.delayed(const Duration(seconds: 3)).then((value) {
      Navigator.of(context).pushReplacement(
          CupertinoPageRoute(builder: (ctx) => HomePagePass()));
    });
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      backgroundColor: Colors.white,
      body: SizedBox(),
    );
  }
}

———————————-homepagepass.dart

import 'controllers/task_controller.dart';
import 'db/db_make.dart';
import 'main.dart';
import 'notification_service.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  NotificationService().initNotification();
  await DatabaseCodes.initDb();
  runApp(const MyApp());
}

class HomePagePass extends StatefulWidget {
  HomePagePass({super.key});

  @override
  State<HomePagePass> createState() => _HomePagePassState();
}

class _HomePagePassState extends State<HomePagePass> {
  DateTime _selectedDate = DateTime.now();
  final _taskController = Get.put(TaskController());
  var notificationService;




//-----------------TROUBLE IS HERE--------------------------------------------------
  _showTasks() {
    return Expandable(
          child: Obx(() {
          return ListView.builder(
              shrinkWrap: true,
              itemCount: _taskController.taskList.length,
              //_taskController.taskList.length,
              itemBuilder: (_, index) {
                print(_taskController.taskList.length);
                return Container(
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.blueAccent)),
                    width: 100,
                    height: 50,
                    color: Colors.red,
                    margin: const EdgeInsets.only(bottom: 10),
                    child:
                        Text(_taskController.taskList[index].title.toString()));
              });
        }));
  }
//-----------------TROUBLE IS HERE--------------------------------------------------

  @override
  void initState() {
    super.initState();
    notificationService = NotificationService();

    setState(() {
      print('i am here');
    });
  }

  bool toggle = false;

  String formattedDate = DateFormat('yyyy-MM-dd').format(DateTime.now());

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: ChangeNotifierProvider<ThemeModel>(
        create: (_) => ThemeModel(),
        child: Consumer<ThemeModel>(
          builder: (_, model, __) {
            return SafeArea(
              child: MaterialApp(
                debugShowCheckedModeBanner: false,
                theme: ThemeData.light(), // Provide light theme.
                darkTheme: ThemeData.dark(), // Provide dark theme.
                themeMode: model.mode, // Decides which theme to show.
                home: Scaffold(
                  appBar: AppBar(
                    elevation: 0,
                    title: const Text('TODOAPP'),
                    leading: IconButton(
                        icon: toggle
                            ? const Icon(Icons.mode_night)
                            : const Icon(
                                Icons.light_mode,
                              ),
                        onPressed: () {
                          setState(() {
                            // Here we changing the icon.
                            toggle = !toggle;
                            model.toggleMode();
                          });
                        }),
                    actions: [
                      IconButton(
                          onPressed: () {},
                          icon: Center(
                              child: Icon(Icons.person_outlined, size: 30)))
                    ],
                  ),
                  body: Column(
                    children: [
                      Container(
                        margin: EdgeInsets.only(left: 20, right: 20, top: 10),
                        child: Column(
                          children: [
//------------------------------------DISPLAY DATE TIME AND (ADD AN ACTION) BUTTON ---------------------------------------------------------------------------------------------------------------------------------------------------
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                _addAction(),
                                SizedBox(
                                  height: 30,
                                  width: 150,
                                  child: Container(
                                      child: ElevatedButton(
                                    child: Text(
                                      '+ Add an Action',
                                      style: TextStyle(color: Colors.white),
                                    ),
                                    onPressed: () {
                                      Navigator.of(context).push(
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                AddTaskPage()),
                                      );
                                    },
                                    style: ElevatedButton.styleFrom(
                                        backgroundColor:
                                            Colors.orange.shade800),
                                  )),
                                ),
                              ],
                            ),
//---------------------------DISPLAY OF THE DAYS PART-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
                            const SizedBox(height: 10),
                            Container(
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  border: Border.all(
                                      color: Colors.black, // Set border color
                                      width: 1.0), // Set border width
                                  borderRadius: const BorderRadius.all(
                                      Radius.circular(
                                          10.0)), // Set rounded corner radius
                                  boxShadow: const [
                                    BoxShadow(
                                        blurRadius: 10,
                                        color: Colors.black,
                                        offset: Offset(1, 3))
                                  ] // Make rounded corner of border
                                  ),
                              child: DatePicker(
                                DateTime.now(),
                                height: 100,
                                width: 80,
                                initialSelectedDate: DateTime.now(),
                                selectionColor: Colors.orange.shade800,
                                selectedTextColor: Colors.black,
                                dateTextStyle: TextStyle(
                                    fontSize: 25,
                                    fontWeight: FontWeight.w600,
                                    color: Colors.green.shade900),
//----------------------------------THE MOST IMPORTANT THING METHOD IS BELOW THIS********************************--------------------------------------------------------------------------------------------------------------------------------------------------------------------
                                onDateChange: (date) {
                                  _selectedDate = date;
                                },
                              ),
                            ),
                            SizedBox(height: 10),

                            Container(
                              child: Text(
                                  DateTime.now().toString().substring(0, 10)),
                            ),
                          ],
                        ),
                      ),
//-------------------------------------------SHOW DATABASE DATA-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
                      SizedBox(height: 10),
                      _showTasks(),
                    ],
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  _notificationDisplayCurrent() {
    NotificationService().showNotification(
        title: 'example', body: 'it works', payload: 'dsdasdas');
  }

  _addAction() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            DateTime.now().toString().substring(0, 10),
            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 25),
          ),
          Text(
            'Today',
            style: GoogleFonts.lato(
                fontSize: 20,
                fontWeight: FontWeight.w700,
                fontStyle: FontStyle.italic,
                color: Colors.orange.shade900),
          )
        ],
      ),
    );
    ElevatedButton(
        child: Text('add'),
        onPressed: () async {
          await Navigator.of(context)
              .push(MaterialPageRoute(builder: (context) => AddTaskPage()));
          _taskController.getTasks();
        });
  }
}

DateTime _selectedDate = DateTime.now();

class ThemeModel with ChangeNotifier {
  ThemeMode _mode;
  ThemeMode get mode => _mode;
  ThemeModel({ThemeMode mode = ThemeMode.light}) : _mode = mode;

  void toggleMode() {
    _mode = _mode == ThemeMode.light ? ThemeMode.dark : ThemeMode.light;
    notifyListeners();
  }
}

add_task_page.dart

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import 'homepagepass.dart';
import 'models/task.dart';

class AddTaskPage extends StatefulWidget {
  AddTaskPage({super.key});

  @override
  State<AddTaskPage> createState() => _AddTaskPageState();
}

class _AddTaskPageState extends State<AddTaskPage> {
  final TaskController _taskController = Get.put(TaskController());

  final _titleController = TextEditingController();
  final _noteController = TextEditingController();

  DateTime _selectedDate = DateTime.now();
  String _endTime = "10:10 PM";
  String _startTime = DateFormat("hh:mm a").format(DateTime.now()).toString();
  int _selectedRemind = 5;
  List<int> remindList = [5, 10, 15, 30];
  String _selectedRepeat = "None";
  List<String> repeatList = ["None", "Daily", "Weekly", "Monthly"];
  int _selectedColor = 0;
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      home: SafeArea(
        child: Scaffold(
            backgroundColor: Colors.grey.shade300,
            appBar: AppBar(
                actions: [
                  IconButton(
                      onPressed: () {},
                      icon: const Center(
                          child: Icon(Icons.person_outlined, size: 30))),
                ],
                elevation: 20,
                title: const Text('TODOAPP'),
                leading: SizedBox.fromSize(
                  size: Size(56, 56), // button width and height
                  child: ClipOval(
                    child: Material(
                      color: Colors.white, // button color
                      child: InkWell(
                        splashColor: Colors.green, // splash color
                        onTap: () {
                          Navigator.of(context).push(
                            MaterialPageRoute(
                                builder: (context) => HomePagePass()),
                          );
                        }, // button pressed
                        child: const Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Icon(
                              Icons.arrow_back_ios_new,
                              size: 40,
                            ), // icon
                            // text
                          ],
                        ),
                      ),
                    ),
                  ),
                )),
            body: Container(
              padding: const EdgeInsets.only(left: 10, right: 10),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    const Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        'Add an Action',
                        style: TextStyle(
                            fontSize: 30, fontWeight: FontWeight.bold),
                      ),
                    ),
//-----------------------------------------------TITLE--------------------------------------------------------------------------------------------------------------------------------------------
                    InputFieldCustom(
                        title: 'Title',
                        hint: 'Enter the title',
                        controller: _titleController),
//-----------------------------------------------NOTE--------------------------------------------------------------------------------------------------------------------------------------------

                    InputFieldCustom(
                        title: 'Note',
                        hint: 'Enter the note',
                        controller: _noteController),
//----------------------------------------------CALENDAR-----------------------------------------------------------------------------------------------------------------------------------------------

                    InputFieldCustom(
                      title: 'Calendar',
                      hint: DateFormat.yMd().format(_selectedDate),
                      widget: IconButton(
                          onPressed: () {
                            _dataGetForUser();
                          },
                          icon: Icon(Icons.calendar_month_rounded,
                              color: Colors.orange.shade800)),
                    ),
//-------------------------------------------TIME BETWEEN--------------------------------------------------------------------------------------------------------------------------
                    Row(
                      children: [
                        Expanded(
                          child: InputFieldCustom(
                              title: 'Start To',
                              hint: _startTime,
                              widget: IconButton(
                                  onPressed: () {
                                    _dataGetTime(isStartTime: true);
                                  },
                                  icon: Icon(Icons.access_time,
                                      color: Colors.orange.shade800))),
                        ),
                        const SizedBox(width: 10),
                        Expanded(
                          child: InputFieldCustom(
                              title: 'End To',
                              hint: _endTime,
                              widget: IconButton(
                                  onPressed: () {
                                    _dataGetTime(isStartTime: false);
                                  },
                                  icon: Icon(Icons.access_time,
                                      color: Colors.orange.shade800))),
                        ),
                      ],
                    ),
//----------------------------------------REMINDER PART--------------------------------------------------------------------------------------------------------------------------------------------
                    InputFieldCustom(
                      title: 'Remind Before',
                      hint: '$_selectedRemind minutes',
                      widget: DropdownButton(
                          icon: Icon(Icons.keyboard_arrow_down,
                              color: Colors.orange.shade800),
                          iconSize: 32,
                          elevation: 4,
                          style: const TextStyle(
                              fontSize: 24, color: Colors.black),
                          underline: Container(height: 0),
                          onChanged: (String? newValue) {
                            setState(() {
                              _selectedRemind = int.parse(newValue!);
                            });
                          },
                          items: remindList
                              .map<DropdownMenuItem<String>>((int value) {
                            return DropdownMenuItem<String>(
                                value: value.toString(),
                                child: Text(value.toString()));
                          }).toList()),
                    ),
//----------------------------------------REPEATER PART--------------------------------------------------------------------------------------------------------------------------------------------
                    InputFieldCustom(
                      title: 'Repeat',
                      hint: '$_selectedRepeat',
                      widget: DropdownButton(
                          icon: Icon(Icons.keyboard_arrow_down,
                              color: Colors.orange.shade800),
                          iconSize: 32,
                          elevation: 4,
                          style: const TextStyle(
                              fontSize: 24, color: Colors.black),
                          underline: Container(height: 0),
                          onChanged: (String? newValue) {
                            setState(() {
                              _selectedRepeat = newValue!;
                            });
                          },
                          items: repeatList
                              .map<DropdownMenuItem<String>>((String? value) {
                            return DropdownMenuItem<String>(
                                value: value,
                                child: Text(value!,
                                    style:
                                        const TextStyle(color: Colors.black)));
                          }).toList()),
                    ),
//----------------------------------------COLOR PART--------------------------------------------------------------------------------------------------------------------------------------------
                    const SizedBox(height: 8),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        _colorPalette(),
//********************************SAVE BUTTON****************************************************************************************************************************************************************************************************************
                        ElevatedButton(
                          child: Text(
                            'SAVE',
                            style: TextStyle(color: Colors.white),
                          ),
                          onPressed: () {
                            _validateDate();
                          },
                          style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.orange.shade800),
                        ),
                      ],
                    )
                  ],
                ),
              ),
            )),
      ),
    );
  }

  _colorPalette() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          "Color",
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.w400),
        ),
        const SizedBox(height: 8),
        Wrap(
          children: List<Widget>.generate(5, (int index) {
            return GestureDetector(
              onTap: () {
                setState(() {
                  _selectedColor = index;
                });
              },
              child: Padding(
                padding: const EdgeInsets.only(right: 8),
                child: CircleAvatar(
                    radius: 14,
                    backgroundColor: index == 0
                        ? Colors.red
                        : index == 1
                            ? Colors.blue
                            : index == 2
                                ? Colors.green
                                : index == 3
                                    ? Colors.orange
                                    : index == 4
                                        ? Colors.pink
                                        : Colors.pink,
                    child: _selectedColor == index
                        ? const Icon(
                            Icons.done,
                            color: Colors.white,
                            size: 16,
                          )
                        : Container()),
              ),
            );
          }),
        )
      ],
    );
  }

  _addTaskToDb() async {
    int value = await _taskController.addTask(
        task: Task(
      note: _noteController.text,
      title: _titleController.text,
      date: DateFormat.yMd().format(_selectedDate),
      startTime: _startTime,
      endTime: _endTime,
      remind: _selectedRemind,
      repeat: _selectedRepeat,
      color: _selectedColor,
      isCompleted: 0,
    ));
    print("My id is" + " $value");
  }

  _validateDate() {
    if (_titleController.text.isNotEmpty && _noteController.text.isNotEmpty) {
      _addTaskToDb();
      Get.back();
      Navigator.of(context).push(
        MaterialPageRoute(builder: (context) => HomePagePass()),
      );
    } else if (_titleController.text.isEmpty || _noteController.text.isEmpty) {
      Get.snackbar('Required', 'Please fill all fields!',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.white,
          icon: Icon(
            Icons.warning_amber_rounded,
            color: Colors.red,
          ));
    }
  }

  _dataGetForUser() async {
    DateTime? _pickerCustom = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2024),
      lastDate: DateTime(2124),
    );

    if (_pickerCustom != null) {
      setState(() {
        _selectedDate = _pickerCustom;
        print(_selectedDate);
      });
    } else {
      print('its null or something wrong');
    }
  }

  _dataGetTime({required bool isStartTime}) async {
    var pickedTime = await _showTimeGet();
    String _convertedTime = pickedTime.format(context);
    if (pickedTime == null) {
    } else if (isStartTime == true) {
      setState(() {
        _startTime = _convertedTime;
      });
    } else if (isStartTime == false) {
      setState(() {
        _endTime = _convertedTime;
      });
    }
  }

  _showTimeGet() {
    return showTimePicker(
        initialEntryMode: TimePickerEntryMode.input,
        context: context,
        initialTime: TimeOfDay(
            hour: int.parse(_startTime.split(":")[0]),
            minute: int.parse(
              _startTime.split(":")[1].split(" ")[0],
            )));
  }
}

———————————-task_controller.dart

import 'package:get/get.dart';

import '../db/db_make.dart';
import '../models/task.dart';

class TaskController extends GetxController {
  @override
  void onReady() {
    super.onReady();
  }

  var taskList = <Task>[].obs;

  Future<int> addTask({Task? task}) async {
    return await DatabaseCodes.insert(task);
  }

  //get all the data from table
  void getTasks() async {
    List<Map<String, dynamic>> tasks = await DatabaseCodes.query();
    taskList.assignAll(tasks.map((data) => new Task.fromJson(data)).toList());
  }
}

———————————-db_make.dart

import 'package:sqflite/sqflite.dart';

import '../models/task.dart';

class DatabaseCodes {
  static Database? _db;
  static final int _version = 1;
  static final String _tableName = "tasks";

  static Future<void> initDb() async {
    if (_db != null) {
      return;
    }
    try {
      String _path = await getDatabasesPath() + 'tasks.db';
      _db = await openDatabase(
        _path,
        version: _version,
        onCreate: (db, version) {
          print("creating a new one");
          return db.execute(
            "CREATE TABLE $_tableName("
            "id INTEGER PRIMARY KEY AUTOINCREMENT, "
            "title STRING, note TEXT, date STRING, "
            "startTime STRING, endTime STRING,"
            "remind INTEGER, repeat STRING, "
            "color INTEGER, "
            "isCompleted INTEGER)",
          );
        },
      );
    } catch (e) {
      print(e);
    }
  }

  static Future<int> insert(Task? task) async {
    print("insert function called");
    return await _db?.insert(_tableName, task!.toJson()) ?? 1;
  }

  static Future<List<Map<String, dynamic>>> query() async {
    print('query function called');
    return await _db!.query(_tableName);
  }
}

———————————-task.dart

class Task {
  int? id;
  String? title;
  String? note;
  int? isCompleted;
  String? date;
  String? startTime;
  String? endTime;
  int? color;
  int? remind;
  String? repeat;

  Task({
    this.id,
    this.title,
    this.note,
    this.isCompleted,
    this.date,
    this.startTime,
    this.endTime,
    this.color,
    this.remind,
    this.repeat,
  });
  Task.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    title = json['title'];
    note = json['note'];
    isCompleted = json['isCompleted'];
    date = json['date'];
    startTime = json['startTime'];
    endTime = json['endTime'];
    color = json['color'];
    remind = json['remind'];
    repeat = json['repeat'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['title'] = this.title;
    data['note'] = this.note;
    data['isCompleted'] = this.isCompleted;
    data['date'] = this.date;
    data['startTime'] = this.startTime;
    data['endTime'] = this.endTime;
    data['color'] = this.color;
    data['remind'] = this.remind;
    data['repeat'] = this.repeat;
    return data;
  }
}

2

Answers


  1. Wrapping a ListView.builder directly with an expandable widget like ExpansionPanel in Flutter won’t achieve the desired result.try removing the expandable widget wrapping to listview. I hope this will solve your problem.

    Login or Signup to reply.
  2. Try removing the main() function in the homepagepass.dart and run the app again seems like you have two one in main.dart and the other one in homepagepass.dart.

    Future<void> main() async {
     WidgetsFlutterBinding
     .ensureInitialized();
     NotificationService()
     .initNotification();
    await DatabaseCodes.initDb();
    runApp(const MyApp());
    }
    

    The "main" function is typically the entry point of a program, and a programming language expects one and only one "main" function to start the program’s execution. Attempting to define multiple "main" functions would result in a syntax error.

    I hope it’ll work

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search