Home > Back-end >  Not getting the expected parameter with Navigator.push
Not getting the expected parameter with Navigator.push

Time:04-18

I am having a very odd problem. record: data is being passed correctly; different for every record as expected. But not colorIndex. It's always 8, which is the number of the last item on my list. What's wrong?

List Widget

class NameList extends StatelessWidget {
  const NameList({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    int colorIndex = 0;

    return Container(
      child: GridView.count(
        primary: false,
        children: names.map((data) {
          colorIndex < Colors.primaries.length - 1
              ? colorIndex  
              : colorIndex = 0;

          return Ink(
            color: Colors.primaries[colorIndex][100],
            child: InkWell(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => DetailPage(
                      record: data,
                      colorIndex: colorIndex,
                    ),
                  ),
                );
              },
              child: Hero(
                tag: data.id,
                child: Text(
                  'OK',
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }
}

Details

import 'package:flutter/material.dart';
import './models.dart';

class DetailPage extends StatelessWidget {
  final Name record;
  final int colorIndex;

  const DetailPage({Key? key, required this.record, required this.colorIndex})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    print("Name: "   record.name);
    print("Color: "   colorIndex.toString());

    return Scaffold(
        appBar: AppBar(
          title: const Text(
            'Test',
          ),
        ),
        body: Hero(
          tag: record.id,
          child: Container(
            height: 300,
            color: Colors.primaries[colorIndex][100],
            child: Center(
              child: Text(
                record.name,
              ),
            ),
          ),
        ),
      );
  }
}

CodePudding user response:

We are incrementing colorIndex inside map, and it becomes the last number of the last item on my list after the build, because it is passing reference of colorIndex variable.

To solve this, you can create another variable from loop state inside map and use it on DetailPage.

children: names.map((data) {
      colorIndex < Colors.primaries.length - 1
          ? colorIndex  
          : colorIndex = 0;
      final c = colorIndex; // it will get separate value on each (map)iteration
......

 DetailPage( colorIndex: c, ..)

You can check

  • Related