How to access passed value in the Statefulwidget? - flutter

I am passing an String from another StatefulWidget to the below CardItem StatefulWidget and then from here the String is passed to the _CardItemState as shown in the code below.
But how this String passed should be accessed from _CardItemState(String itemTitle);
class CardItem extends StatefulWidget {
String itemTitle;
CardItem({#required this.itemTitle});
#override
_CardItemState createState() => _CardItemState(itemTitle);
}
class _CardItemState extends State<CardItem> {
_CardItemState(String itemTitle);
void initState(){
print("INiatialize");
print("itemTitle is " + );
}
}

You can access it via widget.itemTitle. For your case you can call it like this:
printItem(){
print("itemTitle is ${widget.itemTitle}");
}
void initState(){
printItem();
super.initState();
}
You also don't need to pass the string in your state constructor. Remove this:
_CardItemState(String itemTitle);

easy! grab it using
widget.itemTitle
class CardItem extends StatefulWidget {
String itemTitle;
CardItem({#required this.itemTitle});
#override
_CardItemState createState() => _CardItemState(itemTitle);
}
class _CardItemState extends State<CardItem> {
String itemTitle; // - 1
_CardItemState(this.itemTitle); // - 2
void initState(){
itemTitle = widget.itemTitle; // - 3;
print("INiatialize");
print("itemTitle is " + itemTitle ); // - 4
print("itemTitle is " + widget.itemTitle ); // same as - 4
}
}

Best way to do this is to use
widget.fieldName
class CardItem extends StatefulWidget {
String itemTitle;
CardItem({#required this.itemTitle});
#override
_CardItemState createState() => _CardItemState(itemTitle:itemTitle);
}
class _CardItemState extends State<CardItem> {
String myItemTitle;
#override
void initState(){
super.initState();
myItemTitle=widget.itemTitle;
print("INiatialize");
print("itemTitle is $myItemTitle";
}
}
otherway round to this problem is to pass data in constructor as shown below, but the above method is recommended to be followed.
class CardItem extends StatefulWidget {
String itemTitle;
CardItem({#required this.itemTitle});
#override
_CardItemState createState() => _CardItemState(itemTitle:itemTitle);
}
class _CardItemState extends State<CardItem> {
String itemTitle;
_CardItemState({this.itemTitle});
void initState(){
print("INiatialize");
print("itemTitle is $itemTitle";
}
}

Related

owner._debugCurrentBuildTarget == this is not true

There is no problem with the codes but when I run
I get error owner._debugCurrentBuildTarget == this is not true how can i solve this problem
class HomePage extends StatelessWidget{
#override
HomePageState createState() => HomePageState();
#override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class HomePageState extends State{
late int first, second;
late String islem;
late String result, sonuc;
I think you are missing the StatefulWidget format, try
class HomePage extends StatefulWidget {
const HomePage({super.key});
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late int first, second;
late String islem;
late String result, sonuc;
#override
void initState() {
super.initState();
first = 1;
second = 2;
islem = "islem";
result = "A";
sonuc = "sonuc";
}
#override
Widget build(BuildContext context) {
return Container();
}
}

How to use stateful widget parameters in state class at construction without adding the widget to the tree?

I stumped into a problem where I need to use a StatefulWidget parameter in its state class when it's constructed, but I couldn't find a way to do it since using widget.[whatever variable name] in the state's class constructor returns an unexpected null value, and the initState function only runs when the widget is being drawn to the screen.
For example:
import 'package:flutter/material.dart';
class Test extends StatefulWidget {
final String text;
Test(this.text);
final state = _TestState();
#override
_TestState createState() => state;
}
class _TestState extends State<Test> {
String? changingText;
void updateChangingText(String moreText){
changingText = changingText! + moreText;
}
#override
void initState() {
super.initState();
changingText = widget.text;
}
#override
Widget build(BuildContext context) {
return Text(changingText!);
}
}
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
var w = Test('test');
w.state.updateChangingText(' text');
return MaterialApp(home: Scaffold(body:
Test('test text')
));
}
}
void main() {
runApp(App());
}
This doesn't work since changingText is being updated before initState gives it its initial value since it only runs when Text is being drawn to the screen and this:
import 'package:flutter/material.dart';
class Test extends StatefulWidget {
final String text;
Test(this.text);
final state = _TestState();
#override
_TestState createState() => state;
}
class _TestState extends State<Test> {
String? changingText;
void updateChangingText(String moreText){
changingText = changingText! + moreText;
}
_TestState(){
changingText = widget.text;
}
#override
Widget build(BuildContext context) {
return Text(changingText!);
}
}
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
var w = Test('test');
w.state.updateChangingText(' text');
return MaterialApp(home: Scaffold(body:
Test('test text')
));
}
}
void main() {
runApp(App());
}
doesn't work either since you can't use widget.[whatever] in state class constructors (for some reason).
So what can I do to use widget parameters in the state class before the widget is drawn to the screen?
Thanks in advance for the help
You should use the initState method present in the State for this instead of the constructor
#override
void initState() {
changingText = widget.text;
super.initState();
}

The instance member 'widget' can't be accessed in an initializer

In my project, I pass data from one widget to another using this code:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
TranslatorSignUpStep2(transModel: this._translatorModel),
),
);
Then I retrive it in the other widget by the code below:
class TranslatorSignUpStep2 extends StatefulWidget {
final TranslatorModel transModel;
TranslatorSignUpStep2({this.transModel});
#override
_TranslatorSignUpStep2State createState() => _TranslatorSignUpStep2State();
}
The problem is, in the TranslatorSignUpStep2 class I want to assign the passed-in transModel to another variable so I write this code
class _TranslatorSignUpStep2State extends State<TranslatorSignUpStep2> {
TranslatorModel _translatorModel = widget.transModel;
}
But it seems like the widget can't be used outside the build method so I get error saying
The instance member 'widget' can't be accessed in an initializer.. Anyone know how to get over this ?
you can access widget in initState function like this.
class _TranslatorSignUpStep2State extends State<TranslatorSignUpStep2> {
TranslatorModel _translatorModel ;
#override
void initState() {
_translatorModel = widget.transModel;
}
}
Just add the keyword late while initializing:
class TranslatorSignUpStep2 extends StatefulWidget {
final TranslatorModel transModel;
TranslatorSignUpStep2({this.transModel});
#override
_TranslatorSignUpStep2State createState() => _TranslatorSignUpStep2State();
}
class _TranslatorSignUpStep2State extends State<TranslatorSignUpStep2> {
late TranslatorModel _translatorModel = widget.transModel;
}
try this code :
TranslatorSignUpStep2 :
class TranslatorSignUpStep2 extends StatefulWidget {
final TranslatorModel transModel;
TranslatorSignUpStep2({this.transModel});
#override
_TranslatorSignUpStep2State createState() => _TranslatorSignUpStep2State(this.transModel);
}
TranslatorSignUpStep2 class :
class _TranslatorSignUpStep2State extends State<TranslatorSignUpStep2> {
_TranslatorSignUpStep2State(TranslatorModel _tempModel ){
this._translatorModel =_tempModel;
};
TranslatorModel _translatorModel ;
}
Add static keyword when innitializing
class OrderDetails extends StatefulWidget {
int selectedDays;
OrderDetails({
this.range,)};
#override
_OrderDetailsState createState() => _OrderDetailsState();
}
class _OrderDetailsState extends State<OrderDetails> {
String getRange;
#override
void initState() {
super.initState();
getRange = widget.range;
}

How to edit a final class field in a method?

I want to edit my fields in a method like that :
class Test extends StatefulWidget{
Test({this.firstField, this.secondField});
final String firstField ;
final String secondField ;
#override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
#override
Widget build(BuildContext context) {
return null;
}
editField( field, newValue){
//edit any field of the class in a single function here
}
}
If I use widget.firstField as first parameter of my method I will be able to edit it locally ( in the method ) but not the field.

How to call a function in a StatefulWidget from another StatefulWidget?

I am trying to call a function(addGeoPoint) from Map class in another function named onDragEnd of the class SwipeButton both of which is are stateful.
class Map extends StatefulWidget {
//Some Code
_MapState createState() => _MapState();
}
class _MapState extends State<Map> {
//Some Functions
void addGeoPoint() async{
}
File 2
class SwipeButton extends StatefulWidget {
// Some Code
#override
SwipeButtonState createState() => SwipeButtonState();
}
class SwipeButtonState extends State<SwipeButton>
with SingleTickerProviderStateMixin {
// Some functions
void _onDragEnd(DragEndDetails details) {
// I want to call the addGeoPoint() function here
}
}
To do so, I tried creating an instance of the class Map as Map mapScreen = new Map and then access the function using mapScreen.addGeoPoint() but, I achieved no success. Any help to solve this problem would be appreciated.
You can use VoidCallBacks to communicate between Widgets:
Map:
class Map extends StatefulWidget {
//Some Code
_MapState createState() => _MapState();
}
class _MapState extends State<Map> {
//Some Functions
void addGeoPoint() async{
//do things
}
Widget buildSwipeButton() {
...
...
return SwipeButton(
onAddGeoPoint: addGeoPoint,
);
}
SwipeButton:
class SwipeButton extends StatefulWidget {
final VoidCallback onAddGeopoint;
SwipeButton({this.onAddGeoPoint});
// Some Code
#override
SwipeButtonState createState() => SwipeButtonState();
}
class SwipeButtonState extends State<SwipeButton>
with SingleTickerProviderStateMixin {
// Some functions
void _onDragEnd(DragEndDetails details) {
// I want to call the addGeoPoint() function here
widget.onAddGeoPoint();
}
}
You can declare your widget like this
class YourWidget extends StatefulWidget {
final Function callback;
YourWidget({#required this.textButton});
#override
YourWidgetState createState() => YourWidgetState();
}
then you can pass de function like this in your stateful parent
YourWidget(
callback: (){}
)
ant then you can use in YourWidget like this in other widget or other function
widget.callback()