Nick
Nick

Reputation: 875

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.

Upvotes: 1

Views: 1566

Answers (2)

Raju Gupta
Raju Gupta

Reputation: 802

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;
}

}`

Upvotes: 1

scrutycs
scrutycs

Reputation: 29

You are assigning ListData = [] in you build Methode. When your build Methode is called by setState() ListData is assigned to [] again.

Try to assign ListData = [] abough your build methode

Upvotes: 1

Related Questions