In a list, the tapped item id is not coming correctly to the onTap function

Viewed 229

I am loading a list of items and displayed them in flutter cards as per the image(I have removed some UI parts).

vehicle list view.

Once the user taps on a card, it should navigate to a different page and that page take the vehicleID as a parameter. Each and every card has a unique vehicleID, the problem is when user tapped on a card, the id that is passed to the _onVehicleTapped method is wrong, even the parameter has been set correctly.

Ex:- If user tapped on "2011 Toyota Prius" the passing vehicleId is 25 which is a different vehicle Id in the card list and not related to the tapped vehicle card.

Widget build(BuildContext context) {
double deviceWidth = MediaQuery.of(context).size.width;
double deviceHeight = MediaQuery.of(context).size.height;
final ScrollController scrollController = ScrollController();
return Container(
  child: SafeArea(
    child: FutureBuilder(
        future: _getDashboardInfoList(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: Container(
                width: deviceWidth * 0.1,
                height: deviceWidth * 0.1,
                child: new CircularProgressIndicator(),
              ),
            );
          } else if (snapshot.hasError) {
            return Container(
                child: Center(
              child: Text(
                "Something Went Wrong",
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.red),
              ),
            ));
          } else {
            return Padding(
              padding: const EdgeInsets.all(6.0),
              child: Container(
                child: Scrollbar(
                  controller: scrollController,
                  child: ListView.builder(
                      controller: scrollController,
                      itemCount: snapshot.data.length,
                      scrollDirection: Axis.vertical,
                      itemBuilder: (context, index) {
                        dashboardInfo = snapshot.data[index];
                        return InkWell(
                          onTap: () => _onVehicleTapped(
                              dashboardInfo.motorVehicleId),
                          child: Container(
                            key: Key(
                                dashboardInfo.motorVehicleId.toString()),
                            margin: EdgeInsets.all(8.0),
                            child: Card(
                              elevation: 4.0,
                              margin: EdgeInsets.zero,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10),
                              ),
                              child: Column(
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  ListTile(
                                    title: Text(dashboardInfo
                                            .vehicleDisplayName
                                            .toUpperCase() +
                                        " " +
                                        dashboardInfo.motorVehicleId
                                            .toString()),
                                    key: Key('txt_vehicleDisplayName_' +
                                        index.toString()),
                                  ),
                                  dashboardInfo.uri == null
                                      ? Image(
                                          key: Key('img_vehicle_' +
                                              index.toString()),
                                          image: AssetImage(
                                              "assets/vehicle_img.png"),
                                          height: deviceHeight * 0.239,
                                          width: deviceHeight * 0.239)
                                      : Image.network(
                                          dashboardInfo.uri,
                                          key: Key('img_vehicle_' +
                                              index.toString()),
                                          height: deviceHeight * 0.239,
                                          width: deviceHeight * 0.239,
                                        ),
                                  Container(
                                    height: deviceHeight * 0.11,
                                    width: deviceWidth * 0.85,
                                    child: Card(
                                      elevation: 0.0,
                                      margin: EdgeInsets.zero,
                                      child: ListTile(
                                        leading: Container(
                                          color: Colors.blue[900],
                                          width: 40,
                                          height: 40,
                                          child: (Icon(
                                            Icons.video_label,
                                            color: Colors.white,
                                          )),
                                        ),
                                        title: Text(
                                            dashboardInfo.plateNumber == ""
                                                ? "-"
                                                : dashboardInfo.plateNumber,
                                            key: Key('txt_plateNumber_' +
                                                index.toString()),
                                            style: TextStyle(
                                                color: Colors.blue[900],
                                                fontSize: 15)),
                                        subtitle: Text(
                                          'PLATE NUMBER',
                                          style: TextStyle(
                                              color: Colors.blueGrey[400],
                                              fontSize: 14,
                                              fontWeight: FontWeight.bold),
                                        ),
                                      ),
                                    ),
                                  ),
                                  Container(
                                    height: deviceHeight * 0.11,
                                    width: deviceWidth * 0.85,
                                    child: Card(
                                      elevation: 0.0,
                                      margin: EdgeInsets.zero,
                                      child: ListTile(
                                        leading: Container(
                                          color: Colors.yellow[900],
                                          width: 40,
                                          height: 40,
                                          child: (Icon(
                                            Icons.attach_money,
                                            color: Colors.white,
                                          )),
                                        ),
                                        title: Text(
                                          utilityService
                                              .apexCurrencyConverter(
                                                  dashboardInfo
                                                      .availableBalance),
                                          style: TextStyle(
                                              color: Colors.yellow[900],
                                              fontSize: 15),
                                          key: Key('txt_availableBalance_' +
                                              index.toString()),
                                        ),
                                        subtitle: Text(
                                          'AVAILABLE BALANCE',
                                          style: TextStyle(
                                              color: Colors.blueGrey[400],
                                              fontSize: 14,
                                              fontWeight: FontWeight.bold),
                                        ),
                                      ),
                                    ),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.symmetric(
                                        vertical: 5.0),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        );
                      }),
                ),
              ),
            );
          }
        }),
  ),
);

}

This is How _onVehicleTapped method looks like

 _onVehicleTapped(int motorVehicleId) {
Navigator.push(
    context,
    MaterialPageRoute(
        builder: (context) =>
            VehicleDetailsPage(motorVehicleId: motorVehicleId)));

}

1 Answers

Your variable dashboardInfo seems to be not a local variable. As such, it can and will get overwritten from item to item and wherever else you decided to change it's value.

Make dashboardInfo a local variable, for example by adding the final keyword:

final dashboardInfo = snapshot.data[index];

This way it will keep it's value, because during the next call of that function, a new local variable of the same name will be generated.

You can then probably delete the non-local variable called dashboardInfo, wherever it is declared.

Related