skip to Main Content

I am learning Flutter and currently am trying to send the index of the list item that is clicked, to another page. I have figured out how to open the new page using GestureDetector but am getting an error when trying to send the index as a string. Here is my code:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView.builder(
      itemCount: totalItems,
      itemBuilder: (context, index) {
        return GestureDetector(
        child: Container( // This is the back container which will show next cell colour on the rounded edge
          color: index == totalItems-1
            ? Colors.transparent
            : colours[(index+1)%2],

        child: Container(
          height: 180,
          decoration: BoxDecoration(
            borderRadius:
            const BorderRadius.only(bottomLeft: Radius.circular(85.0)),
            color: colours[index%2],
          ),
          child: Center(
            child: Text(
              index.toString(),
              style: const TextStyle(color: Colors.white, fontSize: 50),
                ),
              ),
            ),
          ),

          onTap: () => Navigator.push(
              context,
              MaterialPageRoute(
              builder: (context) => const Portfolio(title: 'Portfolio', index: toString(index)),
          )
        );
        },
      )

When trying to send index to the next page as "toString(index)", I am getting an error that states

"A value of type Null can’t be assigned to a parameter of type String
in a const constructor"

When hardcoding a string, the code works. I just don’t understand how index is a type Null here.

Thank you!

2

Answers


  1. I see you’re trying to convert the index to String and then open it the new screen if so the:

    replace:

    toString(index),
    

    with:

    index.toString(),
    
    Login or Signup to reply.
  2. If portfolio page accepts index as:-

    • String: pass index as index.toString()
    • as int : pass index as index

    or you have to remove the const before pushing the page.

    modified code:

    onTap: () => Navigator.push(
                  context,
                  MaterialPageRoute(
                  builder: (context) => Portfolio(title: 'Portfolio', index: index.toString()), // or `index` if type is int in portfolio page
              ));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search