Home > Enterprise >  How do I send data with GestureDetector to another screen in Flutter
How do I send data with GestureDetector to another screen in Flutter

Time:11-18

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!

CodePudding user response:

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

CodePudding user response:

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(),
  • Related