Ad

Flutter Conditional Statement With Output Of Jsondecode Var

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

Answer

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,
    );
  }
Ad
source: stackoverflow.com
Ad