PeakGen
PeakGen

Reputation: 23035

Flutter: setState() or markNeedsBuild() called during build error

I am developing a flutter app. Please check the below code.

LoadingScreen2

class LoadingScreen2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _LoadingScreen2UI(),
    );
  }
}

class _LoadingScreen2UI extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _LoadingScreen2UIState();
  }
}

class _LoadingScreen2UIState extends State<_LoadingScreen2UI> {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: LayoutBuilder(builder: (context, constraints) {
          final maxHeight = constraints.maxHeight;
          return SingleChildScrollView(
            physics: BouncingScrollPhysics(),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: maxHeight * 0.1),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Text(
                      "This is a Text",
                      style: heading1Style),
                ),
                SizedBox(height: maxHeight * 0.04),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Text(
                      "This is another text",
                      style: fadedSubtitle1Style),
                ),
                SizedBox(height: maxHeight * 0.04),
                Image.asset("assets/graphics/splash.png")
              ],
            ),
          );
        }),
      ),
    );
  }

  @override
  void initState() {
    super.initState();

    initProcess();
  }

  void initProcess() async {
    LoadingScreen2Controller _loadingController = LoadingScreen2Controller();
    await _loadingController.initProcess(context);
  }
}

LoadingScreen2Controller

class LoadingScreen2Controller {
  ///
  /// Process the starting work load of the loading screen
  Future<void> initProcess(BuildContext context) async {
    final FirebaseAuthService firebaseAuthService =
        Provider.of<FirebaseAuthService>(context, listen: false);
    final UserService userService =
        Provider.of<UserService>(context, listen: false);
    final UserRoleService userRoleService =
        Provider.of<UserRoleService>(context, listen: false);
    final RoleService roleService =
        Provider.of<RoleService>(context, listen: false);

    // check whether the user is logged in
    fireauth.User? user = firebaseAuthService.getUser();

    if (user == null) {
      print("User eror: ");
      Navigator.of(context)
          .pushNamedAndRemoveUntil('/login', (Route<dynamic> route) => false);
    } else {
      // if the user is logged in, load the initial data and send him to the home screen
      String authToken = await firebaseAuthService.getUser()!.getIdToken();
      await roleService.getAllRoles(authToken);

      Navigator.of(context)
          .pushNamedAndRemoveUntil('/home', (Route<dynamic> route) => false);
    }
  }
}

You can see that in my LoadingScreen2 I am running the initState which invokes the controller class, where the controller class will grab some data and navigate to another screen.

But when it navigates, I get the following error. No crashes, but an error is generated.

E/flutter (27631): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)


E/flutter (27631): #2      _RouteEntry.handlePush.<anonymous closure>
package:flutter/…/widgets/navigator.dart:3018

E/flutter (27631): #3      TickerFuture.whenCompleteOrCancel.thunk
package:flutter/…/scheduler/ticker.dart:407

E/flutter (27631): #4      _rootRunUnary (dart:async/zone.dart:1362:47)


E/flutter (27631): #5      _CustomZone.runUnary (dart:async/zone.dart:1265:19)


E/flutter (27631): <asynchronous suspension>


E/flutter (27631): #6      TickerFuture.whenCompleteOrCancel.thunk (package:flutter/src/scheduler/ticker.dart)
package:flutter/…/scheduler/ticker.dart:1

E/flutter (27631): <asynchronous suspension>


E/flutter (27631):


W/libEGL  (27631): EGLNativeWindowType 0x7347f0e010 disconnect failed


W/libEGL  (27631): EGLNativeWindowType 0x73a765a950 disconnect failed


D/ZrHung.AppEyeUiProbe(27631): not watching, wait.

How can I fix this issue?

Upvotes: 0

Views: 436

Answers (1)

Sameera Perera
Sameera Perera

Reputation: 24

Try to call the initProcess method like this.

@override
void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
        initProcess();
    });
}

Upvotes: 1

Related Questions