Home > Mobile >  FlutterError (setState() or markNeedsBuild() called during build
FlutterError (setState() or markNeedsBuild() called during build

Time:10-16

I have a phone number login screen via Firebase Auth. Then on successful authentication, it takes me to the home page where I need to check the user for their filled in name. If the user has no name in the table, then show screen 1 and if the user has a name, then show screen 2.

Main.dart -> Phone.dart -> OTP.dart -> Home.dart -> Screen1.dart | Screen2.dart

I execute the following code on the home page, but I get an error when I log in to my account:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

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

  @override
  State<MyHome> createState() => _MyHomeState();
}

class _MyHomeState extends State<MyHome> {
  @override
  void initState() {
    super.initState();
    getuserData();
    checkUser();
  }

  Future getuserData() async {
    await FirebaseFirestore.instance
        .collection('users')
        .orderBy('name')
        .get()
        .then((snapshot) => snapshot.docs.forEach((document) {
              print(document.reference);
            }));
  }

  checkUser() {
    if (getuserData() != null) {
      Navigator.pushNamedAndRemoveUntil(context, "Screen1", (route) => false);
    } else {
      Navigator.pushNamedAndRemoveUntil(
          context, "Screen2", (route) => false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Home"),
      ),
      body: Container(
        child: Column(),
      ),
    );
  }
}

What am I doing wrong?

CodePudding user response:

WidgetsBinding.instance.addPostFrameCallback((_){
    getuserData();
    checkUser();
});
  • Related