Flutter Navigator.pop(context) won't work

Viewed 1961

I have seen many questions about Navigator.pop(context) but I didn't find my answer.

As you can see there are three screens so far. The Navigator.pop(context) works fine in the StoryDetailScreen and turns me back to the MainPage. The problem here with EditStoryScreen page, when I get into it I cant go back to the MainPage, when I click on the IconButton I see a black screen.

main.dart

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return 
    MultiProvider(
      providers: [
        ChangeNotifierProvider<Stories>(
          create: (_) =>
              Stories(),
        ),
        ChangeNotifierProvider<Story>(
          create:(ctx) => Story(),
        ),
      ],
      child: MaterialApp(
          title: 'MyShop',
          theme: ThemeData(
            primarySwatch: Colors.purple,
            accentColor: Colors.deepOrange,
            fontFamily: 'Lato',
          ),
          home: Mainpage(),
          routes: {
            StoryDetailScreen.routeName: (ctx) => StoryDetailScreen(),
            UserStory.routeName: (ctx) => UserStory(),
            EditStoryScreen.routeName: (ctx) => EditStoryScreen(),
          }),
    );
  }
}

Mainpage.dart

    
class Mainpage extends StatefulWidget {
  static const routeName = 'main';
  @override
  _MainpageState createState() => _MainpageState();
}

class _MainpageState extends State<Mainpage> {
  var _showOnlyFav = false;

  @override
  Widget build(BuildContext context) {
    final storyCon = Provider.of<Stories>(context);
    

    return Scaffold(

      body: SingleChildScrollView(
        child: Container(
          decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage("images/back.jpg"), fit: BoxFit.fill)),
          child: Column(children: <Widget>[
            SizedBox(
              height: 50,
            ),
            Container(
          
              child: Text("Short Stories",
                  style: TextStyle(
                      fontSize: 40, backgroundColor: Colors.grey[300])),
          
            Padding(
                padding: const EdgeInsets.all(8.0),
                child: Container(
                   
                    child: Row(
                      children: [
                        
                        Container(
                          height: 40,
                          width: 290,
                          decoration: BoxDecoration(
                              color: Colors.grey[300],
                              border: Border.all(width: 1, color: Colors.black),
                              borderRadius: BorderRadius.circular(7)
                              // image: DecorationImage(
                              //     image: AssetImage("images/text.png"))
                              ),
                          child: Center(
                            child: Row(
                              children: [
                                InkWell(
                                  onTap: () {
                                    Navigator.of(context).pushReplacementNamed(UserStory.routeName);
                                  },
                                                                  child: Text(
                                    "Edit Stroy",
                                    style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      color: Colors.black,
                                      fontSize: 30,
                                      // backgroundColor: Colors.grey[300]),
                                    ),
                                  ),
                                ),
                                InkWell(
                                  onTap: () {
                                    Navigator.of(context).pushReplacementNamed(EditStoryScreen.routeName);
                                  },
                                                                  child:Text(
                                  "Add Stroy",
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Colors.black,
                                    fontSize: 30,
                                    // backgroundColor: Colors.grey[300]),
                                  ),
                                ),)
                                
                              ],
                            ),
                          ),
                        ),
                      ],
                    ))),
            StorysGrid(_showOnlyFav),
          ]),
        ),
      ),
    );
  }
}

EditStoryScreen.dart

class EditStoryScreen extends StatefulWidget {
  static const routeName = 'edit';
  

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

class _EditStoryScreenState extends State<EditStoryScreen> {
  final _storyFocusNode = FocusNode();
  final _imgController = TextEditingController();
  final _imgFocusNode = FocusNode();

  @override
  void initState() {
    _imgFocusNode.addListener(updateImg);
    super.initState();
  }

  @override
  void dispose() {
    _imgFocusNode.removeListener(updateImg);
    _storyFocusNode.dispose();
    _imgController.dispose();
    _imgFocusNode.dispose();
    super.dispose();
  }

  void updateImg() {
    if (!_imgFocusNode.hasFocus) {
      setState(() {});
    }
  }
  // void backToHome(context) {
  //   Navigator.pushReplacementNamed(BuildContext(), context);
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Container(
          height: 650,
          color: Colors.white,
          child: Column(
            children: [
              SizedBox(
                height: 30,
              ),
              Align(
                  alignment: Alignment.topLeft,
                  child: RaisedButton(
                      child: Icon(Icons.arrow_back_ios),
                      onPressed: () => Navigator.pop(context)
                      
                      )),
              Padding(
                padding: const EdgeInsets.fromLTRB(15, 10, 15, 15),
                child: Form(
                  child: ListView(
                    shrinkWrap: true,
                    children: <Widget>[
                      TextFormField(
                        decoration: InputDecoration(labelText: "Title"),
                        textInputAction: TextInputAction.next,
                        onFieldSubmitted: (_) {
                          FocusScope.of(context).requestFocus(_storyFocusNode);
                        },
                      ),
                      TextFormField(
                        decoration: InputDecoration(labelText: "Story's text"),
                        maxLines: 14,
                        keyboardType: TextInputType.multiline,
                        focusNode: _storyFocusNode,
                      ),
                      Row(
                        children: [
                          Container(
                            width: 100,
                            height: 100,
                            margin: EdgeInsets.only(top: 8, right: 10),
                            decoration: BoxDecoration(
                              border: Border.all(width: 1, color: Colors.grey),
                            ),
                            child: _imgController.text.isEmpty
                                ? Text("Enter a Url")
                                : Center(
                                    child: FittedBox(
                                      child: Image.network(
                                        _imgController.text,
                                      ),
                                    ),
                                  ),
                          ),
                          Container(
                            width: 200,
                            child: TextFormField(
                              decoration: InputDecoration(
                                labelText: "Image URL",
                              ),
                              keyboardType: TextInputType.url,
                              textInputAction: TextInputAction.done,
                              controller: _imgController,
                              focusNode: _imgFocusNode,
                            ),
                          )
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

StoryDetailScreen.dart

class StoryDetailScreen extends StatelessWidget {
  // final String title;
  // final double price;

  // ProductDetailScreen(this.title, this.price);
  static const routeName = '/story-detail';

  @override
  Widget build(BuildContext context) {
    final storyId =
        ModalRoute.of(context).settings.arguments as String; // is the id!
    final loadedStory = Provider.of<Stories>(
      context,
      listen: false,
    ).findById(storyId);
    return Scaffold(
      body: SingleChildScrollView(
        child: Container(
          width: double.infinity,
          // height: 700,
          decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage("images/back1.jpg"), fit: BoxFit.fill)),
          // color: Color(0xfffae3d9),
          // child: Column(children: <Widget>[
          //   SizedBox(
          //     height: 10,
          //   ),
          //   Container(
          //     width: 340,
          child:
              Column(crossAxisAlignment: CrossAxisAlignment.center, children: [
            SizedBox(
              height: 50,
            ),
            Align(
                alignment: Alignment.topLeft,
                child: RaisedButton(
                  
                  child: Icon(Icons.arrow_back_ios),
                  onPressed: (){
                    Navigator.pop(context);

                })
              ),

            Card(
              elevation: 10,
              margin: EdgeInsets.all(10),
              child: Text("${loadedStory.title}",
                  softWrap: false,
                  textDirection: TextDirection.ltr,
                  style: TextStyle(
                    color: Color(0xFF6a2c70),
                    decorationColor: Colors.black,
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                  )),
            ),
            SizedBox(height: 30),

            Container(
              width: double.infinity,
              color: Colors.white70,
              child: Padding(
                padding:
                    const EdgeInsets.symmetric(vertical: 10, horizontal: 5),
                child: Text(
                  loadedStory.story,
                  textDirection: TextDirection.rtl,
                  style: TextStyle(
                    color: Color(0xFF6a2c70),
                    decorationColor: Colors.black,
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                    // fontFamily: "Kufam"),
                  ),
                ),
              ),
            ),
            SizedBox(
              height: 20,
            ),
            Card(
              child: Container(
                height: 60,
                width: 210,
                decoration: BoxDecoration(color: Colors.white60),
                child: Center(
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Like(),
                      ]),
                ),
              ),
            ),

            // ],

            // )
            SizedBox(
              height: 30,
            )
          ]),
        )
        // ]
        ,
      ),
      // ),
      // ),
    );
  }
}
2 Answers

You're invoking

Navigator.of(context).pushReplacementNamed(UserStory.routeName)

so this is removing your Mainpage from the navigation stack and replacing it with UserStory, which is why when you call Navigator.pop(context), there's nothing to go back to and all you get is a black screen.

Change it to Navigator.of(context).pushNamed(UserStory.routeName).

You have to define the Mainpage route as well in the routes.

Related