1

每次将新元素(位置)添加到数据库时,我都会尝试更新下面的 listView,但只有在我关闭并重新打开应用程序时才会更新,但在用户导航到 LocationHistory 页面时不会更新

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,
                          ),
             


                        ],
                      )

              );}

            ),);
        







  }
}

我使用 notifyListeners 通知列表重建自身的 locationHistoryModel

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();

  }

当我导航到列表时,我尝试在此处更新列表的小部件未找到任何更改

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,
                ),
              ),



            ],
          ),
        ),

    );
  }
}
4

0 回答 0