getting future string and saving state in flutter


I am trying to get the string value of a future, and saving state in flutter. user chooses the endTime and it should display on the UI untill it ends. however, I am getting the following error:

type 'String' is not a subtype of type 'Future<String>' in type cast

the method:

final Future<SharedPreferences> _prefs = 
Future<String> _textLine = '' as Future<String>;

Future<String> fastTrue() async {
final SharedPreferences prefs = await _prefs;
String formattedDate = DateFormat('yyyy-MM-dd, 
final textLine = (prefs.getString('formattedDate') ?? 
 Languages.of(context)!.setYourFastTime) as Future<String>;

setState(() {
  _textLine = prefs.setString('formattedDate',
 +'\n$formattedDate').then((bool success) {
    return textLine;
return textLine;

in initState():

  void initState() {
  _textLine = _prefs.then((SharedPreferences prefs) {
  return prefs.getString('formattedDate') ?? 
  Languages.of(context)!.setEndTime +'\n'+DateFormat('yyyy-MM-dd, 

then in my widget build():

  Padding(padding: const EdgeInsets.only(top: 170),
                child: FutureBuilder<String>(
                    future: _textLine,
                    builder: (BuildContext context, 
   AsyncSnapshot<String> snapshot) {
                      switch (snapshot.connectionState) {
                        case ConnectionState.waiting:
                          return const CircularProgressIndicator();
                          if (snapshot.hasError) {
                            return Text('Error: ${snapshot.error}');
                          } else {
                            return Text(
                              Languages.of(context)!.endTimeIs + 

help me, pls, tried using hive, but was not able to get to save the state of the widget. Thanks!


This code throws the error because you try to cast a String to a Future<String>>, although it is a String.

Future<String> _textLine = '' as Future<String>;

If you want to declare a Future with a value, you can use the value method.

Future<String> _textLine = Future.value('');

Answered By – quoci

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *