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

Flutter打开AlertDialog报错:未找到MaterialLocalizations如何解决?

解决 Flutter 中 No MaterialLocalizations found 错误

错误原因分析

你碰到的这个报错其实是上下文层级的问题:你传给_getCsvDocunent的是MyAppState的context,这个上下文是在MaterialApp的层级之上的——而MaterialLocalizations是MaterialApp内部提供的资源,外部的上下文根本找不到它,所以弹窗就抛出了这个异常。

解决方案:使用内部上下文修复

最简单的修复方式是用Builder组件获取MaterialApp内部的上下文,这样就能顺利访问到所需的本地化资源了。修改后的完整代码如下:

import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  void _getCsvDocunent(BuildContext ctx) async {
    if (ctx != null) _showAlert(ctx, 'Hello world');
  }
  Future _showAlert(BuildContext context, String message) async {
    return showDialog(
      context: context,
      child: AlertDialog(
        title: Text(message),
        actions: <Widget>[
          FlatButton(
            onPressed: () => Navigator.pop(context),
            child: Text('Ok'))
        ],
      ));
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Plugin example app'),
        ),
        body: Center(
          // 用Builder包裹,获取MaterialApp内部的上下文
          child: Builder(
            builder: (innerContext) {
              return Column(
                children: <Widget>[
                  FlatButton(
                    child: Text('Show alert'),
                    // 传入内部上下文innerContext
                    onPressed: () => _getCsvDocunent(innerContext),
                  ),
                ],
              );
            },
          ),
        ),
      ),
    );
  }
}

简化版思路

你也可以直接简化代码,去掉_getCsvDocunent的中转,直接在按钮回调里用内部上下文调用弹窗:

FlatButton(
  child: Text('Show alert'),
  onPressed: () {
    Builder(
      builder: (context) => _showAlert(context, 'Hello world'),
    );
  },
)

核心逻辑就是:确保调用showDialog时使用的context是MaterialApp内部的上下文,这样才能访问到它提供的本地化资源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:13:58