In my Flutter app I want to re-use a custom dialog that received user input. All works fine if I do the showDialog() from within the class and have the custom AlertDialog in another class. However, that forces me to re-type the button's onpressed and showdialog sections every single time. I'd prefer to have that also in another reusable class and pass user input to it (and get the button with all functionalities in return). The problem with this is that the user input is not present when the page is loaded, so I need to know the updated state when the button is pressed. And there I get stuck... guessing it should be something with passing the widget's state, but getting lost here.
I created a minimal app to recreate the problem, here is the code:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
var myTextFieldController = TextEditingController();
return Scaffold(
appBar: AppBar(title: const Text('Dialog test')),
body: ListView(
padding: const EdgeInsets.all(20),
children: [
TextField(controller: myTextFieldController),
TestButton().getButton(context, myTextFieldController.text),
],
),
);
}
}
class TestButton {
Widget getButton(BuildContext context, myText) {
return ElevatedButton(
child: const Text('Show Dialog'),
onPressed: () {
showDialog(
context: context,
builder: (builder) {
return AlertDialog(
title: Text(myText), // is always empty
);
});
},
);
}
}
The AlertDialog's text remains empty , despite text in the TextField. How can I get this to work? Thx!