dart Navigator.pushReplacement in function Undefined name ‘context’

Issue

I am new to flutter, so I want to create a app that contains buttons and buttons navigate to different pages. for that I defined a variable called toFunc inside the Cards (Cards are buttons on the homepage). All I want to for each button define a function that navigate to relevant page. For errors (if something goes wrong) i create a stateless widget called UnderConstruction but when I use it under the Card widget there is no problem but when I define a variable and attach it to that variable toFunc it gives me an error like:

Undefined name 'context'.
Try correcting the name to one that is defined, or defining the name.

so I am attaching the code if anyone can help me I appreciate that.

Homepage:

    class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: Text("BFOBKG"),
        backgroundColor: BfobkgBlue,
      ),
      backgroundColor: BfobkgYellow,
      drawer: new Drawer(
        child: ListView(
          children: <Widget>[
            UserAccountsDrawerHeader(
              accountName: new Text(
                "Oğuzhan Recep Akkol",
                style: new TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 17.0,
                ),
              ),
              accountEmail: new Text("oraakkol674@gmail.com"),
              currentAccountPicture: CircleAvatar(
                backgroundImage: NetworkImage(
                    "https://banner2.cleanpng.com/20180623/iqh/kisspng-computer-icons-avatar-social-media-blog-font-aweso-avatar-icon-5b2e99c40ce333.6524068515297806760528.jpg"),
              ),
              decoration: new BoxDecoration(
                color: BfobkgRed,
              ),
            ),
            ListTile(
              leading: Icon(Icons.person),
              title: Text("Profile"),
            ),
            ListTile(
              leading: Icon(Icons.vpn_key),
              title: Text("Password"),
            ),
            ListTile(
              leading: Icon(Icons.info),
              title: Text("Information"),
            ),
            ListTile(
              leading: Icon(Icons.backpack),
              title: Text("Backpack"),
            ),
          ],
        ),
      ),
      body: Container(
        padding: EdgeInsets.all(30.0),
        child: GridView.count(
          mainAxisSpacing: 20,
          crossAxisCount: 2,
          children: <Widget>[
            Cards(
              icon: "assets/icons/movie-frame-with-number-one.svg",
              clr: Colors.grey,
              title: 'BFÖBKG Volume One',
              toFunc: toConstruct,
            ),
            Cards(
              icon: "assets/icons/two-in-film-strip-photogram.svg",
              clr: Colors.grey,
              title: 'BFÖBKG Volume Two',
              toFunc: toConstruct,
            ),
            Cards(
              icon: "assets/icons/010-search.svg",
              clr: Colors.grey,
              title: 'Suggest Me A Film',
              toFunc: toConstruct,
            ),
            Cards(
              icon: "assets/icons/091-bar chart.svg",
              clr: Colors.grey,
              title: 'Statistics',
              toFunc: toConstruct,
            ),
            Cards(
              icon: "assets/icons/092-user.svg",
              clr: Colors.grey,
              title: 'Profile',
              toFunc: toConstruct,
            ),
            Cards(
              icon: "assets/icons/051-server.svg",
              clr: Colors.grey,
              title: 'Settings',
              toFunc: toConstruct,
            ),
            Cards(
              icon: "assets/icons/031-telephone call.svg",
              clr: Colors.grey,
              title: 'Contact Us',
              toFunc: toConstruct,
            ),
            Cards(
              icon: "assets/icons/048-padlock.svg",
              clr: Colors.grey,
              title: 'Admin Login',
              toFunc: toConstruct,
            ),
          ],
        ),
      ),
    );
  }
}

UnderConstruction:

    class UnderConstructionScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        fit: StackFit.expand,
        children: [
          Image.asset(
            "assets/images/8_404 Error.png",
            fit: BoxFit.cover,
          ),
          Positioned(
            bottom: MediaQuery.of(context).size.height * 0.14,
            left: MediaQuery.of(context).size.width * 0.065,
            child: Container(
              decoration: BoxDecoration(
                boxShadow: [
                  BoxShadow(
                    offset: Offset(0, 5),
                    blurRadius: 25,
                    color: Colors.black.withOpacity(0.17),
                  ),
                ],
              ),
              child: Center(
                child: TextButton(
                  onPressed: () {
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) > HomePage(),
                    ));
                  },
                  child: Text("Back to Homepage",
                      style: TextStyle(
                          color: Colors.black,
                          fontSize: 17,
                          fontFamily: "Cairo")),
                  style: TextButton.styleFrom(
                    primary: Colors.white,
                    backgroundColor: Colors.greenAccent,
                    onSurface: Colors.grey,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30),
                    ),
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}

Homepage buttons (cards):

    class Cards extends StatelessWidget {
  Cards({
    required this.title,
    required this.icon,
    required this.clr,
    required this.toFunc,
  });

  final String title;
  final String icon;
  final MaterialColor clr;
  final Function toFunc;

  @override
  Widget build(BuildContext context) {
    return Card(
      color: BfobkgBackground,
      shadowColor: Colors.black,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
      ),
      elevation: 7.5,
      margin: EdgeInsets.only(left: 8, right: 8),
      child: InkWell(
        borderRadius: BorderRadius.circular(20),
        onTap: toFunc(),
        splashColor: clr[300],
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              SvgPicture.asset(
                icon,
                height: 100,
                width: 150,
                semanticsLabel: title,
              ),
              Text(title,
                  style: new TextStyle(
                      fontSize: 16.0,
                      fontWeight: FontWeight.w700,
                      fontFamily: "Cairo"))
            ],
          ),
        ),
      ),
    );
  }
}

to Construct :

toConstruct(BuildContext context) {
Navigator.pushReplacement(
    context,
    MaterialPageRoute(
      builder: (context) > UnderConstructionScreen(),
    ));

Solution

I tried to get your example running, but was not getting that same error. However, I had to make a few changes.

I changed the type of the toFunc field from Function to void Function(BuildContext).

I also added the method toConstruct under the HomePage widget.

void toConstruct(BuildContext context) {
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) > UnderConstructionScreen()),
  );
}

Now the toFunc Method of Cards can be called using onTap: () > toFunc(context).

Here is the full example, but I removed graphics and exchanged custom colors:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  void toConstruct(BuildContext context) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) > UnderConstructionScreen()),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: Text("BFOBKG"),
        backgroundColor: Colors.blue,
      ),
      backgroundColor: Colors.yellow,
      drawer: new Drawer(
        child: ListView(
          children: <Widget>[
            UserAccountsDrawerHeader(
              accountName: new Text(
                "Oğuzhan Recep Akkol",
                style: new TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 17.0,
                ),
              ),
              accountEmail: new Text("oraakkol674@gmail.com"),
              currentAccountPicture: CircleAvatar(
                backgroundImage: NetworkImage(
                    "https://banner2.cleanpng.com/20180623/iqh/kisspng-computer-icons-avatar-social-media-blog-font-aweso-avatar-icon-5b2e99c40ce333.6524068515297806760528.jpg"),
              ),
              decoration: new BoxDecoration(
                color: Colors.red,
              ),
            ),
            ListTile(
              leading: Icon(Icons.person),
              title: Text("Profile"),
            ),
            ListTile(
              leading: Icon(Icons.vpn_key),
              title: Text("Password"),
            ),
            ListTile(
              leading: Icon(Icons.info),
              title: Text("Information"),
            ),
            ListTile(
              leading: Icon(Icons.backpack),
              title: Text("Backpack"),
            ),
          ],
        ),
      ),
      body: Container(
        padding: EdgeInsets.all(30.0),
        child: GridView.count(
          mainAxisSpacing: 20,
          crossAxisCount: 2,
          children: <Widget>[
            Cards(
              icon: "assets/icons/movie-frame-with-number-one.svg",
              clr: Colors.grey,
              title: 'BFÖBKG Volume One',
              toFunc: toConstruct,
            ),
            Cards(
              icon: "assets/icons/two-in-film-strip-photogram.svg",
              clr: Colors.grey,
              title: 'BFÖBKG Volume Two',
              toFunc: toConstruct,
            ),
            Cards(
              icon: "assets/icons/010-search.svg",
              clr: Colors.grey,
              title: 'Suggest Me A Film',
              toFunc: toConstruct,
            ),
            Cards(
              icon: "assets/icons/091-bar chart.svg",
              clr: Colors.grey,
              title: 'Statistics',
              toFunc: toConstruct,
            ),
            Cards(
              icon: "assets/icons/092-user.svg",
              clr: Colors.grey,
              title: 'Profile',
              toFunc: toConstruct,
            ),
            Cards(
              icon: "assets/icons/051-server.svg",
              clr: Colors.grey,
              title: 'Settings',
              toFunc: toConstruct,
            ),
            Cards(
              icon: "assets/icons/031-telephone call.svg",
              clr: Colors.grey,
              title: 'Contact Us',
              toFunc: toConstruct,
            ),
            Cards(
              icon: "assets/icons/048-padlock.svg",
              clr: Colors.grey,
              title: 'Admin Login',
              toFunc: toConstruct,
            ),
          ],
        ),
      ),
    );
  }
}

class UnderConstructionScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        fit: StackFit.expand,
        children: [
          Positioned(
            bottom: MediaQuery.of(context).size.height * 0.14,
            left: MediaQuery.of(context).size.width * 0.065,
            child: Container(
              decoration: BoxDecoration(
                boxShadow: [
                  BoxShadow(
                    offset: Offset(0, 5),
                    blurRadius: 25,
                    color: Colors.black.withOpacity(0.17),
                  ),
                ],
              ),
              child: Center(
                child: TextButton(
                  onPressed: () {
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) > HomePage(),
                    ));
                  },
                  child: Text("Back to Homepage",
                      style: TextStyle(
                          color: Colors.black,
                          fontSize: 17,
                          fontFamily: "Cairo")),
                  style: TextButton.styleFrom(
                    primary: Colors.white,
                    backgroundColor: Colors.greenAccent,
                    onSurface: Colors.grey,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30),
                    ),
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}

class Cards extends StatelessWidget {
  Cards({
    required this.title,
    required this.icon,
    required this.clr,
    required this.toFunc,
  });

  final String title;
  final String icon;
  final MaterialColor clr;
  final void Function(BuildContext) toFunc;

  @override
  Widget build(BuildContext context) {
    return Card(
      color: Colors.blue,
      shadowColor: Colors.black,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
      ),
      elevation: 7.5,
      margin: EdgeInsets.only(left: 8, right: 8),
      child: InkWell(
        borderRadius: BorderRadius.circular(20),
        onTap: () > toFunc(context),
        splashColor: clr[300],
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Text(
                title,
                style: new TextStyle(
                  fontSize: 16.0,
                  fontWeight: FontWeight.w700,
                  fontFamily: "Cairo",
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

Answered By – Tim Brückner

Leave a Comment