-2

I want to show city name(cityName) and temperature(temp) on the flutter screen, but I can see only the red screen error, LateInitializatronError.

What I can't understand is both 'print(cityName) and print(temp)' in updateData method are work well.

It shows what that has.

How can I do?

Here is the code.

import 'package:flutter/material.dart';

class WeatherScreen extends StatefulWidget {
  WeatherScreen({this.parseWeatherData});
  final parseWeatherData;

  @override
  _WeatherScreenState createState() => _WeatherScreenState();
}

class _WeatherScreenState extends State<WeatherScreen> {

  late String cityName;
  late double temp;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    updateData(widget.parseWeatherData);
  }

  void updateData(dynamic weatherData) async {
    temp = weatherData['main']['temp'];
    cityName = weatherData['name'];

    print(cityName);
    print(temp);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                '$cityName',
                style: TextStyle(fontSize: 30.0),
              ),
              SizedBox(
                height: 20.0,
              ),
              Text(
                '$temp',
                style: TextStyle(fontSize: 30.0),
              )
            ],
          ),
        ),
      ),
    );
  }
}
Sam spud
  • 3
  • 1
  • 1
    Does this answer your question? [What is a Future and how do I use it?](https://stackoverflow.com/questions/63017280/what-is-a-future-and-how-do-i-use-it) – nvoigt Aug 18 '21 at 12:19
  • 1
    Look at the above link to understand what you have to do, if you have data arriving async for example via an API. Your way will not work. "late" is not meant to do that. – nvoigt Aug 18 '21 at 12:20
  • Or maybe I misunderstood what your code is doing. Why is it async? You don't seem to be doing anything using an await keyword, could you maybe just drop the async keyword and it works? – nvoigt Aug 18 '21 at 12:21

1 Answers1

0

Not sure why this is the error you get but the text widget is missing a Directionality ancestor widget that specifies if the text is left to right or right to left (MaterialApp also provides this)

So wrap the column in a Directionality

Abhishek Chhabra
  • 366
  • 2
  • 12
  • Thank you for your help. It solved! But I have no idea why it's working. Anyway, thanks a lot! – Sam spud Aug 18 '21 at 12:33
  • uh, that cannot possibly the error... the error says it's a "late initialization error". Because the initialization is in a method declared async and therefore likely to not be done when needed. – nvoigt Aug 18 '21 at 14:04