0

I successfully get data from API. I test it using the Print command and the element displayed successfully in the console. When I tried to access the same element in TEXT Widget it displays null.

Here is the code:

import 'package:api_practice/worker/data.dart';
import 'package:flutter/material.dart';
import 'package:api_practice/worker/data.dart';

class WeatherHome extends StatefulWidget {
  @override
  _WeatherHomeState createState() => _WeatherHomeState();
}

class _WeatherHomeState extends State<WeatherHome> {
  TextEditingController searchcont = TextEditingController();
  DataClass datainstace = DataClass();

  void data() async {
    await datainstace.getcurrentlocation();
    await datainstace.getdata();
    print(datainstace.area);
  }

  @override
  void initState() {
    data();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child:Text(
                ("${datainstace.area}"),
                style: TextStyle(fontSize: 25, color: Colors.white),
              ),
    );
  }
}

output on console: output in console

App looks like: appscreen

Anas Shafi
  • 25
  • 1
  • 4

3 Answers3

2

In addition to the previous answers, you can use a value listenable builder, this improves performance and thus it is not necessary to use a setState.

You can check the following link to obtain information on how to use it Explore ValueListenableBuilder in Flutter

1

You should use setState method in data function. Because your build method is finishing before your async method.

Use it like this:

import 'package:api_practice/worker/data.dart';
import 'package:flutter/material.dart';
import 'package:api_practice/worker/data.dart';

class WeatherHome extends StatefulWidget {
  @override
  _WeatherHomeState createState() => _WeatherHomeState();
}

class _WeatherHomeState extends State<WeatherHome> {
  TextEditingController searchcont = TextEditingController();
  DataClass datainstace = DataClass();

  void data() async {
    await datainstace.getcurrentlocation();
    await datainstace.getdata();
    print(datainstace.area);
    setState(() {});
  }

  @override
  void initState() {
    data();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child:Text(
                "${datainstace.area}",
                style: TextStyle(fontSize: 25, color: Colors.white),
              ),
    );
  }
}
Hazar Belge
  • 1,009
  • 4
  • 20
0

when you want to update the state of your widget, you have to call the setState function to make the widget re-render with the changes.

  void data() {
    setState(() async {
      await datainstace.getcurrentlocation();
      await datainstace.getdata();
      print(datainstace.area);
    });
  }