getting future string and saving state in flutter

Issue

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 = 
SharedPreferences.getInstance();
Future<String> _textLine = '' as Future<String>;

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

setState(() {
  _textLine = prefs.setString('formattedDate',
      Languages.of(context)!.endTimeIs
 +'\n$formattedDate').then((bool success) {
    return textLine;
  });
});
return textLine;
 }

in initState():

 @override
  void initState() {
  super.initState();
  
  _textLine = _prefs.then((SharedPreferences prefs) {
  return prefs.getString('formattedDate') ?? 
  Languages.of(context)!.setEndTime +'\n'+DateFormat('yyyy-MM-dd, 
 hh:mma').format(DateTime.now());
});

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();
                        default:
                          if (snapshot.hasError) {
                            return Text('Error: ${snapshot.error}');
                          } else {
                            return Text(
                              Languages.of(context)!.endTimeIs + 
      "\n${snapshot.data}"
                            );
                          }
                      }
                    })),

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

Solution

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.