Newbie’s Simple question. I would like to save the result of a variable created with a callback as a var and output it within the text of another widget. What should I do..?
Row(
children: [
Expanded(
child: Container(
height: 40,
color: primaryColor20,
child: Text(''),
),
),
ElevatedButton(
onPressed: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (_) => KpostalView(
callback: (Kpostal result){
print(result.address);
var resultAddress = result.address;
},
),
),
);
},
child: Text('Find Address'),
),
],
),
4
Answers
use a StatefulWidget, then
setState(() => resultAddress = result.address;
such tax you can useText(resultAddress)
You have to use a StatefulWidget
You can use
Text('My text ${result.address}')
but to refresh the value you’ll need it to be inside of a StatefulWidgetyou have 2 choices.
setState(() => resultAddress = result.address;
this makes
resultAddress
changeable by usingsetState
.Provider
. create a class like this:as you see changing
_resultAddress
bynotifyListeners()
tells you and you can show it.you can use
_resultAddress
byConsumer
like this in your codes:be careful to import Provider package to your pubspec.yaml and provide your provider class in your main like this:
the best benefit of provider as state management is that you can use your variables where ever you want.
Happy Coding…