1

can any one give me the solving for this error. i don't know when the error made and don't know what is the part of code that make this problem

this is the error that shown when i run program

═══════ Exception caught by widgets library ═══════════════════════════════════
The following _TypeError was thrown building MyApp(dirty):
type '_Type' is not a subtype of type 'BuildContext'

The relevant error-causing widget was
MyApp
package:my_first_app/main.dart:15
When the exception was thrown, this was the stack
#0      TasksCubit.get
package:my_first_app/…/mycubitclasses/taskscubit_class.dart:14
#1      new HomeLayout
package:my_first_app/layout/homelayout.dart:29
#2      MyApp.build
package:my_first_app/main.dart:24
#3      StatelessElement.build
package:flutter/…/widgets/framework.dart:4876
#4      ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4806
#5      Element.rebuild
package:flutter/…/widgets/framework.dart:4529
#6      ComponentElement._firstBuild
package:flutter/…/widgets/framework.dart:4787
#7      ComponentElement.mount
package:flutter/…/widgets/framework.dart:4781
#8      Element.inflateWidget
package:flutter/…/widgets/framework.dart:3817
#9      Element.updateChild
package:flutter/…/widgets/framework.dart:3551
#10     RenderObjectToWidgetElement._rebuild
package:flutter/…/widgets/binding.dart:1202
#11     RenderObjectToWidgetElement.mount
package:flutter/…/widgets/binding.dart:1171
#12     RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure>
package:flutter/…/widgets/binding.dart:1119
#13     BuildOwner.buildScope
package:flutter/…/widgets/framework.dart:2597
#14     RenderObjectToWidgetAdapter.attachToRenderTree
package:flutter/…/widgets/binding.dart:1118
#15     WidgetsBinding.attachRootWidget
package:flutter/…/widgets/binding.dart:953
#16     WidgetsBinding.scheduleAttachRootWidget.<anonymous closure>

and this is my main.dart file

import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:my_first_app/layout/homelayout.dart';
import 'package:my_first_app/moduls/login/login.dart';
import 'package:my_first_app/moduls/messanger/messangerscreen.dart';
import 'package:my_first_app/moduls/counter/counter_screen.dart';
import 'package:my_first_app/moduls/messanger/mydesign.dart';
import 'moduls/homescreen/HomeScreen.dart';
import 'moduls/counter/counter_screen.dart';
import 'moduls/bmiscreen/ibm_calculator.dart';
import 'shared/bloc_observ.dart';

void main() {
  //  Bloc.observer = MyBlocObserver();
 return runApp(MyApp());
}
//=========================================================
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) 
  {  
    return MaterialApp( 
      debugShowCheckedModeBanner: false  ,
      home: HomeLayout(),
    );
  }
}

i added cubit class ..maybe problem appear when i add it

and this is my HomeLayout screen

// ignore_for_file: prefer_const_constructors

import 'dart:ffi';
import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:my_first_app/moduls/archive_task_screen/archive_task.dart';
import 'package:my_first_app/moduls/done_task_screen/done_task.dart';
import 'package:my_first_app/moduls/new_task_screen/new_task.dart';
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:my_first_app/shared/componants/componants.dart';
import 'package:my_first_app/shared/mycubitclasses/taskscubit_class.dart';
import 'package:my_first_app/shared/mycubitclasses/taskstates.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import '../shared/componants/constants.dart';
class HomeLayout extends StatelessWidget 
{
  //======================variables===============================
  
  var scaffoldkey = GlobalKey<ScaffoldState>();
  var formkey = GlobalKey<FormState>();
  var titleController = TextEditingController();
  var timeController = TextEditingController();
  var dateController = TextEditingController();
 
  TasksCubit cubitt = TasksCubit.get(context);
  // scaffold contain in this screen :
  // 1. appBar  2. FAB floatingActionButton 3. body 4. bottomNavigationBar
//=================================================================
  //=================================================================
  @override
  Widget build(BuildContext context) 
  {
    return BlocProvider (
      
      create:  (context) {
        return TasksCubit()..creatDataBase();
      },
      child: Scaffold(
        key: scaffoldkey,
    //========================app bar =================================
        appBar: AppBar(
          title: Text(
            cubitt.titls[cubitt.currentindex],
          ),
        ),
    //===========================body ======================================
     
        body:  BlocBuilder<TasksCubit,TasksStates>(
          builder:  (BuildContext context, TasksStates state)
          {
            if (state is InsertDataBase)
         {
          Navigator.pop(context);
         }
         return cubitt.screens[cubitt.currentindex];
         
          }),
    //===========================FAB======================================
        floatingActionButton: FloatingActionButton(
          onPressed: () 
          {
            if (cubitt. isBottomSheetShown) 
            {
             cubitt.InserttTODataBase(
                titel: titleController.text,
                date: dateController.text,
                time: timeController.text,
                status: 'new',
              ).then((value) {
                print( '*************************** Insert succesfully  **************************');
               
                cubitt.ChangeBottomState(false,Icons.edit);
              });
            }
            else // if bottomsheet closed
            {
              scaffoldkey.currentState!.showBottomSheet(
                    (context) => Container(
                      padding: EdgeInsets.all(20.0),
                      color: Colors.grey[200],
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children:
                         [
                          DefoultFormField(
                            controller: titleController,
                            label: 'input title',
                            prefix: Icons.title,
                            type: TextInputType.text,
                            validate: ((String value) {}),
                            // validate: (String? value){
                            //   if(value!.isEmpty)
                            //   {
                            //     return' must title not empty ';
                            //   }
                            //   return null ;
                            // },
                          ),
                          SizedBox(
                            height: 5.0,
                          ),
                          //////////////////////////////////////////////////////////////////////
                          DefoultFormField(
                            controller: timeController,
                            label: 'input time',
                            prefix: Icons.watch,
                            type: TextInputType.datetime,
                            validate: ((String value) {}),
                            //  validate: (String? value){
                            //     if(value!.isEmpty)
                            //     {
                            //       return' must time not empty ';
                            //     }
                            //    // return null ;
                            //   },
                            ontap: () {
                              showTimePicker(
                                context: context,
                                initialTime: TimeOfDay.now(),
                              ).then((value) {
                                return timeController.text =
                                    value!.format(context);
                              });
                            },
                          ),
                          ///////////////////////////// formfied  date /////////////////////////////////////////
                          SizedBox(
                            height: 5.0,
                          ),
                          DefoultFormField(
                            controller: dateController,
                            label: 'input date',
                            prefix: Icons.calendar_today,
                            type: TextInputType.datetime,
                            validate: ((String value) {}),
                            // validate: (String value){
                            //   if(value.isEmpty)
                            //   return' must date not empty ';
                            //   return null ;
                            // },
                            ontap: () {
                              showDatePicker(
                                context: context,
                                initialDate: DateTime.now(),
                                firstDate: DateTime.now(),
                                lastDate: DateTime.parse('2023-05-05'),
                              ).then((value) {
                                return dateController.text =
                                    DateFormat.yMMMd().format(value!);
                              });
                            },
                          ),
    
                          //////////////////////////////////////////////////////////////////////
                        ],
                      ),
                    ),
                    // if i closed the bottomSheet in my hand not in FAB will give error so i did this :
                  )
                  .closed .then((value)
                   {
                    
                  cubitt.ChangeBottomState(false,Icons.edit);
              }); // closed func
    
              cubitt.ChangeBottomState(true,Icons.add);
            }
          },
          child: Icon(
         cubitt. fabicon,
          ),
        ),
    //========================  BottomNavigationBar =========================================
        bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          elevation: 50.0,
          currentIndex: cubitt.currentindex,
          onTap: (index) {
            cubitt.ChangeIndex(index);
          },
          backgroundColor: Colors.blue[200],
          items:
           
              [
            BottomNavigationBarItem(
              icon: Icon(
                Icons.menu,
              ),
              label: 'NEW TASK',
            ),
            BottomNavigationBarItem(
              icon: Icon(
                Icons.done_all,
              ),
              label: 'DONE TASK',
            ),
            BottomNavigationBarItem(
              icon: Icon(
                Icons.archive,
              ),
              label: 'ARCHIVE TASK',
            ),
          ],
        ),
      ),
    );
  }
//============================ finish scaffold =======================================

  




}

and this is TasksCubit class


import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:my_first_app/moduls/new_task_screen/new_task.dart';
import 'package:my_first_app/shared/mycubitclasses/taskstates.dart';
import 'package:sqflite/sqflite.dart';
import '../../moduls/archive_task_screen/archive_task.dart';
import '../../moduls/done_task_screen/done_task.dart';

class TasksCubit extends Cubit<TasksStates>
{
  
 TasksCubit():super ( InitailTasksState());
static TasksCubit get(context)=>BlocProvider.of(context);
//////////////////////////////////////////////////////////////////////
int currentindex = 0;
 List<Widget> screens = [
    NewTask(),
    DoneTask(),
    ArchiveTask(),
  ];
  List<String> titls = [
    'new task',
    'done task ',
    'archive task',
  ];
  void ChangeIndex (index)
  {
    currentindex =index;
    emit(changBottomNavBar());
  }
  var isBottomSheetShown = false;
  IconData fabicon = Icons.add;

void ChangeBottomState ( bool isShow ,IconData icon )
{
  isBottomSheetShown=isShow;
  fabicon=icon;
  emit(changBottomSheet());

}



  // **************************** DataBase ************************************
  late Database Mydatabase;
List<Map> tasks =[];
  void creatDataBase()  {
     openDatabase(
      'todo.db',
      version: 1,
      onCreate: (db, version) {
        print(
            '************************** daataBase Created  ****************************');
        db            .execute(
                'CREATE TABLE tasks (id INTEGER PRIMARY KEY,titel TEXT,date TEXT,time TEXT,status TEXT)')
            .then((value) {
          print(
              '************************** table creaated  ****************************');
        }).catchError((err) {
          print(
              '************************** error in create table  ****************************${err.toString()}');
        });
      },
      onOpen: (db) {
        // ignore: avoid_print
        print(
            '************************** daataBase opened  ****************************');
            GetDataFromDataBase(db).then((value) 
            {
            tasks=value;
            emit(GetFromDataBase());
               print(
            '************************** your table next ****************************');
              print(tasks);
               print(
            '************************** your table above ****************************');
            }
            ).catchError((err){
               print(
            '************************** error when get data  ${err.toString()} ****************************');
            });
      },
    ).then((value) {
      Mydatabase=value;
      emit(CreatDataBase());
    });
  }
//============================================================================================
//========================== insert data to dataBase =========================================

   InserttTODataBase(
      {
      required String titel,
      required String date,
      required String time,
      required String status
      }) async 
      {
    await Mydatabase.transaction((txn)
     {
      return txn.rawInsert('INSERT INTO tasks (titel,date,time,status) VALUES ("$titel","$date","$time","$status")')
          .then((value) 
       {
        print('************************** inserted successfulyt to  id ${value}  ****************************');
        emit(InsertDataBase());
         GetDataFromDataBase(Mydatabase).then((value) 
            {
            tasks=value;
            emit(GetFromDataBase());
               print( '************************** your table next ****************************');
              print(tasks);
               print('************************** your table above ****************************');
            });

      }).catchError((err) 
      {
        print('************************** error when inserted to record  ****************************${err.toString()}');
      });

    });
  }

 /////////////////////////// get data from dataBase////////////////////////////////////
 //============================================================================================

Future<List<Map>> GetDataFromDataBase (database) async
{
 return await database.rawQuery('SELECT * FROM tasks');

}

}
mayaghj
  • 15
  • 7
  • could you please include main.dart code? – eamirho3ein Sep 03 '22 at 17:17
  • they prevent me to share the main.dart file .. they said add more details and i don't know what i have to do – mayaghj Sep 03 '22 at 17:24
  • do not just add some code. also add some exposition to make it consider as edit for stackoverflow – eamirho3ein Sep 03 '22 at 17:28
  • i did that .. thanks . and i updated the question above – mayaghj Sep 03 '22 at 17:30
  • I don't think it gonna fixs it. – eamirho3ein Sep 03 '22 at 17:47
  • i run these commands 'clean flutter ' ' pub get flutter ' and wait the screen to run . so slowly – mayaghj Sep 03 '22 at 17:52
  • Can you include your `TasksCubit` – Md. Yeasin Sheikh Sep 03 '22 at 17:53
  • okay .. the commands didn't fix the problem . – mayaghj Sep 03 '22 at 17:59
  • ok i will try to add taskCubit – mayaghj Sep 03 '22 at 17:59
  • Check @Robert Sandberg's answer – Md. Yeasin Sheikh Sep 03 '22 at 18:01
  • i update the question above – mayaghj Sep 03 '22 at 18:02
  • Do not try to reply on my answer by requesting an edit on it. In short, when you run into new problems, write new issues on it. In your case here, I'm afraid you might run into a couple.. You are trying to access variables (e.g. context) that are not defined in your classes where you try to access them. You are defining controllers in the StatelessWidget. which will lead to new problems for you. – Robert Sandberg Sep 03 '22 at 18:12
  • so sorry but i am a new in stack overflow .. i will delete my edit after finished – mayaghj Sep 03 '22 at 18:15
  • No, you don't have to delete the question. When you have received a solution that helps you move forward with your problem. It does not have to solve all the problems you have. Just that it helped you move forward. Mark an appropriate answer as "accepted"/"completed", then move on to the next problem you face. – Robert Sandberg Sep 03 '22 at 18:16
  • 1
    this is not my special screen .. i am beginner in flutter and trying to apply the course – mayaghj Sep 03 '22 at 18:21
  • are you mean that i need to make new question on stack overflow because appear new problem ?? and mark accepted for your suggestion? – mayaghj Sep 03 '22 at 18:24
  • Yes if the new problem is not the same as the old problem. It is better if the questions are precise for a certain issue. If a new issue doesn't match the original question then it should be a new question, otherwise the original question handle multiple things which is not according to stackoverflow guidelines. – Robert Sandberg Sep 04 '22 at 06:02

1 Answers1

0

Context isn't available where you call:

TasksCubit cubitt = TasksCubit.get(context).

Maybe not a good idea, but if you run that line inside the build method, it'll work.

Robert Sandberg
  • 6,832
  • 2
  • 12
  • 30