Search code examples
flutterdartlistviewdart-async

setState doesn't update the ListView data


I want to load data on ListView from API on only button click event not in initState(). I getting data from server but not updated on ListView.

I searched for this but not get any proper solution, I'm new in flutter.

here's my code:

@override
  Widget build(BuildContext context) {

    List<dynamic> ListData = [];

Future _getData() async {

      String apiUrl = "http://myURL";
      final params = {"id": "1", "keyword": "xyz"};

      var response = await http.post(
        Uri.parse(apiUrl),
        body: params,
      );

      var jsonData = jsonDecode(response.body);

      List<dynamic> DATA = [];
      DATA = jsonData['data'];

      setState(() {
        ListData = DATA;
      });

      print('DATA COUNT: ${ListData.length}');

      return ListData;
    }
}

I'm getting here "DATA COUNT" properly, check below button & ListView code.

    SizedBox(
     height: 45,
     width: 60,
     child: ElevatedButton(
            style: ElevatedButton.styleFrom(
            primary: Colors.orangeAccent,
            ),
     onPressed: () async {
     await _getData();
     print('button pressed ${ListData.length}');
     },
     child: Text(
     '${ListData.length}',
     style: TextStyle(
     fontSize: 18.0,
     fontWeight: FontWeight.bold,
     ),
    ),
   ),
  ),
Expanded(
  child: ListView.builder(
    itemCount: ListData.length,
    itemBuilder: (context, index) {
      return ListTile(
        title: Text('${ListData[index]}'),
      );
    },
  ),
),

I'm getting data here "button pressed" also properly, but not updated on button text and ListView builder, what is wrong in this my code thanks in advance.


Solution

  • Remove your ListData from build method. The reason is when setState is called each time method will be rebuild and hence it will make your ListData empty each time.

    List<dynamic> ListData = [];
    
    `@override
    
    Widget build(BuildContext context) {
    
    
    
    Future _getData() async {
    
      String apiUrl = "http://myURL";
      final params = {"id": "1", "keyword": "xyz"};
    
      var response = await http.post(
        Uri.parse(apiUrl),
        body: params,
      );
    
      var jsonData = jsonDecode(response.body);
    
      List<dynamic> DATA = [];
      DATA = jsonData['data'];
    
      setState(() {
        ListData = DATA;
      });
    
      print('DATA COUNT: ${ListData.length}');
    
      return ListData;
    }
    

    }`