0

I want to show different images for different outputs of JSONdecode. I get var between 01d and 50d. For example, when it gives out 04d, I want to show Image 'assets/night.png' and for 05d, I want to show Image 'assets/afternoon.png' and more. I am a complete beginner with flutter, this is what I thought about:

var current_icon;

  Future getWeather () async {
    http.Response response = await http.get(Uri.parse("https://api.openweathermap.org/data/2.5/weather?q=city&appid=****"));
    var results = jsonDecode(response.body);
    setState(() {
      this.current_icon = results['weather'][0]['icon'];
    });
  }
@override
  void initState () {
    super.initState();
    this.getWeather();
  }

and then put it in my container here:

new Container(
    height: double.infinity,
    width: double.infinity,
    child: new Image(
          image: (What should I do here?),
          fit: BoxFit.cover,
       ),
    ), 
2
  • Use conditional statement (ie. if - else if or switch) and return image data based on your requirement and pass to your image widget Commented Jul 9, 2021 at 14:45
  • But how should I do that? Can you give me some code, please? Commented Jul 9, 2021 at 14:59

1 Answer 1

0

As per your query assuming all images comes from assets. You can make cases as per your requirement like this:

String getImageData(String id) {
    String value = '';
    switch (id) {
      case '01d':
        value = 'assets/a.png';
        break;
      case '02d':
        value = 'assets/b.png';
        break;
      default:
        value = 'assets/c.png';
    }
    return value;
  }

pass below widget as child of your container widget

Widget imageWidget() {
    return Image.asset(
      getImageData('01d'), // pass your value here
      fit: BoxFit.cover,
    );
  }
Sign up to request clarification or add additional context in comments.

5 Comments

Ok thanks a lot, but isn't it showing the same every time? Like, now it is showing 01d, which is great, but in this moment the output of the decode is 04d. Can you help me again?
You need to pass the output of your jsonDecode to getImageData. So instead of getImageData('01d'), do getImageData(current_icon).
@Cubii you have a special privilege: you may accept the answer that you believe is the best solution to your problem
I didn't know that I have to do that, here you go. Another little question: When I navigate to the page it shows a red screen saying type 'Null' is not a subtype of type 'String' for a second. Do you have an idea how I could fix that?
@Cubii Might this helps you: stackoverflow.com/questions/59955033/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.