0

Im trying to update the listView below every time a new element (location) is added to the database but it is updated only once I close and reopen the app but not when the user navigate to LocationHistory page

class LocationHistory extends StatefulWidget {


  @override
  _LocationHistoryState createState() => _LocationHistoryState();
}

class _LocationHistoryState extends State<LocationHistory> {


  Widget build(BuildContext context) {


            return Scaffold(

              appBar: AppBar(
       
                leading: new IconButton(
                  icon: Icon(Icons.arrow_back),
                  onPressed: () => Navigator.of(context).pop(),
                ),
                title: Text("Saved Locations"),


              ),

              body: Consumer<LocationHistoryModel>(
                  builder: (context, locationHistoryModel, child){
                  return ListView.builder(
                  itemCount: locationHistoryModel.currentUserLocations.length,
                  itemBuilder: (context, index) =>
                      Column(
                        children: <Widget>[
                          buildListTile(
                            address: locationHistoryModel
                                .currentUserLocations[index].address,
                            createdAt: locationHistoryModel
                                .currentUserLocations[index].createdAt,
                            inOut: locationHistoryModel
                                .currentUserLocations[index].inOut,
                          ),
             


                        ],
                      )

              );}

            ),);
        







  }
}

The locationHistoryModel where I use notifyListeners to notify the list to rebuild itself

class LocationHistoryModel extends ChangeNotifier{

  final locationHistory = LocationHistoryRep();
  List currentUserLocations =[];
  User _user;


  set user(User value) {
    _user = value;
  }

  User get user => _user;

  LocationHistoryModel () {

    getLocationHistory();

  }



  getLocationHistory() async{

    var locationsHistory = await locationHistory.getAllSavedLocations();

    List allUsersLocations = locationsHistory["data"] ;

    for(int i =0; i<allUsersLocations.length;i++){

           if(allUsersLocations[i]["userId"]==_user.id){
             currentUserLocations.add(LocationElement.fromJson(allUsersLocations[i]));
           }
    }
    notifyListeners();

    return currentUserLocations;



  }

  setLocation({String address, String inOut}) async{

     await locationHistory.addCurrentLocation(address: address,inOut: inOut,userId: _user.id);
    notifyListeners();

  }

Widget from where I try to update the list here when I navigate to the list no changement are found

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  GoogleMapController mapController;

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }


  @override
  void initState() {
    super.initState();
    Provider.of<AuthModel>(context, listen: false).getUser();


  }



  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    final location = Provider.of<Location>(context);
    final locationHistory = Provider.of<LocationHistoryModel>(context);



    return location.currentLocation == null ? Scaffold(body: CircularIndicator()): Scaffold(

      appBar: AppBar(
        centerTitle: true,
          backgroundColor: Colors.orange,
        title: Center(child: Text('Remote Tracker')),


      ),

      ),
      floatingActionButton: new FloatingActionButton(
        backgroundColor: Colors.orange,
        child: const Icon(Icons.location_on),
        onPressed: () async{

          showDialog(context: context,
              builder: (BuildContext context){
                return AdvanceCustomAlert(
                  location.address,
                      () async{
                    await locationHistory.setLocation(address: location.address,inOut: "out");
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => LocationHistory(),
                    // here when navigating to LocationHistory the list is not updating
                    ));
                    },
                      () async{
                    await locationHistory.setLocation(address: location.address,inOut: "in");
                    Navigator.of(context).pop();

                    },
                );
              }
          );// Add your onPressed code here!
        },
      ),
      floatingActionButtonLocation:
      FloatingActionButtonLocation.centerFloat,
      bottomNavigationBar: new BottomAppBar(
        color: Colors.white,

      ),
        body: Container(
          width: size.width,
          height: size.height,
          child: Stack(
            alignment: Alignment.centerRight,
            children: <Widget>[
              GoogleMap(
                onMapCreated: _onMapCreated,
                myLocationEnabled: true,
                initialCameraPosition: CameraPosition(
                  target: LatLng(location.currentLocation.latitude,location.currentLocation.longitude),
                  zoom: 14.0,
                ),
              ),



            ],
          ),
        ),

    );
  }
}
Ah_Ch_97
  • 61
  • 1
  • 9
  • Provider ChangeNotifier only listen on changes inside your Provider Service/Class. If your referring to changes on your database ofcourse your Provider wont know that. You need to call again your function to retrieve the changes on your databases. The other way around is to stream changes on your databases so your Provider can changed its state values. – Raine Dale Holgado Apr 13 '21 at 08:19
  • When your LocationHistoryModel is Initialize you called getLocationHistory(); in the constructor this is only called once your LocationHistoryModel. If you want you can set getLocationHistory() to be called again or add a refresh method to call that method – Raine Dale Holgado Apr 13 '21 at 08:23
  • everytime I use the LocationHistoryModel I recall the getLocationHistory method..It should retrieve the new list element s no ? – Ah_Ch_97 Apr 13 '21 at 08:26
  • Try adding print statement if it got called again. But yes if you recall getLocationHistory method it should retrieve new list. But keep it mind that it might add it to the previous currentUserLocations List.. You can currentUserLocations.clear() then fill it up again – Raine Dale Holgado Apr 13 '21 at 08:29

0 Answers0