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

Flutter中AppBar内IconButton导航报错Undefined name 'context'的解决求助

解决Flutter中AppBar IconButton跳转页面时context未定义的问题

这个报错的原因很明确:你在main函数里的AppBar的IconButton回调里直接使用context,但这个位置根本没有可用的BuildContext变量。而且就算你能拿到这里的context,它也没法访问到MaterialApp内部的Navigator——因为这个context是MaterialApp的父级上下文,而Navigator是MaterialApp提供的服务,必须用MaterialApp子树里的context才能调用。

下面给你两种可行的解决方案:

方案一:将AppBar移到DicePage组件内部

这是最规范的做法,因为页面的导航栏属于页面的一部分,应该和页面内容放在同一个StatefulWidget里。这样DicePage的build方法里的context就能直接用来调用Navigator了。

修改后的代码如下:

import 'package:dicee/OneDice.dart';
import 'package:flutter/material.dart';
import 'dart:math';

void main() {
  return runApp(
    const MaterialApp(
      home: DicePage(), // 直接把DicePage作为home
    ),
  );
}

class DicePage extends StatefulWidget {
  const DicePage({Key? key}) : super(key: key);

  @override
  State<DicePage> createState() => _DicePageState();
}

class _DicePageState extends State<DicePage> {
  int leftDiceNumber = 1;
  int rightDiceNumber = 3;

  void rollDice() {
    setState(() {
      leftDiceNumber = Random().nextInt(6) + 1;
      rightDiceNumber = Random().nextInt(6) + 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold( // 将Scaffold移到这里,整合AppBar和页面内容
      backgroundColor: Colors.green.shade300,
      appBar: AppBar(
        title: const Center(child: Text('Dicee')),
        backgroundColor: Colors.purple,
        elevation: 10.0,
        actions: [
          IconButton(
            onPressed: () {
              // 这里的context是DicePage的build方法提供的,可正常访问Navigator
              Navigator.of(context).push(
                MaterialPageRoute(builder: (_) => const OneDice()),
              );
            },
            icon: const Icon(
              Icons.indeterminate_check_box,
              size: 40,
            ),
          ),
        ],
      ),
      body: Center(
        child: Row(
          children: [
            Expanded(
              child: TextButton(
                onPressed: rollDice,
                child: Image.asset('images/dice$leftDiceNumber.png'),
              ),
            ),
            Expanded(
              child: TextButton(
                onPressed: rollDice,
                child: Image.asset('images/dice$rightDiceNumber.png'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

方案二:用Builder包裹IconButton获取子级context

如果你不想移动AppBar的位置,可以用Builder组件包裹IconButton,Builder会给你一个能访问到Navigator的子级context:

修改main函数里的AppBar部分代码:

appBar: AppBar(
  title: const Center(child: Text('Dicee')),
  backgroundColor: Colors.purple,
  elevation: 10.0,
  actions: [
    Builder( // 添加Builder组件
      builder: (context) { // 这里的context是Builder提供的子级上下文,可访问Navigator
        return IconButton(
          onPressed: () {
            Navigator.of(context).push(
              MaterialPageRoute(builder: (_) => const OneDice()),
            );
          },
          icon: const Icon(
            Icons.indeterminate_check_box,
            size: 40,
          ),
        );
      },
    ),
  ],
),

这样修改后,点击图标就能正常跳转到OneDice页面了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 09:02:37