Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear data when back button pressed

Tags:

flutter

dart

I've 2 pages, and each of these pages have the same function in initState that return a list.

The first page has the regular function, the second page has the same function but with filter that return filtered list.

The problem is when i press on the "back button" in the second page and go back to the first page, I am getting the filtered list instead of the regular list.

How do i "clear" the data from the second page before going to the first page?

The function:

  Future fetchProducts({flag = false})  {
  return http
        .get(
            'MyAddress')
        .then<Null>((http.Response response) {
      final Map<String, dynamic> listData = json.decode(response.body); 
      listData.forEach((String id, dynamic fetchedData) {
        final Product product = Product(
          id: id, 
          address: fetchedData['address'],
          image: fetchedData['imageUrl'],
        );
        fetchedData.add(product);   
      });
      _product = flag
          ? fetchedData.where((Product product) {        
              return product.userId == 1;
            }).toList()
                     : fetchedData;
    });
  }
like image 806
Michael Avatar asked Jun 08 '19 10:06

Michael


1 Answers

There are two ways of triggering actions when going back to a page (route).

1)

void WaitforBeingBackfromConfig() async{
    await Navigator.push(
      context, MaterialPageRoute(
        builder: (context) => ConfigScreen('platzhalter'))
    );

//Do something right after return to page1
  }

2) As stated before by @Michael: WillPopScope:

Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _SaveAndBack,
      child: Scaffold(
        appBar: AppBar(
          title: Text('Config'),
        ),
        body: Column(children: <Widget>[
     ....    ]),
      ),
    );

This calls the function "_SaveAndBack" before page2 is left.

like image 184
Christian Dressler Avatar answered Nov 27 '22 01:11

Christian Dressler