Flutter: Undefined name 'context'

2.3k Views Asked by At

I'm currently coding an app and I have some problems with page routing. I´m using a RouteGenerator, which works perfectly except in this case.

If I try to navigate to my second screen, I receive an error saying:

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

I would appreciate if somebody could help me with this.

Here is my code (the Project Class is in a different file):

import 'package:flutter/material.dart';

class ProjectCard extends StatefulWidget {
  const ProjectCard({
    Key? key,
    required this.project,
  }) : super(key: key);

  final Project project;

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

class _ProjectCardState extends State<ProjectCard> {
  // ignore: non_constant_identifier_names
  List<Project> demo_projects = [];
  @override
  void initState() {
    super.initState();

    demo_projects.add(Project(title: 'Test', description: 'Test', onTap: () {Navigator.pushNamed(context, '/second');}),);
  }
  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {},
      child: Container(
          decoration: BoxDecoration(
              color: secondaryColor,
              borderRadius: BorderRadius.all(Radius.circular(30))),
          padding: const EdgeInsets.all(defaultPadding),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                    widget.project.title!,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(fontSize: 20, color: primaryColor),
                  ),
              Spacer(),
              Text(
                widget.project.description!,
                maxLines: Responsive.isMobileLarge(context) ? 3 : 4,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(height: 1.5),
              ),
              Spacer(),
            ],
          )),
    );
  }
}

import 'package:flutter/material.dart';

class ProjectsGridView extends StatelessWidget {
  const ProjectsGridView({
    Key? key,
    this.crossAxisCount = 3,
    this.childAspectRatio = 1.5,
  }) : super(key: key);

  final int crossAxisCount;
  final double childAspectRatio;

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: demo_projects.length,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: crossAxisCount,
        childAspectRatio: childAspectRatio,
        crossAxisSpacing: defaultPadding,
        mainAxisSpacing: defaultPadding,
      ),
      itemBuilder: (context, index) => ProjectCard(
        project: demo_projects[index],
      ),
    );
  }
}

class Project {
  final String? title, description;
  void Function () onTap;
  

  Project({this.title, this.description, required this.onTap});
}

// ignore: non_constant_identifier_names
List<Project> demo_projects = [
  Project(
    title: "Test",
    description:
        "Test",
        onTap: (){},
  )
];
3

There are 3 best solutions below

3
On BEST ANSWER

Make your class stateful and try with initstate

import 'package:flutter/material.dart';

class ProjectCard extends StatefulWidget {
  const ProjectCard({
    Key? key,
    required this.project,
  }) : super(key: key);

  final Project project;

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

class _ProjectCardState extends State<ProjectCard> {
  List<Project> demo_projects= [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    demo_projects.add(Project(
      title: "Test",
      description:
      "Test",
      onTap: (){Navigator.pushNamed(context, '/second');},
    ),);


  }
  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {},
      child: Container(
          decoration: BoxDecoration(
              color: secondaryColor,
              borderRadius: BorderRadius.all(Radius.circular(30))),
          padding: const EdgeInsets.all(defaultPadding),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                widget.project.title!,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(fontSize: 20, color: primaryColor),
              ),
              Spacer(),
              Text(
                widget.project.description!,
                maxLines: Responsive.isMobileLarge(context) ? 3 : 4,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(height: 1.5),
              ),
              Spacer(),
            ],
          )),
    );
  }
}
2
On

You are getting this error because you have not defined the variable context anywhere and are trying to pass it on.

List<Project> demo_projects = [
  Project(
    title: "Test",
    description:
        "Test",
        onTap: (){Navigator.pushNamed(**context**, '/second');},
  ),

Usually, you have a context inside of the build method of your widgets.

@override
  Widget build(BuildContext context) {
 }

You have not provided a full code snippet, so I do not know the full implementation.

5
On

Try to declare context variable hope its help to you.

    class Project {
      final BuildContext context;
      final String title, description;
      void Function() onTap;

            Project({
              this.title,
              this.context,
              this.description,
              @required this.onTap,
          });
     }

BuildContext context;
List<Project> demo_projects = [
  Project(
    context: context,
    title: "Test",
    description: "Test",
    onTap: () {
      Navigator.pushNamed(context, '/second');
    },
  ),
];