MaterialPageRoute
- Flutter course
- Beginner
- Lesson 88/99
- 4 min
Build Material transition with MaterialPageRoute.
What is MaterialPageRoute?
MaterialPageRoute is a route class that provides a Material design transition animation. Its builder parameter takes a function that builds the screen to open. On Android it slides up from below, and on iOS it slides in from the right.
MaterialPageRoute(
builder: (context) => SecondScreen(),
)The builder parameter
builder is a callback function that takes a BuildContext parameter and returns a Widget. MaterialPageRoute calls this function to build the new screen. The parameter name is usually written as _ since it is not used; but context can also be given if desired.
Practice Make a transition with MaterialPageRoute
Write a function gecis that prints Gecis yapildi. In main call gecis. Add an ElevatedButton whose onPressed uses MaterialPageRoute to open a Scaffold screen.
Starter code
import 'package:flutter/material.dart';
// gecis fonksiyonu yaz: "Gecis yapildi" yazdirsin
void main() {
// gecis'i cagir
runApp(const Uygulama());
}
class Uygulama extends StatelessWidget {
const Uygulama({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
// ElevatedButton ekle
child: SizedBox(),
),
),
);
}
}Sample solution
import 'package:flutter/material.dart';
void gecis() {
print('Gecis yapildi');
}
void main() {
gecis();
runApp(const Uygulama());
}
class Uygulama extends StatelessWidget {
const Uygulama({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (_) => Scaffold()),
);
},
child: Text('Gecis'),
),
),
),
);
}
}Expected output
Gecis yapildi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the builder parameter of MaterialPageRoute return?
- int
- bool
- String
- Widget Correct answer
Explanation: The builder parameter is a callback function that returns a Widget; it does not return String, int or bool.
2 Add the builder parameter
MaterialPageRoute(
____: (_) => Scaffold(),
)
MaterialPageRoute(
builder: (_) => Scaffold(),
)
Explanation: The parameter of MaterialPageRoute that builds the screen is builder; child, widget or screen are not valid parameter names.
3 MaterialPageRoute parts
| Term | Meaning |
|---|---|
MaterialPageRoute |
Material transition route |
builder |
Callback that builds the screen |
transition |
Transition animation |
Navigator |
Calls the route |