I am new at Flutter. I am trying to have a floatingActionButton which will open a showDialog box when pressed. But at the first code it doesn't do anything and at debug console at vscode the error is
════════ Exception caught by gesture ═══════════════════════════════════════════ No MaterialLocalizations found.
But I found the second code working correct. Would you please point out the issue with the first code. Thank you. 1st Flutter code:
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),
),
),
);
}
}
2nd Flutter code:
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.
);
}
}
After the error , I created new project (2nd one) and tried to do the same thing and worked fine. I guess there is a problem with sateless - stateful.
runApp()requires aStatelessWidgetinStatelessWidgetyou can callStatefulWidget. Your second is working because you useStatelessWidgetinrunApp(). But before using any flutter widgetMaterialAppis required.