Flutter code executed before button clicked
This code passes a function to onPressed
that is executed when the button is pressed
onPressed: () => openBook(url)
Your code
onPressed: openBook(url)
executes openBook(url)
and passed the result to onPressed
to be executed on button press, which doesn't seem to be what you want.
BoA
Updated on December 04, 2022Comments
-
BoA over 1 year
I have a ListTile (in the drawer), which when clicked, goes to a new screen and in that screen the user can choose from a number of (using a for loop) IconButtons (which are in a ListView), but the function which is to be executed when one taps the button is actually executed when the user is sent to the choosing screen (when he/she clicked the ListTile) and as a result the function (which by the way opens another screen) gets executed the same amount of times as there are IconButtons in my ListView and before they are clicked.
For more details see the sourcecode:
When the ListTile is clicked:
setState(() { goDownloads(files); });
Function for opening to the new screen:
goDownloads(List<File> files) async { for (int n = 0; n < files.length; n++) { String url = files[n].path; Widget container = new Container( child: new Row( children: <Widget>[ new IconButton( onPressed: openBook(url),//This is the code that gets executed before it's supposed to icon: new Icon(Icons.open_in_browser), ), ... ] ) ); dlbooks.add(container); } setState(() { Navigator.of(context).push(new MaterialPageRoute<Null>( builder: (BuildContext context) { return new Scaffold( appBar: new AppBar(title: new Text('My Page')), body: new Center( child: new ListView( children: dlbooks ), ), ); }, )); }); }
I also have the full code in a main.dart file, though I don't recommend it since it's not well written, I'm still a noob. https://pastebin.com/vZapvCKx Thanks in advance!
-
BoA about 6 yearsThank you very much for the great and quick answer, it's working perfectly now. I still have to practice this dart syntax a little it seems.
-
Günter Zöchbauer about 6 yearsWhat might add to the confusion is, that often the form
onPressed: openBook
is used, which is equivalent short form foronPressed: () => openBook()
which can always used when the parameters in(...) =>
andopenBook(...)
match exactly.