Search code examples
flutternavigationflutter-layoutnavigator

Navigator.pop not working and show black background?


I try back to previous screen. But UI only show black background and it only happens on this screen. I tried both Navigator.pop(context); and Navigator.of(context).pop();.

This my code:

return MaterialApp(
    home: SafeArea(
  child: Scaffold(
    body: BlocBuilder<TimeKeepingCubit, TimeKeepingState>(
    builder: (context, state)
{
  var scale = 1.0;
  if (state.controller != null){
    var camera = state.controller!.value;
    // fetch screen size
    final size = MediaQuery.of(context).size;

    // calculate scale depending on screen and camera ratios
    // this is actually size.aspectRatio / (1 / camera.aspectRatio)
    // because camera preview size is received as landscape
    // but we're calculating for portrait orientation
    var scale = size.aspectRatio * camera.aspectRatio;

    // to prevent scaling down, invert the value
    if (scale < 1) scale = 1 / scale;
  }
  return Stack(
    children: [
      state.controller == null ? SizedBox() : Center(
        child: Transform.scale(
          scale: scale,
          child: Center(
            child: CameraPreview(state.controller!),
          ),
        ),
      ),
      Visibility(
        visible: state is TimeKeepingLoading,
        child: Center(
            child: Container(
                width: 68,
                height: 68,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: AppColors.whiteE0E0E0),
                child: CupertinoActivityIndicator())
        ),
      ),
      buildAlignScafoldScan(),
      Positioned(
        top: 0,
        left: 0,
        child: IconButton(
          icon: SvgPicture.asset(Res.ic_back_left_blue),
          onPressed: () {
            Navigator.pop(context);
            // Navigator.of(context).pop();
          },
        ),
      ),

Solution

  • I finally found my problem. That's the context in this code

    BlocBuilder<TimeKeepingCubit, TimeKeepingState>(
        builder: (context, state)
    

    make when used Navigator.pop(context); inside it causes black screen. My solution was to create a function that scopes use Navigator.pop(context); is no longer in the BlocBuilder. It will use the context of the main screen.

    void backToPreScreen() {
      Navigator.pop(context);
    }