Search code examples
flutterdartsharedpreferences

Future<dynamic> is not subtype of type String? flutter Err


I have an err in my app. I can't read data from shared perfrences in flutter

my code

TextFormField(
              enabled: false,
             initialValue:  Data.getData(key: 'phone_number'),
                    maxLength: 14,
                    keyboardType: TextInputType.phone,
                    textDirection: TextDirection.ltr,
                    decoration: InputDecoration(
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.deepPurple),
                      ),
                      suffixIcon: Icon(
                        Icons.phone_android_sharp,
                        color: Colors.deepPurple,
                      ),
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30.0)),
)),

my getData func

static getData({key}) async {
    final perf = await SharedPreferences.getInstance();
    var data = perf.getString(key);
    print(data);
    return data.toString();
  }

Solution

  • Declare a variable initialValue and then assign it the value by calling the function getData to it as follows:-

    String initialValue='';
    @override
    void initState(){
       super.initState();
       initializeData();
    }
    
    void initializeData()async{
      setState((){
        initialValue=await Data.getData(key: 'phone_number');
      });
    }
    

    and then simply put this initialValue in your below code as:-

    TextFormField(
                  enabled: false,
                 initialValue:  initialValue,
                        maxLength: 14,
                        keyboardType: TextInputType.phone,
                        textDirection: TextDirection.ltr,
                        decoration: InputDecoration(
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.deepPurple),
                          ),
                          suffixIcon: Icon(
                            Icons.phone_android_sharp,
                            color: Colors.deepPurple,
                          ),
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(30.0)),
    )),