Facing Errors In Flutter When Using Sqflite

Issue

import 'package:flutter/material.dart';


import 'package:todoapp/data/data.dart';

import 'package:todoapp/data/task.dart';

class TodoHome extends StatefulWidget {TodoHome({Key? key}) : super(key: key);

  @override
  _TodoHomeState createState() => _TodoHomeState();
}

class _TodoHomeState extends State<TodoHome> {

  Color mainColor= Color(0XFF0d0952);

  Color secondColor=Color(0XFF212061); 

  Color btnColor=Color(0XFFff955b);

  Color editorColor=Color(0XFF4044CC);

  TextEditingController inputcontroller= TextEditingController();
  String newTasktxt='';
  getTasks()async{
   final tasks =await DBProvider.dataBase.getTasks();
   print(tasks);
   return tasks;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
        backgroundColor: mainColor,
        title: Text("BMS ToDo",style: TextStyle(
          fontSize: 20.0,
          fontStyle: FontStyle.italic,
        ),),
        centerTitle: true,
      ),
      backgroundColor: mainColor,
      body: Column(
        children: [
          Expanded(child: FutureBuilder(
            future: getTasks  (),
            builder: (_,taskData) {
          
              switch (taskData.connectionState) {
                case ConnectionState.waiting:
                  {
                    return Center(child: CircularProgressIndicator());
                  }
                  case ConnectionState.done:
                  {
                    if (taskData.data != Null) {
                      
                      return Padding(padding: const EdgeInsets.all(9.0),
                    child: ListView.builder(

                      itemCount: taskData.data.length,
                      itemBuilder:( context, index) {
                        String task= taskData.data [index]['task'].toString();
                        String day= DateTime.parse(taskData.data [index]['creationDate']).day
                        .toString();
                        return Card(
                          color: secondColor,
                          child: InkWell(
                            onTap: (){},
                            child: Row(
                              children: [
                                Container(
                                  margin: EdgeInsets.only(right: 20.0),
                                  padding: EdgeInsets.all(8.0),
                                  decoration: BoxDecoration(
                                    color: Colors.redAccent,
                                    borderRadius: BorderRadius.circular(12.0),
                                  ),
                                  child: Text(day),

                                ),
                                Expanded(child: Padding(  
                                  padding: EdgeInsets.all(9.0),

                                child:
                                
                                Text(task)),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                      ),
                      );
                    } else{
                      return Center(
                      child: Text('Enter Your Task'),
                      );
                    }
                  }
                
                case ConnectionState.none:
                  
                  break;
                case ConnectionState.active:
                 
                  break;
              }
            }
            )),
          Container(
             padding: EdgeInsets.symmetric(horizontal: 12.0,vertical: 18.0),
            decoration: BoxDecoration(color: editorColor,borderRadius: BorderRadius.only(
              topLeft: Radius.circular(19.0),
              topRight: Radius.circular(19.0),
            )),
            
            child: Row(
              children: [
                Expanded(child:TextField(
                  controller: inputcontroller,
                  decoration: InputDecoration(  
                    filled: true,
                    fillColor: Colors.white70,
                    hintText: "Enter Your Task",
                    focusedBorder: InputBorder.none,
                    
                  ),
                ),),
                SizedBox(width: 14.0),
                FlatButton.icon(icon: Icon(Icons.add), label: Text("Add  Task"),
                color: btnColor,
                shape: StadiumBorder(),
                onPressed: (){
                  setState(() {
                    newTasktxt=inputcontroller.text.toString();
                    inputcontroller.text='';
                  });
                  Task newTask=Task(task: newTasktxt,datetime: DateTime.now() );
                  DBProvider.dataBase. addnewtask(newTask);
                },),
                
              ],
            ),
          ),
        ],
      ),
    );
  }

  
}

*The body might complete normally, causing ‘null’ to be returned, but the return type is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.
*The property ‘length’ can’t be unconditionally accessed because the receiver can be ‘null’.
Try making the access conditional (using ‘?.’) or adding a null check to the target (‘!’).
*The property ‘length’ can’t be unconditionally accessed because the receiver can be ‘null’.
Try making the access conditional (using ‘?.’) or adding a null check to the target (‘!’).
*The method ‘[]’ can’t be unconditionally invoked because the receiver can be ‘null’.
Try making the call conditional (using ‘?.’) or adding a null check to the target (‘!’).

Solution

On your FutureBuilder, the widget is not returning widget for every possible cases, you need to handle other states, replace Container with your widget.

 ....
 case ConnectionState.none:
  return Container();
case ConnectionState.active:
  return Container();
default:
  return Container();

Second issue is coming from null-safety, you need to check data if it is null , then assign it

like for itemCount

itemCount: taskData.data?.length,
 String task = taskData.data == null
    ? "no data found"
    : taskData.data![index]['task'].toString();

Do the same for others.

Check more about null-safety

Answered By – Yeasin Sheikh

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.