1

Question When I used MaterialPageRoute my Text Widget in page 2 isn't showing. What I do here wrong?

My main page

class _MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            floatingActionButton: FloatingActionButton(
              onPressed: () {
                Navigator.push(context,
                    new MaterialPageRoute(builder: (context) => Page2()));
              },
            ),
            body: Container(
              child: Center(
                  child: Text(
                'Page 1',
                style: TextStyle(fontSize: 30.0),
              )),
            )));
  }
}

Page2 (The message that I print "Moved to page 1" printed to the screen actually.

import 'package:flutter/material.dart';

class Page2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var black = Colors.black;
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.pop(context);
            print("Moved to page 1");
          },
        ),
        backgroundColor: Colors.blue,
        body: Container(
          child: Center(
            child: Text(
              'Page 2',
              style: TextStyle(
                fontSize: 2.0,
              ),
            ),
          ),
        ));
  }
}

Thanks

Aspis
  • 55
  • 5

1 Answers1

0

Try to remove the home body and put it inside a new class like this

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Page1());
  }
}

class Page1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            print('a');
            Navigator.push(context,
                MaterialPageRoute(builder: (context) => Page2()));
          },
        ),
        body: Container(
          child: Center(
              child: Text(
                'Page 1',
                style: TextStyle(fontSize: 30.0),
              )),
        ));
  }
}

class Page2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var black = Colors.black;
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.pop(context);
            print("Moved to page 1");
          },
        ),
        backgroundColor: Colors.blue,
        body: Container(
          child: Center(
            child: Text(
              'Page 2',
              style: TextStyle(
                fontSize: 2.0,
              ),
            ),
          ),
        ));
  }
}

This is happening due to the context that you are passing to navigator. For more info you can read this Navigator operation requested with a context that does not include a Navigator

Anirudh Sharma
  • 657
  • 7
  • 19