madusanka
madusanka

Reputation: 163

Populate json api data in a dropdownbox in flutter

I was trying to populate json array data into dropdown and it worked fine. And after I tried to replace json array with json api. after replacing with api it doesn't work. This may a simple problem but it seems hard to me...i'm totally new to flutter. I couldn't find a proper tutorial.please give me the way to do it. below is my code

home.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:chart_test1/countryList.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;


  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
 Countries countries;

  List<Countries> _list = [];
  String selectedRegion;

  @override
  Widget build(BuildContext context) {
    final json = JsonDecoder().convert(countries);
//here counttries is a problem

    _list = (json).map<Countries>((item) => Countries.fromJson(item)).toList();
    selectedRegion = _list[0].iso2;

    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            DropdownButtonHideUnderline(
              child: new DropdownButton<String>(
                hint: new Text("Select Region"),
                value: selectedRegion,
                isDense: true,
                onChanged: (String newValue) {
                  setState(() {
                    selectedRegion = newValue;
                  });
                  print(selectedRegion);
                },
                items: _list.map((Countries map) {
                  return new DropdownMenuItem<String>(
                    value: map.iso2,
                    child: new Text(map.country,
                        style: new TextStyle(color: Colors.black)),
                  );
                }).toList(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

apiData.dart

import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';

class Countries {
  final String country;
  final String slug;
  final String iso2;

  Countries({this.country, this.slug, this.iso2});  

  factory Countries.fromJson(Map<String, dynamic> json) {
    return Countries(
      country: json['country'],
      slug: json['slug'],
      iso2: json['iso2'],
    );
  }

  Future<List<Countries>> getAllCountries() async {

    var data = await http.get("https://api.covid19api.com/countries");

    var jsonData = json.decode(data.body);
    print(jsonData);
    return jsonData;
  }


}

Thank you!

Upvotes: 0

Views: 60

Answers (1)

chunhunghan
chunhunghan

Reputation: 54407

You can copy paste run full code below
You can parse with countriesFromJson and call init() to initialize _list in initState

code snippet

 List<Countries> countriesFromJson(String str) =>
    List<Countries>.from(json.decode(str).map((x) => Countries.fromJson(x)));
 ...
 static Future<List<Countries>> getAllCountries() async {
    var data = await http.get("https://api.covid19api.com/countries");
    var jsonData = countriesFromJson(data.body);
    print(jsonData);
    return jsonData;
  }
 ... 
 @override
  void initState() {
    // TODO: implement initState
    init();
    super.initState();
  }

  void init() async {
    _list = await Countries.getAllCountries();
    selectedRegion = _list[0].iso2;
    setState(() {});
  }

working demo

enter image description here

full code

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';

List<Countries> countriesFromJson(String str) =>
    List<Countries>.from(json.decode(str).map((x) => Countries.fromJson(x)));

String countriesToJson(List<Countries> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Countries {
  String country;
  String slug;
  String iso2;

  Countries({
    this.country,
    this.slug,
    this.iso2,
  });

  factory Countries.fromJson(Map<String, dynamic> json) => Countries(
        country: json["Country"],
        slug: json["Slug"],
        iso2: json["ISO2"],
      );

  Map<String, dynamic> toJson() => {
        "Country": country,
        "Slug": slug,
        "ISO2": iso2,
      };

  static Future<List<Countries>> getAllCountries() async {
    var data = await http.get("https://api.covid19api.com/countries");
    var jsonData = countriesFromJson(data.body);
    print(jsonData);
    return jsonData;
  }
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  Countries countries = Countries();

  List<Countries> _list = [];
  String selectedRegion;

  @override
  void initState() {
    // TODO: implement initState
    init();
    super.initState();
  }

  void init() async {
    _list = await Countries.getAllCountries();
    selectedRegion = _list[0].iso2;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            DropdownButtonHideUnderline(
              child: DropdownButton<String>(
                hint: Text("Select Region"),
                value: selectedRegion,
                isDense: true,
                onChanged: (String Value) {
                  setState(() {
                    selectedRegion = Value;
                  });
                  print(selectedRegion);
                },
                items: _list.map((Countries map) {
                  return DropdownMenuItem<String>(
                    value: map.iso2,
                    child: Text(map.country,
                        style: TextStyle(color: Colors.black)),
                  );
                }).toList(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Upvotes: 1

Related Questions