我可以从函数中获取返回值

发布于 2025-02-07 01:25:00 字数 796 浏览 0 评论 0原文

我有一个名为totallabel()的类,该类从另一个函数中获得双重值:

Future<double> getValue(String type) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    double total = prefs.getDouble(type) ?? 0;
    return total;
  } 

这就是我调用该函数以获取结果的方式:

TotalLabel(
                typeOf: 'Hidrats de carboni',
                subtitle: 'Range',
                onPressed: () {},
                fillBar:
                    getValue('hidratsDeCarboni') //gets result from function
                )

问题是,当我调用函数传递函数时,传递了我想要获得的变量的ID时,我有一个错误:“参数类型'未来不能分配给参数类型double”。

谢谢。

I have a class called TotalLabel() that gets a double value from another function:

Future<double> getValue(String type) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    double total = prefs.getDouble(type) ?? 0;
    return total;
  } 

This is how I call the function to get the result:

TotalLabel(
                typeOf: 'Hidrats de carboni',
                subtitle: 'Range',
                onPressed: () {},
                fillBar:
                    getValue('hidratsDeCarboni') //gets result from function
                )

The problem is that when I call the function passing the ID of the variable that I want to get, I have this error: "The argument type 'Future can't be assigned to the parameter type double".

Error

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猫性小仙女 2025-02-14 01:25:00

getValue返回future&lt; double&gt;,因此您要么在initstate 中等待它,要么使用Future> FutureBuilder

FutureBuilder<double>(
  future: getValue('hidratsDeCarboni'),
  builder: (context, snapshot) {
    if(snapshot.connectionState != ConnectionState.done) {
      return CircularProgressIndicator();
    } else if(!snapshot.hasError && snapshot.hasData) {
      return TotalLabel(
        typeOf: 'Hidrats de carboni',
        subtitle: 'Range',
        onPressed: () {},
        fillBar: snapshot.data!,
      );
    } else {
      return const Text('error');
    }
  }
)

getValue returns a Future<double> so you either await for it in the initState or use a FutureBuilder

FutureBuilder<double>(
  future: getValue('hidratsDeCarboni'),
  builder: (context, snapshot) {
    if(snapshot.connectionState != ConnectionState.done) {
      return CircularProgressIndicator();
    } else if(!snapshot.hasError && snapshot.hasData) {
      return TotalLabel(
        typeOf: 'Hidrats de carboni',
        subtitle: 'Range',
        onPressed: () {},
        fillBar: snapshot.data!,
      );
    } else {
      return const Text('error');
    }
  }
)
给妤﹃绝世温柔 2025-02-14 01:25:00

您正在从未来函数中返回值,您需要使用等待响应,然后使用该值。

you are returning the value from a future function you need to use await to wait for a response then use that value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文