Functions With Parameters
Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 7 of 34.
A function can take a value each time you call it. That value is a parameter, written in the parentheses with its type:
void greet(String name) {
print('Hi, $name!');
}
greet('Ada'); // Hi, Ada!
greet('Linus'); // Hi, Linus!Inside the function, name is a variable holding whatever was passed in. One function now does the work of many.
A button cannot pass a value by itself: onPressed: wants a function with no parameters. So wrap the call in a small function with no name, the kind you met in Your First Button:
ElevatedButton(
onPressed: () { greet('Ada'); },
child: Text('Ada'),
)Challenge
EasyReplace orderTea with one function order that takes a String drink and prints One Tea, please, One Coffee, please or One Juice, please. Make all three buttons use it.
Try it yourself
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
void orderTea() {
print('One Tea, please');
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton(onPressed: orderTea, child: Text('Tea')),
SizedBox(height: 12),
ElevatedButton(onPressed: () {}, child: Text('Coffee')),
SizedBox(height: 12),
ElevatedButton(onPressed: () {}, child: Text('Juice')),
],
),
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Making It Interactive
Practice on your own: Online Flutter compiler