【问题标题】:Instance of 'Future<String>' instead of showing the value'Future<String>' 的实例而不是显示值
【发布时间】:2019-01-27 15:33:00
【问题描述】:

我正在使用颤振,我试图从我之前设置的 shared_preferences 中获取一个值,并将其显示在一个文本小部件中。但我得到Future&lt;String&gt; 的实例而不是值。这是我的代码:

Future<String> getPhone() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    final String patientPhone = prefs.getString('patientPhone').toString();
        print(patientPhone);

    return patientPhone;
  }

Future<String> phoneOfPatient = getPhone();

Center(child: Text('${phoneOfPatient}'),))

【问题讨论】:

    标签: flutter dart future


    【解决方案1】:

    prefs.getString( 之前缺少await 并使用setState() 而不是返回值。 build() 不能使用await

      String _patientPhone;
    
      Future<void> getPhone() async {
        final SharedPreferences prefs = await SharedPreferences.getInstance();
        final String patientPhone = await /*added */ prefs.getString('patientPhone');
        print(patientPhone);
    
        setState(() => _patientPhone = patientPhone);
      }
    
      build() {
        ...
        Center(child: _patientPhone != null ? Text('${_patientPhone}') : Container(),))
      }
    

    【讨论】:

    • 我没有收到该错误,但显示的值为 null,我确信它不为 null,因为我在另一个文件中使用它(该文件是 http 响应并且没有建设者)
    • 您使用了我的_patientPhone != null ... 代码吗?该值最初是null,因为获取它的代码是异步的,并且只会在一段时间后产生一个值!= null。当 Flutter 同时运行 build() 时,该值仍然是 null
    • print(patientPhone); 打印过什么吗?
    • 在其他文件中是这样,但在这里不是。
    • 这里还有之前的代码,它确实显示了手机,但是当我将它更改为你的代码时,它不会打印任何东西
    【解决方案2】:

    调用返回 Future 的函数不会阻塞您的代码,这就是该函数被称为异步的原因。相反,它会立即返回一个未完成的 Future 对象。

    String phoneOfPatient;
    
    Future<void> getPhone() async {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      final String patientPhone = await /*added */ prefs.getString('patientPhone');
    
    }
    

    func 这样调用之后。 Future 的结果只有在 Future 完成后才可用。

    您可以使用以下任一关键字访问 Future 的结果:

    那么

    等待

    您可以通过以下任一方式使用此函数的结果:

    getphone.then((value) =>  {
      print(value);               // here will be printed patientPhone numbers.
      phoneOfPatient = value;
    });
    

    或者

    Future<void> foo() async {
      String phoneOfPatient = await getphone();
      print(phoneOfPatient);        // here will be printed patientPhone numbers.
    }
    

    【讨论】:

      【解决方案3】:

      如果您无法选择使用awaitasync,您可以执行以下操作。

      getPhone().then((value){
       print(value);
      });
      

      然后为它们分配一个变量。由此,您将获得来自value 的结果。

      【讨论】:

        猜你喜欢
        • 2023-02-11
        • 1970-01-01
        • 2020-08-15
        • 2022-01-20
        • 1970-01-01
        • 1970-01-01
        • 2021-10-12
        • 1970-01-01
        • 2012-02-09
        相关资源
        最近更新 更多