SET 5 – Navigation and Routing SET 9 – REST API Integration 1 SET 5 – Navigation and Routing Program 5(a) · Program 5(b) SET 9 – REST API Integration Program 9(a) · Program 9(b) 5(a) Home and Order Details Screens 5(b) Named Routes 9(a) Fetch and Display Posts from REST API 9(b) Refresh Posts and View Post Details SET 5 – Navigation and Routing SET 9 – REST API Integration 2 SET 5 – Navigation and Routing Program 5(a): Home and Order Details Screens 1. Aim Create Home and Order Details screens. Pass the order ID and total amount using Navigator.push(). 2. Description This program demonstrates how to navigate between two screens and pass data in Flutter. The Home screen contains two text fields to enter the Order ID and Total Amount. When the user clicks the View Order button, Navigator.push() opens the Order Details screen. MaterialPageRoute is used to create the second screen. The entered order ID and total amount are passed through the constructor of the Order Details screen. The second screen displays the received information. The Back button uses Navigator.pop() to return to the Home screen. 3. Program main.dart main.dart 1 import 'package:flutter/material.dart'; 2 3 void main() { 4 runApp(MaterialApp(home: HomePage())); 5 } 6 7 class HomePage extends StatelessWidget { 8 final id = TextEditingController(); 9 final amount = TextEditingController(); 10 11 @override 12 Widget build(BuildContext context) { 13 return Scaffold( 14 appBar: AppBar(title: Text('Home')), 15 body: Padding( 16 padding: EdgeInsets.all(20), 17 child: Column( 18 children: [ 19 TextField( 20 controller: id, 21 decoration: InputDecoration(labelText: 'Order ID'), 22 ), 23 TextField( 24 controller: amount, 25 decoration: InputDecoration(labelText: 'Total Amount'), 26 keyboardType: TextInputType.number, 27 ), 28 ElevatedButton( 29 child: Text('View Order'), 30 onPressed: () { 31 Navigator.push( 32 context, 33 MaterialPageRoute( 34 builder: (context) => OrderPage( SET 5 – Navigation and Routing SET 9 – REST API Integration 3 main.dart 35 id: id.text, 36 amount: amount.text, 37 ), 38 ), 39 ); 40 }, 41 ), 42 ], 43 ), 44 ), 45 ); 46 } 47 } 48 49 class OrderPage extends StatelessWidget { 50 final String id, amount; 51 52 OrderPage({required this.id, required this.amount}); 53 54 @override 55 Widget build(BuildContext context) { 56 return Scaffold( 57 appBar: AppBar(title: Text('Order Details')), 58 body: Center( 59 child: Column( 60 mainAxisAlignment: MainAxisAlignment.center, 61 children: [ 62 Text('Order ID: $id'), 63 Text('Total Amount: Rs. $amount'), 64 ElevatedButton( 65 onPressed: () => Navigator.pop(context), 66 child: Text('Back'), 67 ), 68 ], 69 ), 70 ), 71 ); 72 } 73 } 4. Expected Output Screen 1 – Home Home Order ID 101 Total Amount 1500 View Order Screen 2 – Order Details Order Details Order ID: 101 Total Amount: Rs. 1500 Back SET 5 – Navigation and Routing SET 9 – REST API Integration 4 9:41 Home Order ID 101 Total Amount 1500 View Order Screen 1 – Home 9:41 Order Details Order ID: 101 Total Amount: Rs. 1500 Back Screen 2 – Order Details Program 5(b): Named Routes 1. Aim Configure named routes for Home, Orders and Help screens and demonstrate navigation and returning to the previous screen. 2. Description This program demonstrates navigation between multiple screens using named routes. Three screens are created: Home, Orders and Help. Their route names are registered inside the routes property of MaterialApp. The Home screen contains two buttons: Orders and Help. Navigator.pushNamed() is used to open the respective screens using their route names. A common SimplePage widget is used for both Orders and Help screens, reducing duplicate code. Each screen contains a Back button. Navigator.pop() returns the user to the previous screen. 3. Program main.dart SET 5 – Navigation and Routing SET 9 – REST API Integration 5 main.dart 1 import 'package:flutter/material.dart'; 2 3 void main() { 4 runApp(MaterialApp( 5 initialRoute: '/', 6 routes: { 7 '/': (context) => HomePage(), 8 '/orders': (context) => SimplePage('Orders'), 9 '/help': (context) => SimplePage('Help'), 10 }, 11 )); 12 } 13 14 class HomePage extends StatelessWidget { 15 @override 16 Widget build(BuildContext context) { 17 return Scaffold( 18 appBar: AppBar(title: Text('Home')), 19 body: Center( 20 child: Column( 21 mainAxisAlignment: MainAxisAlignment.center, 22 children: [ 23 ElevatedButton( 24 onPressed: () => 25 Navigator.pushNamed(context, '/orders'), 26 child: Text('Orders'), 27 ), 28 ElevatedButton( 29 onPressed: () => 30 Navigator.pushNamed(context, '/help'), 31 child: Text('Help'), 32 ), 33 ], 34 ), 35 ), 36 ); 37 } 38 } 39 40 class SimplePage extends StatelessWidget { 41 final String title; 42 43 SimplePage(this.title); 44 45 @override 46 Widget build(BuildContext context) { 47 return Scaffold( 48 appBar: AppBar(title: Text(title)), 49 body: Center( 50 child: ElevatedButton( 51 onPressed: () => Navigator.pop(context), 52 child: Text('Back to Home'), 53 ), 54 ), 55 ); 56 } 57 } SET 5 – Navigation and Routing SET 9 – REST API Integration 6 4. Expected Output Screen 1 – Home Home Orders Help Screen 2 – Orders Orders Orders Screen Back to Home Screen 3 – Help Help Help Screen Back to Home 9:41 Home Orders Help Screen 1 – Home 9:41 Orders Orders Screen Back to Home Screen 2 – Orders 9:41 Help Help Screen Back to Home Screen 3 – Help SET 5 – Navigation and Routing SET 9 – REST API Integration 7 SET 9 – REST API Integration Before running Set 9 programs Add the HTTP package to your Flutter project's pubspec.yaml : pubspec.yaml pubspec.yaml 1 dependencies: 2 flutter: 3 sdk: flutter 4 http: ^1.2.2 Run this command: flutter pub get The API we will use is: DummyJSON – Life Posts API https://dummyjson.com/posts/tag/life?utm_source=chatgpt.com It returns a list of posts with title and body fields. The program reads these fields directly from the API response. No post titles or descriptions are manually entered in the code. DummyJSON Program 9(a): Fetch and Display Posts from REST API 1. Aim Fetch posts from a public REST API and display the post title and body in a scrollable ListView with loading and error handling. 2. Description This program demonstrates how to fetch post information from a public REST API and display it in a Flutter application. The HTTP package is used to send a GET request to the API. The server returns post information in JSON format. The jsonDecode() function converts the JSON response into Dart data. The fetchPosts() function uses async and await to perform the API request. It also checks the response status code. If the request is successful, the list of posts is returned. Otherwise, an exception is generated. The FutureBuilder widget handles the API response states. It displays a CircularProgressIndicator while data is loading, an error message if the request fails, and a suitable message if the API returns empty data. Finally, ListView.builder displays the fetched post titles and bodies in a scrollable list using ListTile widgets. SET 5 – Navigation and Routing SET 9 – REST API Integration 8 3. Program main.dart main.dart 1 import 'dart:convert'; 2 import 'package:flutter/material.dart'; 3 import 'package:http/http.dart' as http; 4 5 void main() { 6 runApp(MaterialApp(home: PostsPage())); 7 } 8 9 class PostsPage extends StatefulWidget { 10 @override 11 State<PostsPage> createState() => _PostsPageState(); 12 } 13 14 class _PostsPageState extends State<PostsPage> { 15 late Future<List<dynamic>> posts; 16 17 Future<List<dynamic>> fetchPosts() async { 18 final res = await http.get(Uri.parse( 19 'https://dummyjson.com/posts/tag/life')); 20 21 if (res.statusCode == 200) { 22 return jsonDecode(res.body)['posts']; 23 } 24 throw Exception('Failed to load posts'); 25 } 26 27 @override 28 void initState() { 29 super.initState(); 30 posts = fetchPosts(); 31 } 32 33 @override 34 Widget build(BuildContext context) { 35 return Scaffold( 36 appBar: AppBar(title: Text('Blog Posts')), 37 body: FutureBuilder( 38 future: posts, 39 builder: (context, snapshot) { 40 if (snapshot.connectionState == ConnectionState.waiting) 41 return Center(child: CircularProgressIndicator()); 42 43 if (snapshot.hasError) 44 return Center(child: Text('Error loading posts')); 45 46 if (!snapshot.hasData || snapshot.data!.isEmpty) 47 return Center(child: Text('No posts available')); 48 49 return ListView.builder( 50 itemCount: snapshot.data!.length, 51 itemBuilder: (context, index) { 52 final post = snapshot.data![index]; 53 54 return ListTile( 55 title: Text(post['title']), 56 subtitle: Text(post['body']), 57 ); 58 }, 59 ); 60 }, 61 ), 62 ); 63 } 64 } SET 5 – Navigation and Routing SET 9 – REST API Integration 9 4. Expected Output Output 1 – Loading Screen Blog Posts Loading... Output 2 – Successful Response Blog Posts The forest was alive with the sounds of nature Birds sang, leaves rustled, and a gentle stream trickled nearby... The market was a bustling maze of sights and sounds Stalls filled with colorful produce, the air rich with the scent of spices... Example content from the API's life-tagged posts. Output 3 – Error Screen Blog Posts Error loading posts 9:41 Blog Posts Loading... Output 1 – Loading Screen 9:41 Blog Posts The forest was alive with the sounds of nature Birds sang, leaves rustled, and a gentle stream trickled nearby... The market was a bustling maze of sights and sounds Stalls filled with colorful produce, the air rich with the scent of spices... Output 2 – Successful Response 9:41 Blog Posts Error loading posts Output 3 – Error Screen Program 9(b): Refresh Posts and View Post Details 1. Aim Add a refresh action and open a details view to display the full content of a selected post. 2. Description This program extends the REST API application by adding a refresh option and a separate details screen. SET 5 – Navigation and Routing SET 9 – REST API Integration 10 The application sends an HTTP GET request to the public API and retrieves the list of posts. The response is converted from JSON into Dart data using jsonDecode() The FutureBuilder widget manages the loading, error, empty and successful response states. The ListView.builder displays the fetched posts with their titles and body content. An IconButton with a refresh icon is added to the AppBar. When the user clicks it, the refreshPosts() function calls setState() and fetches the latest response again. When the user taps a particular post, Navigator.push() opens a new Details screen. The selected post is passed through the constructor, and the Details screen displays its complete title and body. 3. Program main.dart main.dart 1 import 'dart:convert'; 2 import 'package:flutter/material.dart'; 3 import 'package:http/http.dart' as http; 4 5 void main() { 6 runApp(MaterialApp(home: PostsPage())); 7 } 8 9 class PostsPage extends StatefulWidget { 10 @override 11 State<PostsPage> createState() => _PostsPageState(); 12 } 13 14 class _PostsPageState extends State<PostsPage> { 15 late Future<List<dynamic>> posts; 16 17 Future<List<dynamic>> fetchPosts() async { 18 final res = await http.get(Uri.parse( 19 'https://dummyjson.com/posts/tag/life')); 20 21 if (res.statusCode == 200) 22 return jsonDecode(res.body)['posts']; 23 24 throw Exception('Failed to load posts'); 25 } 26 27 void refreshPosts() { 28 setState(() { 29 posts = fetchPosts(); 30 }); 31 } 32 33 @override 34 void initState() { 35 super.initState(); 36 posts = fetchPosts(); 37 } 38 39 @override 40 Widget build(BuildContext context) { 41 return Scaffold( 42 appBar: AppBar( 43 title: Text('Blog Posts'), 44 actions: [ 45 IconButton( 46 icon: Icon(Icons.refresh), 47 onPressed: refreshPosts, 48 ), 49 ], 50 ), SET 5 – Navigation and Routing SET 9 – REST API Integration 11 main.dart 51 body: FutureBuilder( 52 future: posts, 53 builder: (context, snapshot) { 54 if (snapshot.connectionState == ConnectionState.waiting) 55 return Center(child: CircularProgressIndicator()); 56 57 if (snapshot.hasError) 58 return Center(child: Text('Error loading posts')); 59 60 if (!snapshot.hasData || snapshot.data!.isEmpty) 61 return Center(child: Text('No posts available')); 62 63 return ListView.builder( 64 itemCount: snapshot.data!.length, 65 itemBuilder: (context, index) { 66 final post = snapshot.data![index]; 67 68 return ListTile( 69 title: Text(post['title']), 70 subtitle: Text(post['body']), 71 onTap: () { 72 Navigator.push( 73 context, 74 MaterialPageRoute( 75 builder: (context) => DetailPage(post), 76 ), 77 ); 78 }, 79 ); 80 }, 81 ); 82 }, 83 ), 84 ); 85 } 86 } 87 88 class DetailPage extends StatelessWidget { 89 final dynamic post; 90 91 DetailPage(this.post); 92 93 @override 94 Widget build(BuildContext context) { 95 return Scaffold( 96 appBar: AppBar(title: Text('Post Details')), 97 body: Padding( 98 padding: EdgeInsets.all(16), 99 child: Column( 100 crossAxisAlignment: CrossAxisAlignment.start, 101 children: [ 102 Text(post['title'], 103 style: TextStyle(fontSize: 20, 104 fontWeight: FontWeight.bold)), 105 SizedBox(height: 15), 106 Text(post['body']), 107 ], 108 ), 109 ), 110 ); 111 } 112 } SET 5 – Navigation and Routing SET 9 – REST API Integration 12 4. Expected Output Screen 1 – Blog Posts with Refresh Blog Posts The forest was alive with the sounds of nature Birds sang, leaves rustled, and a gentle stream trickled nearby... The market was a bustling maze of sights and sounds Stalls filled with colorful produce... Tap the refresh icon to fetch again. Tap a post to view details. Screen 2 – Post Details Post Details The forest was alive with the sounds of nature Birds sang, leaves rustled, and a gentle stream trickled nearby. It was a symphony of life, a reminder of the world's beauty. 9:41 Blog Posts The forest was alive with the sounds of nature Birds sang, leaves rustled, and a gentle stream trickled nearby... The market was a bustling maze of sights and sounds Stalls filled with colorful produce... Screen 1 – Blog Posts with Refresh 9:41 Post Details The forest was alive with the sounds of nature Birds sang, leaves rustled, and a gentle stream trickled nearby. It was a symphony of life, a reminder of the world's beauty. Screen 2 – Post Details