How to: Convert Future String to String and vice versa in Dart| Flutter

This tutorial shows, how to Convert Future<String> to String in Dart and Flutter programming.

Asynchronous programming is supported through the async and await keywords in Dart and Flutter.

When retrieving data from the backend, data loads asynchronously before displaying it in the front end. The Future class uses for asynchronous operations in the Dart application.

It stores the various types of values returned by async operations. Its value is always a future value that awaits the completion of the function. The status of future value is both incomplete and completed.

  • Completed results in either success or error.
  • incomplete is an uncompleted future and waits for execution to finish.

Future<String> denotes that the Async API returns a future String value.

The string is a type used to store a group of characters. We have to convert from one type to another manually.

How do you convert Future String to Str in flutter?

The dart:async package provides classes for async and await operations.

In the below example Created async function and converted a Future String using Future.value(). In real-time, this gets the data from the database. The Async function always returns Future Values.

Future.value(), takes the input String value of dynamic type and returns Future<String> values.

Syntax:

 Future<dynamic> Future.value([FutureOr<dynamic>? value])

Call the future String using await function that returns String.

Here is a code:

import 'dart:async';

void main() async {
  Future<String> stringFuture = _getMockData();
  String message = await stringFuture;
  print(message); // will print one on console.
}

Future<String> _getMockData() async{
  return Future.value("one");
}

The above example

  • Since _getMockData is marked as an async method, It returns Future<String>, and tells String value in the future, this method does not wait for execution but executes in asynchronous execution.
  • awaits of this method returns a value. awaits keyword waits for a response returned from a method

How do you convert String to Future of String in flutter?

This example parses Future<String> into String values.

The string variable is created and assigned with the string literal. Next, the Future class has a Future.value() method that creates a future value. Here is an example

import 'dart:async';

void main() async {
  String message = "Two";
  var futureValues = Future.value(message);
  print(futureValues); //Instance of '_Future<String>'
  print(futureValues.runtimeType); //_Future<String>
}

Conclusion

To summarize, We can easily convert String to Future<String> and Future<String> to String with examples.