Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh list after deleting an item - Flutter

Tags:

list

flutter

api

I am trying to get the list to automatically refresh after the delete option on pop up menu is pressed. It will delete the selected item from a list of items called from an api. That item should immediately dissapear after delete is pressed on it.

API call that fills the list with api data:

  List data;

  @override
  void initState() {
    super.initState();
    this.getJsonData();
  }

  Future<String> getJsonData() async {
    var response = await http.get(
      Uri.encodeFull(url),
      headers: {"Accept": "application/json"},
    );

    var extractdata = json.decode(response.body);
    data = extractdata['levels'];
    levelsData = data;

    setState(
      () {
        var extractdata = json.decode(response.body);
        data = extractdata['levels'];
      },
    );
    return "Success";
  }

...

Api call that deletes:

  delete() async {
    String url = "http://31.183.125.253:8080/users";

    Map map = {
      'price': 1.23,
      'user_id': 'user2'
    };

    print(await apiRequest(url, map));
  }

  Future<String> apiRequest(String url, Map jsonMap) async {
    HttpClient httpClient = new HttpClient();
    HttpClientRequest request = await httpClient.deleteUrl(Uri.parse(url));
    request.headers.set('content-type', 'application/json');
    request.add(utf8.encode(json.encode(jsonMap)));
    HttpClientResponse response = await request.close();
    String statusCode = response.statusCode.toString();
    String reply = await response.transform(utf8.decoder).join();

    print(statusCode);

    httpClient.close();
    return reply;
  }

Expansion tile that stores the list from api call:

...

var levelsData = [];

  @override
  Widget build(BuildContext context) {
    List<dynamic> _getChildren() {
      List<Widget> children = [];
      levelsData.forEach(
        (element) {
            children.add(
              ListTile(
                title: Text(element['price'].toString(),
                trailing: PopUpMenu(
                  onDelete: () {
                    setState(() {
                      delete();
                    });
                  }))
            );}
      );
      return children;
    }
  }

...

Pop up menu:

class PopUpMenu extends StatelessWidget {
  VoidCallback onDelete;

  PopUpMenu({this.onDelete});

  void showMenuSelection(String value) {
    switch (value) {
      case 'Delete':
        onDelete();
        break;
      // Other cases for other menu options
    }
  }

I am able to delete the item selected to delete but the item doesnt dissapear from the list and it didnt show the changes of the list.

like image 374
irongirl Avatar asked Jan 26 '23 13:01

irongirl


2 Answers

Flutter should automatically update to reflect changes to datasources. However, this is only applied after calling:

setState((){

});

So that should be run after you delete the item from the list.

like image 155
DevTard Avatar answered Feb 04 '23 14:02

DevTard


You have to call setState and remove the item from your list.

     class _MyListViewState extends State<MyListView> {
          MyDB _myDB;
          List<MyItem> _myList;

        ...

      void getData() async {
        ...

        _myDB.getData().then((items) {
          setState(() {
            _myList = items;
          });
        });
      }

      @override
      void initState() {
        super.initState();
        getData();
      }

              @override
              Widget build(BuildContext context) {
                return (_myList== null || _myList.isEmpty)
                    ? Center(child: Text('Nothing to see...'))
                    : ListView.builder(
                        itemCount: _myList.length,
                        itemBuilder: (context, index) {
                          return

        ... onPress ...

                _myDB.deleteItem(_myList[index]).whenComplete(() {
                                                setState(() {
                                                  _myList.removeAt(index);
                                                });
                                              });
like image 25
live-love Avatar answered Feb 04 '23 16:02

live-love