Neesh
Neesh

Reputation: 145

"Expected an Identifier" and "Expected to find ')'" for-each errors in Flutter

I am getting "Expected an Identifier" and "Expected to find ')'" errors in my code while using a for-each loop in flutter, here is the code at the loop

body: ListView(
      for(String item in groceryListNames){
        ListTile(
          title: "$item",    
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => GroceryListPage()),
            );
          },
        ),
      },
    ),

Basically, it's supposed to open a new page from a function called GroceryListPage() when pressing the items in the loop, but the loop is giving me the errors above. Here is the entire function:

class _ListsPageState extends State<ListsPage>with SingleTickerProviderStateMixin {
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text("Grocery Lists")),
        drawer: AppDrawer(),
        body: ListView(
          for(String item in groceryListNames){
            ListTile(
              title: "$item",
              
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => GroceryListPage()),
                );
              },
            ),
          },
        ),
    );
  }

}

Upvotes: 1

Views: 24840

Answers (2)

AskNilesh
AskNilesh

Reputation: 69724

First issue in your code

The AppBar widgets title property required a Widgets why you are providing a string

Second issue

To get click event of ListTile you need to use onTap: () {} method There is no method name onPressed () in ListTile widgets

Try this way

 Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Grocery Lists")
      ),
      drawer: AppDrawer(),
      body: ListView(
        children: groceryListNames
            .map(
              (data) => ListTile(
                title: Text("$data"),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => GroceryListPage()),
                  );
                },
              ),
            )
            .toList(),
      ),
    );
  }

Upvotes: 1

lrn
lrn

Reputation: 71828

The error message most likely comes from the code:

ListView(
      for(String item in groceryListNames){

A for statement cannot occur as a parameter of a function (and the ListView constructor does not take any positional parameters at all).

You might want:

ListView( 
  children: [for (String item in groceryListNames) ListTile(
     ....
  )]

Upvotes: 1

Related Questions