I'm starting on Flutter. Today, I learned how to coding a showDialog, but it doesn't work. i have tried to write it again and again but nothing affects... here's my code:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: Scaffold(appBar: AppBar(), body: MyHome())));
}
class MyHome extends StatefulWidget {
const MyHome({Key? key}) : super(key: key);
#override
State<MyHome> createState() => _MyHomeState();
}
class _MyHomeState extends State<MyHome> {
#override
void MyDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("title"),
content: Text("Thanks to clock"),
actions: <Widget>[
TextButton(
onPressed: () {},
child: Text("close"),
)
],
);
});
}
Widget build(BuildContext context) {
return TextButton(
onPressed: () {},
child: Text("Click On me!"),
);
}
}
Please help me! Thanks...
You did not call MyDialog anywhere in the code.
updated code:
import 'package:flutter/material.dart';
class SignUpScreen extends StatefulWidget {
const SignUpScreen({Key? key}) : super(key: key);
#override
State<SignUpScreen> createState() => _SignUpScreenState();
}
class _SignUpScreenState extends State<SignUpScreen> {
#override
void MyDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("title"),
content: Text("Thanks to clock"),
actions: <Widget>[
TextButton(
onPressed: () {},
child: Text("close"),
)
],
);
});
}
Widget build(BuildContext context) {
return TextButton(
onPressed: () {
MyDialog();
},
child: Text("Click On me!"),
);
}
}
The problem is that you are do not invoke dialog-function by you button. Rename dialog-function accordingly to the code-convention, for example 'showMyDialog' and then invoke it:
return TextButton(
onPressed: () => showMyDialog(),
child: Text("Click On me!"),
);
Related
I'm having this issue while creating a splash screen in flutter. I looked for an answer but no one solve the matter or answer perfectly.
Cannot resolve symbol '#android:color/black'
Create StateFulWidget
Add one Future.delayed() to initstate.
#override
void initState() {
super.initState();
Future.delayed(const Duration(seconds: 3), () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const SecondScreen(),
),
);
});
}
Duration(seconds:3) will wait for 3 seconds on the splash screen then it will redirect to SecondScreen.
the code should be like this
class SplashScreen extends StatefulWidget {
const SplashScreen({super.key});
#override
State<SplashScreen> createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
#override
void initState() {
super.initState();
Future.delayed(const Duration(seconds: 3), () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const SecondScreen(),
),
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Colors.blue,
child: const Center(child: Text("Splash Screen")),
),
);
}
}
the whole code
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const SplashScreen(),
);
}
}
class SplashScreen extends StatefulWidget {
const SplashScreen({super.key});
#override
State<SplashScreen> createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
#override
void initState() {
super.initState();
Future.delayed(const Duration(seconds: 3), () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const SecondScreen(),
),
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Colors.blue,
child: const Center(child: Text("Splash Screen")),
),
);
}
}
class SecondScreen extends StatefulWidget {
const SecondScreen({super.key});
#override
State<SecondScreen> createState() => _SecondScreenState();
}
class _SecondScreenState extends State<SecondScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Colors.green,
child: const Center(
child: Text("Home Screen"),
),
),
);
}
}
If it was useful, you can choose it as an approved answer and give points. Good coding.
Try using this,
<item android:background="#android:color/white" />
When it comes to drawable you should assign XMLs or images in your drawable or mipmap resource
Lets say i have a button. So..
String buttonTitle = "Upload";
Above is the button title.
Now i have set this in my text of the button. When i upload something, i want this text to be Uploaded so i use setState method for that and hence the title of the button will be updated. But let's suppose i have 100s of buttons which just says Upload and later have to be changed to just Uploaded if something has been uploaded using that button, am i going to create 100 Strings here? This approach doesn't seem good enough to me. Is there a better approach for this in flutter ?
Check this widget as you expect . click on main button it will update all button state after 3 second like uploading
class MyHomePages2 extends StatefulWidget {
MyHomePages2({Key? key}) : super(key: key);
var Upload = "Upload";
#override
State<MyHomePages2> createState() => _MyHomePages2State();
}
class _MyHomePages2State extends State<MyHomePages2> {
#override
Widget build(BuildContext context) {
return ListView(
children: [
ElevatedButton(
onPressed: () {
setState(() {
widget.Upload = "upload";
});
Future.delayed(Duration(seconds: 3), () {
setState(() {
widget.Upload = "uploaded";
});
});
},
child: Text("MainUpload")),
...List.generate(
100,
(index) => Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () {}, child: Text("$index ${widget.Upload}")),
))
],
);
}
}
SampleCode Dartpad live code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
int myvalue = 0;
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
#override
void initState() {
// functions().then((int value) {
// setState(() {
// myvalue = value;
// });
// future is completed you can perform your task
// });
}
Future<int> functions() async {
// do something here
return Future.value();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: MyHomePages2(),
);
}
}
class MyHomePages2 extends StatefulWidget {
MyHomePages2({Key? key}) : super(key: key);
var Upload = "Upload";
#override
State<MyHomePages2> createState() => _MyHomePages2State();
}
class _MyHomePages2State extends State<MyHomePages2> {
#override
Widget build(BuildContext context) {
return ListView(
children: [
ElevatedButton(
onPressed: () {
setState(() {
widget.Upload = "upload";
});
Future.delayed(Duration(seconds: 3), () {
setState(() {
widget.Upload = "uploaded";
});
});
},
child: Text("MainUpload")),
...List.generate(
100,
(index) => Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () {}, child: Text("$index ${widget.Upload}")),
))
],
);
}
}
My setup:
class Start_Page extends StatefulWidget {
#override
StartPageState createState() => StartPageState();
}
class StartPageState extends State<Start_Page> {
#override
Widget build(BuildContext context){
return Scaffold(
body: Container(
child: ElevatedButton(
style: ButtonStyle(),
onPressed: () {
createUserModalBottomSheet(context);
},
child: Text("Start"),
)
)
);
}
}
void createUserModalBottomSheet(context){
showModalBottomSheet(context: context, builder: (BuildContext bc) {
return Container(
child: Switch(value: true, onChanged: (value) => {value = !value}, activeColor:
Colors.grey)
);
}
}
The Problem is that the switch won't change his value. The Modalbottomsheet appears but won't update changes/states.
Does anyone know a solution?
Use StatefulBuilder to update UI inside showModalBottomSheet. Second issue is you need to use a bool variable to hold value.
class StartPageState extends State<Start_Page> {
bool switchValue = false;
///......
void createUserModalBottomSheet(context) {
showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return StatefulBuilder(
builder: (context, setStateSB) => Container(
child: Switch(
value: switchValue,
onChanged: (value) {
setState(() {
// update parent UI
switchValue = value;
});
setStateSB(() {
// update inner dialog
switchValue = value;
});
},
activeColor: Colors.grey),
),
);
});
}
#override
Widget build(BuildContext context) {
.........
I have this event form, it's to create or edit events data. The save button is inside the app bar action, and the form is inside the body. In this project, I have all of the widgets in different files. How do I run the save function inside EventFormForm.dart when I tap the save button inside EventFromAppBar.dart?
This is the structure :
These are my codes :
EventForm.dart
class EventForm extends StatelessWidget {
// Some Code
// Some Const
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: EventFormAppBar(
// Some Params
),
body: EventFormBody(
// Some Params
)
);
}
}
EventFormAppBar.dart
class EventFormAppBar extends PreferredSize{
// Some Code
// Some Const
// Some Code
#override
Widget build(BuildContext context) {
return AppBar(
// Some Code
actions: <Widget>[
IconButton(
icon: Icon(Icons.save),
onPressed: () {
}
)
]
);
}
}
EventFormBody.dart
class EventFormBody extends StatelessWidget {
// Some Code
// Some Const
#override
Widget build(BuildContext context) {
return SafeArea(
child: SingleChildScrollView(
child: EventFormForm(
// Some Params
),
),
);
}
}
EventFormForm.dart
class EventFormForm extends StatefulWidget {
// Some Code
// Some Const
#override
EventFormFormState createState() => EventFormFormState();
}
class EventFormFormState extends State<EventFormForm> {
//
//
// Some Code
//
//
#override
Widget build(BuildContext context) {
return Form(
//
// Some Code
//
);
}
saveForm() {
//
// Some Code
//
}
}
Tag #chunhunghan
You can copy paste run each files below
Step 1: Use final keyForm = GlobalKey<EventFormFormState>();
Step 2: Pass keyForm to EventFormForm(key: keyForm)
Step 3: In IconButton call keyForm.currentState.saveForm();
IconButton(
icon: Icon(Icons.save),
onPressed: () {
keyForm.currentState.saveForm();
})
working demo
full code
main.dart
import 'package:flutter/material.dart';
import 'event_form.dart';
import 'event_form_form.dart';
void main() => runApp(MyApp());
final keyForm = GlobalKey<EventFormFormState>();
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: EventForm(),
);
}
}
event_form.dart
import 'package:flutter/material.dart';
import 'event_form_appbar.dart';
import 'event_form_body.dart';
class EventForm extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(appBar: EventFormAppBar(), body: EventFormBody());
}
}
event_form_appbar.dart
import 'package:flutter/material.dart';
import 'main.dart';
class EventFormAppBar extends PreferredSize {
#override
Widget build(BuildContext context) {
return AppBar(actions: <Widget>[
IconButton(
icon: Icon(Icons.save),
onPressed: () {
keyForm.currentState.saveForm();
})
]);
}
#override
get preferredSize => Size.fromHeight(50);
}
event_form_body.dart
import 'package:flutter/material.dart';
import 'main.dart';
import 'event_form_form.dart';
class EventFormBody extends StatelessWidget {
#override
Widget build(BuildContext context) {
return SafeArea(
child: SingleChildScrollView(
child: EventFormForm(key: keyForm),
),
);
}
}
event_form_form.dart
import 'package:flutter/material.dart';
class EventFormForm extends StatefulWidget {
EventFormForm({Key key}) : super(key: key);
#override
EventFormFormState createState() {
return EventFormFormState();
}
}
class EventFormFormState extends State<EventFormForm> {
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: RaisedButton(
onPressed: () {
saveForm();
},
child: Text('Submit'),
),
),
],
),
);
}
void saveForm() {
print("execute save Form");
if (_formKey.currentState.validate()) {
// If the form is valid, display a Snackbar.
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text('Processing Data')));
}
}
}
I want to implement a call back from a Stateful widget to another Stateful Widget. (child to parent). The hierarchy is Task (contains) -> ItemBought -> addImage
How do i implement this? Also will the callback function be defined in the Stateful widget or in its state?
This is my current code:
Task.dart
import 'package:flutter/material.dart';
import 'package:flutter_convertor/ItemBought.dart';
class task extends StatelessWidget{
#override
...
}
class taskScreen extends StatefulWidget{
#override
taskState createState() => new taskState();
}
class taskState extends State<taskScreen> {
bool isButtonEnabled = false;
//Callback function i want to call in order to change the state of my Button
formReady(){
setState(() {
isButtonEnabled = !isButtonEnabled ;
});
}
#override
Widget build(BuildContext context) {
Column taskScreen = Column(
children: <Widget>[...
ItemBought(), //ITEMBOUGHT WIDGET
...
Column(
children: <Widget>[
FlatButton(
onPressed: isButtonEnabled ? _completePage : null,
child: Text(
...
),
),
],
)]);
return Scaffold(
appBar: AppBar(
title: Text('Task Screen')),
body: taskScreen,
);
} }
ItemBought.dart
import 'package:flutter/material.dart';
import 'package:flutter_convertor/addImage.dart';
class ItemBought extends StatefulWidget{
#override
_ItemBoughtState createState() => _ItemBoughtState();
}
class _ItemBoughtState extends State<ItemBought> {
...
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget> [
...
addImage(),
...
]
)
);
}
}
addImage.dart
import 'package:flutter/material.dart';
import 'package:flutter_convertor/task.dart';
class addImage extends StatefulWidget{
const addImage({this.formReady});
final VoidCallback formReady;
#override
_addImageState createState() => _addImageState();
}
class _addImageState extends State<addImage> {
// const void({taskState.formReady});
// final VoidCallback formReady;
#override
Widget build(BuildContext context) {
return Container(
child: TextField(
onChanged: (text){
formReady(); //ERROR: The method formReady is not defined for the class _addImageState
},
)
);
}
}
How do i call the function formReady from the widget addImage ?
EDIT:
I tried this code, and removed all compile errors however still not getting the desired result:
in addImage.dart
TextField(
onChanged: (text){
addImage().formReady;
}
)
in Itembought.dart
addImage(formReady: (){
ItemBought().formReady;
}
in task.dart
ItemBought(formReady: (){
this.formReady();
}),
class task extends StatelessWidget {
#override
....
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new ItemBought(callback: (data){
String receivedData = data;
},)
],
),
),
);
}
}
class ItemBought extends StatefulWidget {
final void Function(String data) callback;
const ItemBought({Key key, this.callback}) : super(key: key);
#override
_ItemBoughtState createState() => _ItemBoughtState();
}
class _ItemBoughtState extends State<ItemBought> {
#override
Widget build(BuildContext context) {
return Container(
child: new FlatButton(onPressed: (){
widget.callback("Item Id Or name");
}, child: new Text("Bought Item"),),
);
}
}