Home > Software engineering >  Flutter Sqflite Toggling between Screens based on Login Status creates null operator used on null va
Flutter Sqflite Toggling between Screens based on Login Status creates null operator used on null va

Time:10-18

I am trying to toggle between Login Screen and HomeScreen based on the user status. The logic seems to be working as long as I don't put HomeScreen. I replaced HomeScreen with a different screen to check and the app works as it should. It displays different screens on hot restart based on the user's login status. But as soon as I try to put HomeScreen I get null operator used on null value error.

Here is the toggle logic.

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

  @override
  State<Testing> createState() => _TestingState();
}

class _TestingState extends State<Testing> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: TodoServiceHelper().checkifLoggedIn(),
      builder: ((context, snapshot) {
        if (!snapshot.hasData) {
          return Container(
            child: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
        if (snapshot.hasError) {
          print(snapshot.hasError);
          return Container(
            child: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
        if (snapshot.data!.isNotEmpty) {
          print(snapshot.data);
          return RegisterPage();
          // returning HomePage gives null check operator used on null value error
        } else
          return Login();
      }),
    );
  }
}

Here is the HomeScreen

class HomePage extends StatefulWidget {
  String? username;
  HomePage({this.username});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final GlobalKey<FormState> formKey = GlobalKey();
  TextEditingController termController = TextEditingController();
  void clearText() {
    termController.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          IconButton(
            onPressed: () {
              User loginUser =
                  User(username: widget.username.toString(), isLoggedIn: false);
              TodoServiceHelper().updateUserName(loginUser);
              Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(
                      builder: (BuildContext context) => Login()));
            },
            icon: Icon(Icons.logout),
            color: Colors.white,
          )
        ],
        title: FutureBuilder(
            future: TodoServiceHelper().getTheUser(widget.username!),
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return Container(
                  child: Center(
                    child: CircularProgressIndicator(),
                  ),
                );
              }
              return Text(
                'Welcome ${snapshot.data!.username}',
                style: TextStyle(color: Colors.white),
              );
            }),
      ),
      body: SingleChildScrollView(
        child: Column(children: [
          Column(
            children: [
              Padding(
                padding: const EdgeInsets.all(12.0),
                child: Form(
                  key: formKey,
                  child: Column(
                    children: <Widget>[
                      TextFormField(
                        controller: termController,
                        decoration: InputDecoration(
                          filled: true,
                          fillColor: Colors.white,
                          enabledBorder: OutlineInputBorder(),
                          labelText: 'search todos',
                        ),
                      ),
                      TextButton(
                          onPressed: () async {
                            await Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => ShowingSerachedTitle(
                                        userNamee: widget.username!,
                                        searchTerm: termController.text,
                                      )),
                            );

                            print(termController.text);
                            clearText();
                            setState(() {});
                          },
                          child: Text(
                            'Search',
                          )),
                      Divider(
                        thickness: 3,
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          Container(
            child: Stack(children: [
              Positioned(
                bottom: 0,
                child: Text(
                  ' done Todos',
                  style: TextStyle(fontSize: 12),
                ),
              ),
              IconButton(
              
                onPressed: () async {
                  await Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) =>
                            CheckingStuff(userNamee: widget.username!)),
                  );
                  setState(() {});
                },
                icon: Icon(Icons.filter),
              ),
            ]),
          ),
          Divider(
            thickness: 3,
          ),
          Container(
            child: TodoListWidget(name: widget.username!),
            height: 1000,
            width: 380,
          )
        ]),
      ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Color.fromARGB(255, 255, 132, 0),
      
        onPressed: () async {
          await showDialog(
            barrierDismissible: false,
            context: context,
            builder: ((context) {
              return AddNewTodoDialogue(name: widget.username!);
            }),
          );
          setState(() {});
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

The function used to return user with loginStatus true

  Future<List<User>> checkifLoggedIn() async {
    final Database db = await initializeDB();
    final List<Map<String, Object?>> result = await db.query(
      'users',
      where: 'isLoggedIn = ?',
      whereArgs: ['1'],
    );
    List<User> filtered = [];
    for (var item in result) {
      filtered.add(User.fromMap(item));
    }
    return filtered;
  }

CodePudding user response:

the problem is here enter image description here

enter image description here

you used ! sign on a nullable String , and this string is nullable, try to use this operation (??) so make it widget.username??"" by this line you will check if the user name is null it will be replaced by an empty string.

  • Related