Home > other >  How to fix abscence of fetching data inside initState in Flutter?
How to fix abscence of fetching data inside initState in Flutter?

Time:11-18

I am building an image with list of countries

And get data of countries from Api, I call a function inside initState()

And data is not showed.

Here is no data

But if I try to type and then delete text inside textFormField then data appears

Here is data when I try to type and then delete text

This is my widget:

class SignUp extends StatefulWidget {
  const SignUp({super.key});

  @override
  State<SignUp> createState() => _SignUpState();
}

class _SignUpState extends State<SignUp> {

  List _allCountries = [];
  List _foundCountries = [];

  bool showDropDown = false;

  final ApiService _apiService = ApiService();

  Future<void> getCountries() async {
    try {
      final response = await _apiService.getCountries();
      _allCountries = response['list'];
      log(_allCountries.toString());
    } catch (e) {
      log(e.toString());
      rethrow;
    }
  }

  @override
  void initState() {
    getCountries();
    _foundCountries = _allCountries;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          TextFormField(
            onTap: () {
                setState(() {
                  showDropDown = !showDropDown;
                  // _foundCountries = _allCountries; If I try to add this code, data appears when screen is loaded
                });
              },
          ),
          SizedBox(
            child: showDropDown ? Column(
              children: [
                Flexible(
                  child: ListView.builder(
                    itemCount: _foundCountries.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                        title: Text(
                          _foundCountries[index]['name']
                        ),
                      );
                    },
                  )
                )
              ],
            ) : null,
          )
        ],
      ),
    );
  }
}

The response from Api looks like this:

{"success":true,"list":[{"id": 1, "name": "Abkhazia"}, {"id":2, "name": ""Afghanistan"}]}

I think, the problem is inside initState(), when I set _filteredCountries = _allCountries

I don't know why flutter can't set data inside state. How can I fix that?

CodePudding user response:

Try setState after you get response like this:

Future<void> getCountries() async {
    try {
      final response = await _apiService.getCountries();
      _allCountries = response['list'];
      setState(() {
        _foundCountries = _allCountries;
      });
    } catch (e) {
      log(e.toString());
      rethrow;
    }
  }

and remove _foundCountries = _allCountries; line inside your initState, when you call this line, _allCountries still don't have any data

  • Related