I pass data from textcontroller via getter to text widget and I don't understand why text on widget pronounce doesn't appear. It seems to me that there is some logic in my code, but I'm new to flutter and maybe I don't understand something, tell me. code compiles
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: MyCustomForm(),
),
);
}
class MyCustomForm extends StatefulWidget {
MyCustomForm({super.key});
String s = '';
String get ninja {
return s;
}
@override
State<MyCustomForm> createState() => _MyCustomFormState();
}
class _MyCustomFormState extends State<MyCustomForm> {
final myController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Pronounce(),
TextField(
controller: myController,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState (() {widget.s = myController.text;}),
child: const Icon(Icons.update),
),
);
}
}
class Pronounce extends StatefulWidget {
Pronounce ({super.key});
@override
State<Pronounce> createState() => _PronounceSt();
}
class _PronounceSt extends State<Pronounce> {
@override
Widget build (context) {
return Text (MyCustomForm().ninja);
}
}
Problem is your getter is in MyCustomForm
technically it not shared properly
You should pass data by create constructor
and pass it to another widget or page like this and I will add some constrcutor tips
class Pronounce extends StatefulWidget {
// Define Variable
final String text;
// then create constructor
// ps. if your variable is nullable or has default value you can remove required
Pronounce ({
super.key ,
required this.text,
// ex. when you have default value
// this.text = 'default text',
// ex. nullable case
// this.text,
});
@override
State<Pronounce> createState() => _PronounceSt();
}
class _PronounceSt extends State<Pronounce> {
@override
Widget build (context) {
return Text (text);
// Nullable case you can do like this ?? after nullable variable mean when value is null use this ...
// return Text (text ?? 'Text is empty');
}
}