I am successfully returning a Future to a String but then I cannot seem to find the right wat to assign and use the returned value.
Here I am getting the String name
:
initState() {
name();
super.initState();
}
void name() async {
String? name = await getName();
print(name.toString());
}
From a <Future String>
:
static Future<String?> getName() async {
return "This is my name";
}
Then I need to pass the name
to a Map<String>
:
Map<String, String> NamesAll() {
Map<String, String> result = new Map();
FirstName = name; //I get an error here: Undefined name 'name'.
return result;
}
The problem is that I get an error in Map: Undefined name 'name'
.
How do I fix this?
I am assuming that your code is somehow similar to this:
class _MyHomePageState extends State<MyHomePage> {
String FirstName = '';
@override
initState() {
name();
super.initState();
}
void name() async {
// 1.
String? name = await getName();
print(name.toString());
}
Map<String, String> NamesAll() {
Map<String, String> result = new Map();
FirstName = name;
return result;
}
@override
Widget build(BuildContext context) {
...
}
}
If this is the case, then the name
you defined inside the method name() can not be reached outside that method. For more info refer to Lexical scopes.
If you wanted this to work, a possible solution would be:
class _MyHomePageState extends State<MyHomePage> {
String name = '';
String FirstName = '';
@override
initState() {
name();
super.initState();
}
void name() async {
name = await getName();
print(name.toString());
}
Map<String, String> NamesAll() {
Map<String, String> result = new Map();
FirstName = name;
return result;
}
@override
Widget build(BuildContext context) {
...
}
}
Where name
is now global to the state class, therefore it is a mutable data now and can be reached by any method/member inside the _MyHomePageState
class.
Edit 2:
In case you want to save the data to map:
Map<String, String> result = new Map();
String nameToAwait = await name();
result['keyName'] = nameToAwait;
// you could also do
result['keyName'] = await name();