skip to Main Content

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

2

Answers


  1. There are two mistakes

    1. You are not returning anything from the future<void> param() function
    2. You have to replace Container to FutureBuilder to access variable from future function

    Example:

    Future function:

    Future<String> getData() {
      return Future.delayed(Duration(seconds: 2), () {
        return "I am data";
        // throw Exception("Custom Error");
      });
    }
    

    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(),
    ),
    
    Login or Signup to reply.
  2. 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();
          },
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search