It’s time for a challenge on Flutter widget creation. Currently, we have a an app that has lots of different domains. It’d be nice for the user to navigate to a filter page and to filter out all the courses.
Flutter is all about creating widgets so this is a prime opportunity to test out your widget creation skills. Your challenge is to pause the video, and create a StatefulWidget FilterPage, and then customize it.
So here’s what I want you to do. First, put this filter page in the ui folder in a folder called filter. Next, create a file called filter_page.dart. In that file, The FilterPage StatefulWidget should have a Scaffold and AppBar. The app bar’s title should have a Text widget that uses our filter string from strings.dart. The body should just have a text widget that reads, ‘Filter Page’.
Now that’s a big order. But if you’ve followed along so far, I know you can do it. Once I review the answer, we’ll add the ability to navigate to it. Pause the video, and give it your best shot.
Okay, how did your challenge go. Don’t worry if you got stuck. That’s part of the process. But hey, if you managed to get it, well done. Let’s go through it now together.
Create a new folder called filter in the ui folder. Then create a new file called filter_page.dart. With the file open, create a new stateful widget by typing ST and selecting stateful widget. Give it the name FilterPage.
class FilterPage extends StatefulWidget {
const FilterPage({ Key? key }) : super(key: key);
@override
_FilterPageState createState() => _FilterPageState();
}
class _FilterPageState extends State<FilterPage> {
@override
Widget build(BuildContext context) {
return Container(
);
}
}
Next, select the StatefulWidget and press command-. on macOS or Control-. on windows. Import the material library. Now for the State Class. Update the build method to the following.
class _FilterPageState extends State<FilterPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(Strings.filter),
),
body: const Text('Filter'),
);
}
}
Make sure to import Strings.dart.
import '../../strings.dart';
And that’s it. That was the challenge. Now that we have our page, let’s call it. Open up rwcourses_app.dart. We will add an action to the AppBar. We’ll make a button, providing an icon and then we’ll trigger the navigation from the onPressed property.
appBar: AppBar(
title: Text(Strings.appTitle),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.filter_list),
onPressed: () => Navigator.of(context).push<MaterialPageRoute>(
MaterialPageRoute(builder: (_) => const FilterPage())),
)
],
),
And of course, import the FilterPage
import 'ui/filter/filter_page.dart';
Now build and run or hot reload the app. You’ll see the filter button and when you tap it, you’ll be taken to the filter page. Nice work!