我是 Flutter 的新手。我正在尝试使用一个 floatingActionButton,它会在按下时打开一个 showDialog 框。但是在第一个代码中它没有做任何事情并且在 vscode 的调试控制台中错误是
════════ Exception caught by gesture ═══════════════════════════════════════════ No MaterialLocalizations found.
但我发现第二个代码工作正常。请您指出第一个代码的问题。谢谢。 第一个 Flutter 代码:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future _incrementCounter() => showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text("alert"),
));
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
elevation: 0,
child: Icon(Icons.add),
),
),
);
}
}
第二个Flutter代码:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future _incrementCounter() => showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text("data"),
));
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
错误发生后,我创建了新项目(第二个)并尝试做同样的事情并且工作正常。我想无状态有问题 - 有状态。
runApp()需要一个StatelessWidget在StatelessWidget你可以调用StatefulWidget。你的第二次工作是因为你在 runApp() 中使用了 StatelessWidget。但是在使用任何 flutter 小部件之前需要MaterialApp。
好吧,发生这种情况是因为第一个代码的显示对话框确实获得了具有
Material Widget
配置的 MaterialLocalizations
的上下文,如果您添加上下文以显示对话框,第一个代码应该运行良好。在第二个代码中,它为什么起作用,因为主页已将上下文传递给showdialog
.
第一个代码试试这个:
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future _incrementCounter(BuildContext context) => showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text("alert"),
));
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () => _incrementCounter(context),
elevation: 0,
child: Icon(Icons.add),
),
),
);
}
}