Continuing from previous post, for the part 2 of Flutter tutorials we will learn how to create pages and navigate to them from anywhere in the app.
before anything else, we need to import the `Get`
dependency from flutter packages.
go to https://pub.dev/packages/get and click on the `installing`
tab. copy the latest version to your pubspec.yaml file.
now we need to update our app to use the `Get` GetMaterialApp.
got to `lib/main.dart` and replace the MaterialApp with the GetMaterialApp.
GetMaterialApp(
home: HomePage(),
);
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const HomeScreen(title: 'Home Page'),
);
}
}
under the screens folder, we will create a new file called reddit_page.dart
now we need to add the file to the `lib/screens` folder.
now let’s create a new class called RedditPage.
lib/screens/reddit_page.dart
class RedditPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Reddit'),
),
body: Center(
child: Text('Reddit Page'),
),
);
}
}
go to `lib/home.dart` and update the onTap function to call the `Get.to` function.
onTap: () => Get.to(RedditPage(redditPageName: redditNames[index])),
now if you click on any reddit page, you will be navigated to the RedditPage.
let’s update the `lib/screens/reddit_page.dart` file to show some fake posts.
here we are going to generate a custom flutter page widget where it takes a reddit page name and then builds a list of posts
import 'package:flutter/material.dart';
class RedditPage extends StatelessWidget {
final String redditPageName;
const RedditPage({Key? key, required this.redditPageName}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('r/$redditPageName'),
),
body: Center(
child: ListView.builder(
itemCount: 10,
itemBuilder: (context, index) {
// build a material design card with a title and image in the center
// card should have a title at top and a thumbnail image in the center
return Card(
child: Column(
children: [
ListTile(
title: Text('Post $index'),
subtitle: const Text('subtitle'),
),
Image.network('https://picsum.photos/200/100'),
const SizedBox(height: 10),
],
),
);
},
),
),
);
}
}
in the next part of the tutorial, we will learn how to call the reddit rest api and get the data.
and display them in the page using an infinite list
https://github.com/techprd/reddit_client/tree/feature/Lesson_2