You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter导航报错Undefined named 'context' 解决方案咨询

Hey there! Let's break down why you're hitting that "Undefined named 'context'" error when trying to navigate to FruitsPage, and fix it step by step.

问题根源

The Navigator.push() method needs a BuildContext to locate the app's navigation stack, but your code isn't properly passing or accessing a valid context when triggering the onTap callback. This usually happens in one of two cases:

  1. You're trying to use context in a scope where it doesn't exist (like a global variable outside a widget's build method).
  2. Your FruitsListingCards component isn't passing its own context to the onTap callback you're providing.
解决方案1:Update FruitsListingCards to pass context to the callback

First, modify your FruitsListingCards widget to accept an onTap callback that expects a BuildContext, then pass the component's own context when the gesture is triggered:

class FruitsListingCards extends StatelessWidget {
  final String fruitName;
  final String imagePath;
  // Update the onTap parameter to accept a function that takes BuildContext
  final void Function(BuildContext) onTap;

  const FruitsListingCards({
    super.key,
    required this.fruitName,
    required this.imagePath,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      // Pass the widget's context to your onTap callback
      onTap: () => onTap(context),
      child: Card(
        // Your existing card UI code here
        child: Column(
          children: [
            Image.asset(imagePath),
            Text(fruitName),
          ],
        ),
      ),
    );
  }
}

Then, when defining your map of FruitsListingCards, you can use the passed context to trigger navigation:

final fruitCards = {
  'apple': FruitsListingCards(
    fruitName: 'Apple',
    imagePath: 'assets/apple.png',
    onTap: (context) {
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => const FruitsPage()),
      );
    },
  ),
  // Add other fruit cards the same way
};
解决方案2:Define your cards inside the widget's build method

If you don't want to modify FruitsListingCards, you can instead define your fruit cards map inside the build method of your main widget. This way, you have direct access to the valid BuildContext provided by the build method:

class MainPage extends StatelessWidget {
  const MainPage({super.key});

  @override
  Widget build(BuildContext context) {
    // Define the cards here, where context is available
    final fruitCards = {
      'apple': FruitsListingCards(
        fruitName: 'Apple',
        imagePath: 'assets/apple.png',
        onTap: () {
          Navigator.push(
            context, // Use the build method's context directly
            MaterialPageRoute(builder: (context) => const FruitsPage()),
          );
        },
      ),
    };

    return Scaffold(
      body: GridView.count(
        crossAxisCount: 2,
        children: fruitCards.values.toList(),
      ),
    );
  }
}

⚠️ Important: Don't define fruitCards as a global variable outside the widget class—global variables are initialized before the widget tree is built, so there's no valid BuildContext available at that point.

Why does this error happen?

BuildContext is Flutter's way of giving widgets access to their position in the widget tree. Navigation relies on this context to find the Navigator widget that's part of your MaterialApp/CupertinoApp root. When you see "Undefined named 'context'", it means the variable context doesn't exist in the current scope—you either haven't passed it in, or you're trying to use it where it hasn't been initialized yet.

Extra Checks
  • Make sure your main page is wrapped inside a MaterialApp (or CupertinoApp). Without this root widget, Navigator won't be available, and you'll get a different error even with a valid context.
  • If you're using a StatefulWidget, you can also use context from the state class's build method, just like with a StatelessWidget.

内容的提问来源于stack exchange,提问作者Raghav Joshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 15:27:53