How to fix "No MaterialLocalizations found" error in Flutter
The No MaterialLocalizations found error appears in Flutter when using Material widgets outside of a MaterialApp context. This post explains how to fix it and prevent it in your projects.
Why does the “No MaterialLocalizations found” error occur?
This error means you’re using a Material widget (like Scaffold
, TextField
, or AlertDialog
) outside of a MaterialApp
or without proper localization setup. The MaterialLocalizations
widget is added automatically by MaterialApp
, and is required for many Material components to work correctly.
Example scenario:
If you try to show a dialog using a context that isn’t under a MaterialApp
, you’ll get this error. For example:
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Test"),
content: Text("Done..!"),
);
},
);
If the context doesn’t have MaterialLocalizations
, the dialog can’t be shown.
How to fix the “No MaterialLocalizations found” error
Here are the steps to resolve this error:
1. Wrap your app in a MaterialApp
Make sure your app’s root widget is MaterialApp
:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
title: "Test",
home: TestPage(),
);
}
}
2. Use the correct BuildContext
When showing dialogs or navigating, always use a context that is a descendant of MaterialApp
. For example, use the context from a widget’s build
method, not from a global or ancestor widget.
3. Provide localization delegates if needed
If you’re using custom navigation or advanced localization, ensure you provide the necessary localization delegates in your MaterialApp
:
MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: [
const Locale('en', ''), // English, no country code
// Add other supported locales here
],
// ...
)
Best practices to avoid this error
- Always wrap your app in a
MaterialApp
when using Material widgets. - Use the correct context for dialogs and navigation.
- Set up localization if your app supports multiple languages.
Conclusion
The “No MaterialLocalizations found” error in Flutter is common, but easy to fix by wrapping your app in a MaterialApp
and using the right context. Following best practices will help you avoid this error and build more robust Flutter apps.
Need help with Flutter or cross-platform development? Our team is here to help you debug and build better apps!
Click the button below to book a free consultation with us 🤝
Book Free Consultation