获取来自Future函数的变量如何做?

huangapple go评论63阅读模式
英文:

How do I get the variable from a Future function?

问题

以下是已翻译的内容:

I have a Future function that retrieves data. It performs well, however, my goal is to display the data in a widget. The problem is that I can't seem to use the variable.

Here is the code I used for the Future function:

Future<void> param() async {
    String url1 = "my url";
    final response1 = await http.get(url1);
    String url2 = "my url";
    final response2 = await http.get(url2);
    String url3 = "my url";
    final response3 = await http.get(url3);
    String url4 = "my url";
    final response4 = await http.get(url4);

    field_1 fieldno1 = field_1.fromJson(jsonDecode(response1.body));
    field_2 fieldno2 = field_2.fromJson(jsonDecode(response2.body));
    field_3 fieldno3 = field_3.fromJson(jsonDecode(response3.body));
    field_4 fieldno4 = field_4.fromJson(jsonDecode(response4.body));

    final String? co2 = fieldno1.field1;
    final String? pm25 = fieldno2.field2;
    final String? temp = fieldno3.field3;
    final String? humi = fieldno4.field4;

    print(co2);
    print(pm25);
    print(temp);
    print(humi);
}

And here is where I wish to put my variable (co2):

Container(
    height: 100,
    margin: const EdgeInsets.only(top: 20, bottom: 20, left: 15, right: 15,),
    padding: const EdgeInsets.only(right: 40, left: 30),
    decoration: BoxDecoration(
        color: co2 > 1000 ? Color(0xFFF1954A) : Color(0xFF7dbd0c),
        borderRadius: const BorderRadius.all(Radius.circular(15.0)),
    ),
    child: sub(co2, "2", "CO", "Carbon Dioxide", "ppm"),
),
英文:

I have a Future function that retrieves data. It performs well, however, my goal is to display the data in a widget. The problem is that I can't seem to use the variable.

Here is the code I used for the Future function:

Future&lt;void&gt; param() async{
    String url1 = &quot;my url&quot;;
    final response1 = await http.get(url1);
    String url2 = &quot;my url&quot;;
    final response2 = await http.get(url2);
    String url3 = &quot;my url&quot;;
    final response3 = await http.get(url3);
    String url4 = &quot;my url&quot;;
    final response4 = await http.get(url4);

    field_1 fieldno1 = field_1.fromJson(jsonDecode(response1.body));
    field_2 fieldno2 = field_2.fromJson(jsonDecode(response2.body));
    field_3 fieldno3 = field_3.fromJson(jsonDecode(response3.body));
    field_4 fieldno4 = field_4.fromJson(jsonDecode(response4.body));

    final String? co2 = fieldno1.field1;
    final String? pm25 = fieldno2.field2;
    final String? temp = fieldno3.field3;
    final String? humi = fieldno4.field4;

    print(co2);
    print(pm25);
    print(temp);
    print(humi);
  }

And here is where I wish to put my variable (co2):

Container(
              height: 100,
              margin: const EdgeInsets.only(top: 20, bottom: 20, left: 15, right: 15,),
              padding: const EdgeInsets.only(right: 40, left: 30),
              decoration: BoxDecoration(
                color: co2 &gt; 1000 ? Color(0xFFF1954A) : Color(0xFF7dbd0c),
                borderRadius: const BorderRadius.all(Radius.circular(15.0)),),
              child: sub(co2, &quot;2&quot; , &quot;CO&quot;, &quot;Carbon Dioxide&quot;,&quot;ppm&quot;),
            ),

答案1

得分: 2

  1. 你没有从future&lt;void&gt; param()函数中返回任何内容。

  2. 你必须将Container替换为FutureBuilder,以从future函数中访问变量。

示例:

Future函数:

Future&lt;String&gt; getData() {
  return Future.delayed(Duration(seconds: 2), () {
    return &quot;我是数据&quot;;
    // throw Exception(&quot;自定义错误&quot;);
  });
}

FutureBuilder:

FutureBuilder(
  builder: (ctx, snapshot) {
    ... 这里放一些代码
       
    // 显示LoadingSpinner以指示等待状态
    return Center(
      child: CircularProgressIndicator(),
    );
  },
   
  // 需要解析的Future
  // 以便在Canvas上显示某些内容
  future: getData(),
),
英文:

There are two mistakes

  1. You are not returning anything from the future&lt;void&gt; param() function
  2. You have to replace Container to FutureBuilder to access variable from future function

Example:

Future function:

Future&lt;String&gt; getData() {
  return Future.delayed(Duration(seconds: 2), () {
    return &quot;I am data&quot;;
    // throw Exception(&quot;Custom Error&quot;);
  });
}

FutureBuilder:

FutureBuilder(
  builder: (ctx, snapshot) {
    ... some code here
       
    // Displaying LoadingSpinner to indicate waiting state
    return Center(
      child: CircularProgressIndicator(),
    );
  },
   
  // Future that needs to be resolved
  // inorder to display something on the Canvas
  future: getData(),
),

答案2

得分: 0

以下是您要翻译的代码部分:

You have multiple variables to return.

in this case, you can do it like below:

import 'package:flutter/material.dart';

class MyDataView extends StatefulWidget {
  @override
  _MyDataViewState createState() => _MyDataViewState();
}

class _MyDataViewState extends State<MyDataView> {
  Future<Map<String, dynamic>>? futureData;

  @override
  void initState() {
    super.initState();
    futureData = param();
  }

  Future<Map<String, dynamic>> param() async {
    String url1 = "my url";
    final response1 = await http.get(url1);
    String url2 = "my url";
    final response2 = await http.get(url2);
    String url3 = "my url";
    final response3 = await http get(url3);
    String url4 = "my url";
    final response4 = await http.get(url4);

    field_1 fieldno1 = field_1.fromJson(jsonDecode(response1.body));
    field_2 fieldno2 = field_2.fromJson(jsonDecode(response2.body));
    field_3 fieldno3 = field_3.fromJson(jsonDecode(response3.body));
    field_4 fieldno4 = field_4.fromJson(jsonDecode(response4.body));

    final String? co2 = fieldno1.field1;
    final String? pm25 = fieldno2.field2;
    final String? temp = fieldno3.field3;
    final String? humi = fieldno4.field4;

    print(co2);
    print(pm25);
    print(temp);
    print(humi);

    Map<String, dynamic> data = {
      "co2": co2,
      "pm25": pm25,
      "temp": temp,
      "humi": humi,
    };

    return data;
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<Map<String, dynamic>>(
      future: futureData,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Container(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              children: [
                Text("CO2: ${snapshot.data!['co2']}"),
                Text("PM25: ${snapshot.data!['pm25']}"),
                Text("Temperature: ${snapshot.data!['temp']}"),
                Text("Humidity: ${snapshot.data!['humi']}"),
              ],
            ),
          );
        } else if (snapshot.hasError) {
          return Text("${snapshot.error}");
        }
        return const CircularProgressIndicator();
      },
    );
  }
}

希望这有所帮助!

英文:

You have multiple variables to return.

in this case, you can do it like below:

import &#39;package:flutter/material.dart&#39;;
class MyDataView extends StatefulWidget {
@override
_MyDataViewState createState() =&gt; _MyDataViewState();
}
class _MyDataViewState extends State&lt;MyDataView&gt; {
Future&lt;Map&lt;String, dynamic&gt;&gt;? futureData;
@override
void initState() {
super.initState();
futureData = param();
}
Future&lt;Map&lt;String, dynamic&gt;&gt; param() async {
String url1 = &quot;my url&quot;;
final response1 = await http.get(url1);
String url2 = &quot;my url&quot;;
final response2 = await http.get(url2);
String url3 = &quot;my url&quot;;
final response3 = await http.get(url3);
String url4 = &quot;my url&quot;;
final response4 = await http.get(url4);
field_1 fieldno1 = field_1.fromJson(jsonDecode(response1.body));
field_2 fieldno2 = field_2.fromJson(jsonDecode(response2.body));
field_3 fieldno3 = field_3.fromJson(jsonDecode(response3.body));
field_4 fieldno4 = field_4.fromJson(jsonDecode(response4.body));
final String? co2 = fieldno1.field1;
final String? pm25 = fieldno2.field2;
final String? temp = fieldno3.field3;
final String? humi = fieldno4.field4;
print(co2);
print(pm25);
print(temp);
print(humi);
Map&lt;String, dynamic&gt; data = {
&quot;co2&quot;: co2,
&quot;pm25&quot;: pm25,
&quot;temp&quot;: temp,
&quot;humi&quot;: humi,
};
return data;
}
@override
Widget build(BuildContext context) {
return FutureBuilder&lt;Map&lt;String, dynamic&gt;&gt;(
future: futureData,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Container(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Text(&quot;CO2: ${snapshot.data![&#39;co2&#39;]}&quot;),
Text(&quot;PM25: ${snapshot.data![&#39;pm25&#39;]}&quot;),
Text(&quot;Temperature: ${snapshot.data![&#39;temp&#39;]}&quot;),
Text(&quot;Humidity: ${snapshot.data![&#39;humi&#39;]}&quot;),
],
),
);
} else if (snapshot.hasError) {
return Text(&quot;${snapshot.error}&quot;);
}
return const CircularProgressIndicator();
},
);
}
}

huangapple
  • 本文由 发表于 2023年3月1日 12:49:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75599675.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定