1

I am trying to create a sample and I am trying to create a navigation from a statefulWidget, I am getting the below error, most of the samples talk about navigation between stateless widgets

flutter: ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
flutter: The following assertion was thrown while handling a gesture:
flutter: Navigator operation requested with a context that does not include a Navigator.
flutter: The context used to push or pop routes from the Navigator must be that of a widget that is a
flutter: descendant of a Navigator widget.

below is my code

import 'package:flutter/material.dart';
import 'package:flutter_app/second.dart';

main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  var strings = ["Flutter", "Java", "SWift"];
  var displayText = "";

  void onPressed() {
    var list = List<int>.generate(3, (int index) => index); // [0, 1, 4]
    list.shuffle();
    print(list);

    setState(() {
      displayText = strings[list.first];
    });
  }

  @override
  Widget build(BuildContext context) {
    var scaffold = Scaffold(
      appBar: AppBar(
        title: Text('Flutter Second'),
      ),
      body: Container(
          child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              displayText,
              style: TextStyle(
                  color: Colors.red,
                  fontStyle: FontStyle.normal,
                  fontWeight: FontWeight.bold,
                  fontSize: 30.0),
            ),
            Padding(
              padding: EdgeInsets.all(10.0),
            ),
            RaisedButton(
              child: Text('Change'),
              textColor: Colors.black,
              onPressed: () {
                Navigator.pushNamed(context, '/second'); // Fails here
              },
            )
          ],
        ),
      )),
    );
    return MaterialApp(
      home: scaffold,
      routes: {
        '/second': (context) => SecondScreen(),
      },
    );
  }
}

Below is what I have tried

  1. Used Navigator.of(context)

  2. Wrapped the statefulwidget as a home of a material app created from a statelesswidget.

but no luck.

anoop4real
  • 7,598
  • 4
  • 53
  • 56

0 Answers0