【问题标题】:Future<dynamic> is not subtype of type String? flutter ErrFuture<dynamic> 不是 String 类型的子类型?颤振错误
【发布时间】:2021-08-17 05:16:26
【问题描述】:

我的应用程序出错了。我无法从 Flutter 中的共享性能中读取数据

我的代码

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)),
)),

我的 getData 函数

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

【问题讨论】:

标签: flutter dart sharedpreferences


【解决方案1】:

当您返回 String 值并且由于您没有指定返回类型时,您会收到此错误。

请将您当前的 getData 函数替换为以下函数,希望这能解决问题。

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

【讨论】:

    【解决方案2】:

    声明一个变量initialValue,然后通过调用函数getData给它赋值,如下:-

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

    然后简单地将这个 initialValue 放在下面的代码中:-

    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)),
    )),
    

    【讨论】:

      猜你喜欢
      • 2020-01-01
      • 2021-10-21
      • 2021-11-20
      • 2021-12-10
      • 2021-10-18
      • 2019-06-26
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      相关资源
      最近更新 更多