Initstate isn't referenced Flutter Problem - flutter

i am facing a new problem with my code, and honestly, I cant figure out where is my mistake , i have made the exact same widget in another file, and runs perfectly.
I'm starting to believe that there is one problem with some widgets maybe.
I paste my code so you can check it out and tell me where is my mistake (very common ) or maybe is some widget/ line of code that is breaking the code.
import 'package:flutter/material.dart';
void main(List<String> args) {
runApp(MaterialApp(
home: Scaffold(
body: Products(),
),
));
}
class Products extends StatefulWidget {
Products({Key key}) : super(key: key);
#override
_ProductsState createState() => _ProductsState();
}
Class _ProductsState extends State<Products> {
#override
Widget build(BuildContext context) {
bool valoractual;
#override
void initState() {
super.initState();
valoractual = false;
}
return Scaffold(
appBar: AppBar(
backgroundColor: Color.fromRGBO(239, 180, 185, 1),
actions: <Widget>[
Icon(
Icons.search,
size: 25,
),
Switch(
activeColor: Colors.white,
inactiveThumbColor: Colors.blue[900],
value: valoractual,
onChanged: (bool cambio) {
setState(() {
valoractual = cambio;
});
//cambiovalor();
if (valoractual) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => AlertDialog(
content: Text(" delete option"),
actions: [
FlatButton(
onPressed: () {
print("****************");
print(valoractual);
Navigator.of(context).pop();
return valoractual;
},
child: Text("Continue"),
)
],
),
);
} else {
showDialog(
context: context,
builder: (context) => AlertDialog(
content:
Text("view option"),
actions: [
FlatButton(
onPreenter code heressed: () {
print("****************");
print(valoractual);
Navigator.of(context).pop();
return valoractual;
},
child: Text("Aceptar"),
)
],
),
);
}
},
),
Icon(Icons.delete, size: 20),
],
),
body: Container(
margin: EdgeInsets.only(top: 10),
child: Text("this is sample text"),
),
);
}
}

used the following code style
Happy Coding :)

try to put your initState function out of the build function
like
Class _ProductsState extends State<Products> {
bool valoractual;
#override
void initState() {
super.initState();
valoractual = false;
}
#override
Widget build(BuildContext context) {
return Scaffold(

Related

Flutter build not behaving as expected

I'm trying to make a note app but there is a yellow square showing on the screen.
I've included the main.dart code and also allnotesscreens.dart. I think there is something wrong with allnotesscreens code, but I don't know what.
Maybe _loadViewMode() part.
Why this problem is happening?!!!
Main.dart:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'providers/label_provider.dart';
import 'providers/note_provider.dart';
import 'package:provider/provider.dart';
import 'constants/app_constants.dart';
import 'screens/all_labels_screen.dart';
import 'screens/all_notes_screen.dart';
import 'screens/drawer_screen.dart';
main() {
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
systemNavigationBarColor: ColorsConstant.grayColor,
),
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => NoteProvider()),
ChangeNotifierProvider(create: (_) => LabelProvider()),
],
builder: (context, child) => MaterialApp(
title: 'Note-App',
debugShowCheckedModeBanner: false,
themeMode: ThemeMode.dark,
theme: customThemeData(context),
initialRoute: '/',
routes: {
'/': (context) => const AllNotesScreen(),
DrawerScreen.routeName: (context) => const DrawerScreen(),
AllLabelsScreen.routeName: (context) => const AllLabelsScreen(),
},
),
);
}
}
allnotesscreens.dart:
class AllNotesScreen extends StatefulWidget {
const AllNotesScreen({Key? key}) : super(key: key);
#override
State<AllNotesScreen> createState() => _AllNotesScreenState();
}
class _AllNotesScreenState extends State<AllNotesScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
Container(
height: 200,
width: 100,
color: Colors.yellow,
),
),
);
}
String _viewMode = ViewMode.staggeredGrid.name;
bool _isLoading = false;
final _scaffoldKey = GlobalKey<ScaffoldState>();
#override
void initState() {
super.initState();
setState(() {
_isLoading = true;
});
}
#override
void didChangeDependencies() {
super.didChangeDependencies();
Future _loadViewMode() async {
final prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey('view-mode')) return;
setState(() {
_viewMode = prefs.getString('view-mode') ?? ViewMode.staggeredGrid.name;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: const Text(
"all notes",
style: TextStyleConstants.titleAppBarStyle,
),
actions: [
if (context
.watch<NoteProvider>()
.items
.isNotEmpty)
IconButton(
onPressed: () {
showSearch(
context: context,
delegate: NoteSearch(isNoteByLabel: false),
);
},
icon: const Icon(Icons.search),
),
IconButton(
onPressed: () async {
final result = await changeViewMode(_viewMode);
setState(() {
_viewMode = result;
});
},
icon: _viewMode == ViewMode.staggeredGrid.name
? const Icon(Icons.view_stream)
: const Icon(Icons.grid_view),
),
const SizedBox(
width: 6,
)
],
),
drawer: const DrawerScreen(),
body: _isLoading
? const Center(
child: CircularProgressIndicator(),
)
: RefreshIndicator(
onRefresh: () => refreshOrGetData(context),
child: Consumer<NoteProvider>(
builder: (context, noteProvider, child) =>
noteProvider.items.isNotEmpty
? NoteListViewWidget(
notes: noteProvider.items,
viewMode: _viewMode,
scaffoldContext: _scaffoldKey.currentContext!,
)
: child!,
child: const NoNoteUIWidget(
title: "your notes after adding will appear here",
),
),
),
floatingActionButton: FloatingActionButton(
child: linearGradientIconAdd,
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => const EditNoteScreen(),
));
},
),
);
}
}
}
The first few lines of your _AllNotesScreenState class are why there's a yellow square; that's what you're telling it to build.
class _AllNotesScreenState extends State<AllNotesScreen> {
// this build function here is what is drawing to the screen
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
Container(
height: 200,
width: 100,
color: Colors.yellow,
),
),
);
}
Maybe it's just how you've pasted it in, but it appears as though you have a build function defined within the didChangeDependencies function. If you took it out of there, it would then make it apparent that you have two build functions defined for the class.
I'm assuming it's the second one that you actually want building.
#override
void didChangeDependencies() {
super.didChangeDependencies();
Future _loadViewMode() async {
final prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey('view-mode')) return;
setState(() {
_viewMode = prefs.getString('view-mode') ?? ViewMode.staggeredGrid.name;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
...

Alert dialogue not displaying even with show dialogue

I changed it to stateful and used return dialogue but still nothing.
void main() {
runApp(
MyApp(),
);
}
class MyApp extends StatefulWidget {
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
createAlertDialogue(BuildContext context) {
TextEditingController customeController = TextEditingController();
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text(" Your NAme"),
content: TextField(
controller: customeController,
),
actions: <Widget>[
MaterialButton(
elevation: 5.0,
child: Text('submit'),
onPressed: () {},
)
],
);
});
}
Widget _buildForgotPasswordBtn(BuildContext ctx) {
return Container(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: () {
setState(() {
createAlertDialogue(ctx);
});
},
child: Text(
'forgot password',
style: kLabelStyle,
),
),
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Color.fromARGB(206, 5, 42, 146),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_buildForgotPasswordBtn(context),
],
),
),
),
);
}
}
I used setState and even put ctx in createalertdialogue because it didn't work until I changed from context to this.
I don't get any errors but I get nothing when I press the forgot password button on the emulator.
The button is there and can be pressed with no errors but still nothing appears.
i fixed it nevermind sorry the answer was changing the navigation method to Navigator.pushNamed
I Just slightly edited your code
Wrap your runApp with MaterialApp
from
void main() {
runApp(
MyApp(),
);
}
to
void main() {
runApp(
MaterialApp(
home: MyApp(),
),
);
}
your full code
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: MyApp(),
),
);
}
class MyApp extends StatefulWidget {
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
createAlertDialogue(BuildContext context) {
TextEditingController customeController = TextEditingController();
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text(" Your NAme"),
content: TextField(
controller: customeController,
),
actions: <Widget>[
MaterialButton(
elevation: 5.0,
child: Text('submit'),
onPressed: () {},
)
],
);
});
}
Widget _buildForgotPasswordBtn(BuildContext ctx) {
return Container(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: () {
setState(() {
createAlertDialogue(ctx);
});
},
child: Text(
'forgot password',
),
),
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Color.fromARGB(206, 5, 42, 146),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_buildForgotPasswordBtn(context),
],
),
),
),
);
}
}

How do I activate button if at least one checkbox is selected? - Flutter

I have an alert dialog that displays a series of check boxes.
I am trying to ensure that if at least one of the checkboxes is selected, the confirm button is enabled, otherwise, if no checkbox is selected, it appears as inactive.
I have a parent and a child widget, both statefull. In one of them I have the button that should be enabled / disabled, and in the other one I have the content of the alert dialog.
The challenge for me has been to notify the parent widget from the child widget, that the flag variable with which I determine whether the button should be active or not, has been updated.
I have tried sending a function to the child widget that it executes, also with ValueSetter and ValueChanged, but so far without success.
If after activating or inactivating one of the checkboxes, I do a hot reload, the button is also updated. So I think it may be something with setState that I am not taking into account.
This is what I have done so far, ready to copy and paste into dartPad.
Thanks for your help.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: FrequencySelectionPage(),
),
),
);
}
}
class FrequencySelectionPage extends StatefulWidget {
FrequencySelectionPage();
#override
_FrequencySelectionPageState createState() => _FrequencySelectionPageState();
}
class _FrequencySelectionPageState extends State<FrequencySelectionPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: ListTile(
leading: Icon(Icons.calendar_today),
title: Text('Some days of the week'),
trailing: Icon(Icons.keyboard_arrow_right_rounded),
onTap: () {
_showDialog(context);
}
),),
);
}
void _showDialog(BuildContext context) {
final double screenSize = MediaQuery.of(context).size.height;
bool? canConfirm;
void setCanConfirm(bool value) {
setState(() {
canConfirm = value;
});
}
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Choose days"),
content: Container(
width: 200,
height: screenSize * 0.60,
child: ShowAlertContent(
setCanConfirm: setCanConfirm),
),
actions: <Widget>[
SizedBox(
width: screenSize * 0.50,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Cancel'),
),
SizedBox(
height: 20.0,
width: 20.0,
),
ElevatedButton(
child: Text('Confirm'),
onPressed: (canConfirm == false)
? null
: () {
Navigator.of(context).pop();
},
),
],
),
)
],
);
},
);
}
}
class ShowAlertContent extends StatelessWidget {
final ValueSetter<bool> setCanConfirm;
const ShowAlertContent(
{required this.setCanConfirm});
#override
Widget build(BuildContext context) {
return ShowSomeWeekDaysOptionContent(setCanConfirm: setCanConfirm);
}
}
class ShowSomeWeekDaysOptionContent extends StatefulWidget {
final ValueChanged<bool> setCanConfirm;
const ShowSomeWeekDaysOptionContent({required this.setCanConfirm});
#override
_ShowSomeWeekDaysOptionContentState createState() =>
_ShowSomeWeekDaysOptionContentState();
}
class _ShowSomeWeekDaysOptionContentState
extends State<ShowSomeWeekDaysOptionContent> {
Map<String, bool> days = {
'Day1': false,
'Day2': false,
'Day3': false,
'Day4': false,
'Day5': false,
'Day6': false,
'Day7': false
};
#override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: ListView(
padding: EdgeInsets.all(8.0),
children: days.keys.map(
(day) {
return StatefulBuilder(builder:
(BuildContext context, StateSetter setCheckboxState) {
return CheckboxListTile(
title: Text(day),
value: days[day],
onChanged: (bool? value) {
setState(() {});
setCheckboxState(() {
days[day] = value!;
if (days.containsValue(true)) {
widget.setCanConfirm(true);
} else {
widget.setCanConfirm(false);
}
});
},
);
});
},
).toList(),
),
),
],
);
}
}
In your example you need something which rebuilds the button, when the value of canConfirm changes. You could use a ValueListenableBuilder. Therefore you have to make canConfirm a ValueNotifier.
Here is the working example:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: FrequencySelectionPage(),
),
),
);
}
}
class FrequencySelectionPage extends StatefulWidget {
FrequencySelectionPage();
#override
_FrequencySelectionPageState createState() => _FrequencySelectionPageState();
}
class _FrequencySelectionPageState extends State<FrequencySelectionPage> {
late ValueNotifier<bool> canConfirm;
#override
void initState() {
canConfirm = ValueNotifier(false);
super.initState();
}
void setCanConfirm(bool value) {
canConfirm.value = value;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: ListTile(
leading: Icon(Icons.calendar_today),
title: Text('Some days of the week'),
trailing: Icon(Icons.keyboard_arrow_right_rounded),
onTap: () {
_showDialog(context);
}),
),
);
}
void _showDialog(BuildContext context) {
final double screenSize = MediaQuery.of(context).size.height;
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Choose days"),
content: Container(
width: 200,
height: screenSize * 0.60,
child: ShowAlertContent(setCanConfirm: setCanConfirm),
),
actions: <Widget>[
SizedBox(
width: screenSize * 0.50,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Cancel'),
),
SizedBox(
height: 20.0,
width: 20.0,
),
ValueListenableBuilder<bool>(
valueListenable: canConfirm,
builder: (context, value, child) {
return ElevatedButton(
child: Text('Confirm'),
onPressed: (value == false)
? null
: () {
Navigator.of(context).pop();
},
);
},
),
],
),
)
],
);
},
);
}
}
class ShowAlertContent extends StatelessWidget {
final ValueSetter<bool> setCanConfirm;
const ShowAlertContent({required this.setCanConfirm});
#override
Widget build(BuildContext context) {
return ShowSomeWeekDaysOptionContent(setCanConfirm: setCanConfirm);
}
}
class ShowSomeWeekDaysOptionContent extends StatefulWidget {
final ValueChanged<bool> setCanConfirm;
const ShowSomeWeekDaysOptionContent({required this.setCanConfirm});
#override
_ShowSomeWeekDaysOptionContentState createState() =>
_ShowSomeWeekDaysOptionContentState();
}
class _ShowSomeWeekDaysOptionContentState
extends State<ShowSomeWeekDaysOptionContent> {
Map<String, bool> days = {
'Day1': false,
'Day2': false,
'Day3': false,
'Day4': false,
'Day5': false,
'Day6': false,
'Day7': false
};
#override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: ListView(
padding: EdgeInsets.all(8.0),
children: days.keys.map(
(day) {
return StatefulBuilder(builder:
(BuildContext context, StateSetter setCheckboxState) {
return CheckboxListTile(
title: Text(day),
value: days[day],
onChanged: (bool? value) {
setCheckboxState(() {
days[day] = value!;
if (days.containsValue(true)) {
widget.setCanConfirm(true);
} else {
widget.setCanConfirm(false);
}
});
},
);
});
},
).toList(),
),
),
],
);
}
}
I don’t know about your case but ummmm.. I think this one maybe a lot easier
`bool _isChecked = false;
#override
Widget build(BuildContext context) {
return Column(
children: [
Checkbox(
value: _isChecked,
onChanged: (value) {
setState(() {
_isChecked = value;
});
},
),
ElevatedButton(
child: Text('Button'),
onPressed: (){
if(_isChecked){
print('CHeckbox is checked');
}else{
print('CHeckbox is not checked');
}
},
),
],
);
}`

Could not find the correct Provider . The provider you are trying to read is in a different route

I have following route in my app:
Main.dart ---> SplashScreen.dart ---> DetailsPage.dart
Main.dart
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => FontSizeHandler()),
],
child: MyApp(),
),
);
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: SplashScreen(),
);
}
}
From SplashScreen.dart I move to DetailsPage.dart using Navigator.pushAndRemoveUntil i.e
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) => DetailsPage()), (route) => false);
Now in Details page on App Bar there is icon and on press of which I want to change the font using FontSizeHandler
DetailsPage.dart
class DetailsPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(
icon: Icon(Icons.arrow_upward),
onPressed: () {
context.read<FontSizeHandler>().increaseFont();
},
),
IconButton(
onPressed: () {
context.read<FontSizeHandler>().decreaseFont();
},
icon: Icon(Icons.arrow_downward),
),
],
title: Text(
"DetailsPage",
style: GoogleFonts.roboto(),
),
),
body: SafeArea(
child: SingleChildScrollView(
child: Card(
child: Container(
padding: EdgeInsets.fromLTRB(5, 5, 5, 15),
child: AutoSizeText(
"MyTexts",
textAlign: TextAlign.justify,
style: GoogleFonts.openSans(
fontSize:
context.watch<FontSizeHandler>().fontSize.toDouble(),
),
),
),
),
),
),
);
}
}
So the problem here is I am getting this error message
Could not find the correct Provider This likely
happens because you used a BuildContext that does not include the
provider
Is this error is due to I used Navigator.pushAndRemoveUntil?
Though I have ChangeNotifierProvider at top of hierarchy why is it throwing error?
How to solve this?
FontSizeHandler.dart
class FontSizeHandler with ChangeNotifier {
int fontSize = 15;
void increaseFont() {
fontSize = fontSize + 2;
notifyListeners();
}
void decreaseFont() {
fontSize = fontSize - 2;
notifyListeners();
}
}
Solved: The Problem Was With Importing Wrong ChangeNotifier class. Never Trust autoimport again
Updated Answer
For reference, the issue was caused by an erroneous import as below:
import 'file:///.../fontchangehandler.dart'; // import 'package:.../fontchangehandler.dart';
Original Answer
Unfortunately I was unable to reproduce the error that you are experiencing using the provided code. If you could provide the rest of the code from the DetailsPage class then that might help to further diagnose the error. I was able to get the example below working which hopefully you might find useful:
import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider<FontSizeHandler>(
create: (context) {
return FontSizeHandler();
},
),
],
child: MyApp(),
),
);
}
class FontSizeHandler extends ChangeNotifier {
int _fontSize = 15;
int get fontSize => _fontSize;
void increaseFont() {
_fontSize = _fontSize + 2;
notifyListeners();
}
void decreaseFont() {
_fontSize = _fontSize - 2;
notifyListeners();
}
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: SplashScreen(),
);
}
}
class SplashScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
onPressed: () async {
await Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) {
return DetailsPage();
},
),
(route) => false,
);
},
child: Text('GO TO DETAILS'),
),
),
);
}
}
class DetailsPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(
icon: Icon(Icons.arrow_upward),
onPressed: () {
context.read<FontSizeHandler>().increaseFont();
},
),
IconButton(
onPressed: () {
context.read<FontSizeHandler>().decreaseFont();
},
icon: Icon(Icons.arrow_downward),
),
],
title: Text(
"DetailsPage",
style: GoogleFonts.roboto(),
),
),
body: SafeArea(
child: SingleChildScrollView(
child: Card(
child: Container(
padding: EdgeInsets.fromLTRB(5, 5, 5, 15),
child: AutoSizeText(
"MyTexts",
textAlign: TextAlign.justify,
style: GoogleFonts.openSans(
fontSize: context.watch<FontSizeHandler>().fontSize.toDouble(),
),
),
),
),
),
),
);
}
}

flutter: Another exception was thrown: No MaterialLocalizations found

I am trying to show an Alert Dialog on press of a button in Flutter.
Following is my code
main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return MyAppState();
}
}
class MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "Different Widgets",
debugShowCheckedModeBanner: false,
home: showAlertDialog()
);
}
void _dialogResult(String value) {
if (value == "YES") {
print("YES");
} else {
print("NO");
}
Navigator.pop(context);
}
Widget showAlertDialog() {
TextEditingController textEditingController = TextEditingController();
return Scaffold(
appBar: AppBar(
title: Text("Different Widgets"),
),
body: Container(
child: Center(
child: Column(
children: <Widget>[
TextField(
controller: textEditingController,
),
RaisedButton(
onPressed: () {
print("Hi");
AlertDialog dialog = AlertDialog(
title: Text("Hi"),
content: Text(
textEditingController.text,
style: TextStyle(fontSize: 30.0),
),
actions: <Widget>[
FlatButton(
onPressed: () {
_dialogResult("YES");
},
child: Text("YES")),
FlatButton(
onPressed: () {
_dialogResult("NO");
},
child: Text("NO")),
],
);
showDialog(context: context, builder: (BuildContext context) => dialog);
},
child: Text("Click Me"),
)
],
),
),
),
);
}
What does this has to do with Localisation, I cannot follow. I did the same steps as per the docs. I am able to see the button but on click of that button I keep getting error. I tried writing print statement inside of button click and the print statement appears in the log, definitely something wrong with AlertDialog.
You may get No MaterialLocalizations found error while showing dialog using showDialog() class in Flutter. The issue is putting child widget on home property of MaterialApp() widget without creating new widget class.
One way to solve is putting MaterialApp() inside runApp() and create new class for home property.
import 'package:flutter/material.dart';
main() {
runApp(
MaterialApp(
home: MyApp(),
title: "Different Widgets",
debugShowCheckedModeBanner: false,
),
);
}
/*
place MaterialApp() widget on runApp() and create
new class for its 'home' property
to escape 'No MaterialLocalizations found' error
*/
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return MyAppState();
}
}
class MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return showAlertDialog();
}
void _dialogResult(String value) {
if (value == "YES") {
print("YES");
} else {
print("NO");
}
Navigator.pop(context);
}
Widget showAlertDialog() {
TextEditingController textEditingController = TextEditingController();
return Scaffold(
appBar: AppBar(
title: Text("Different Widgets"),
),
body: Container(
child: Center(
child: Column(
children: <Widget>[
TextField(
controller: textEditingController,
),
RaisedButton(
onPressed: () {
print("Hi");
AlertDialog dialog = AlertDialog(
title: Text("Hi"),
content: Text(
textEditingController.text,
style: TextStyle(fontSize: 30.0),
),
actions: <Widget>[
FlatButton(
onPressed: () {
_dialogResult("YES");
},
child: Text("YES")),
FlatButton(
onPressed: () {
_dialogResult("NO");
},
child: Text("NO")),
],
);
showDialog(
context: context,
builder: (BuildContext context) => dialog);
},
child: Text("Click Me"),
)
],
),
),
),
);
}
}