Skip to main content

How To Create Live Cricket Match App In Flutter (Last Part)

 




Step 6: Navigate to a match details screen

Next, let's set up a way for the user to navigate to a screen with more details about a specific cricket match. Create a new file called match_details_screen.dart and add the following code to it:

import 'package:flutter/material.dart'; import 'api.dart'; class MatchDetailsScreen extends StatefulWidget { final String matchId; MatchDetailsScreen({required this.matchId}); @override _MatchDetailsScreenState createState() => _MatchDetailsScreenState(); } class _MatchDetailsScreenState extends State<MatchDetailsScreen> { Map _matchDetails = {}; @override void initState() { super.initState(); _getMatchDetails(); } Future<void> _getMatchDetails() async { final data = await Api.get('cricketScore?unique_id=${widget.matchId}'); setState(() { _matchDetails = data; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Match Details'), ), body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Container( padding: EdgeInsets.all(16), color: Colors.grey[300], child: Text( _matchDetails['team-1'] + ' vs ' + _matchDetails['team-2'], style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), ), Container( padding: EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( 'Score: ${_matchDetails['score']}',

style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), SizedBox(height: 16), Text( 'Status: ${_matchDetails['stat']}', style: TextStyle(fontSize: 16), ), SizedBox(height: 16), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Column( children: [ Text( _matchDetails['team-1'], style: TextStyle(fontWeight: FontWeight.bold), ), SizedBox(height: 8), Image.network( 'https://www.countryflags.io/${_matchDetails['team-1-abbreviation']}/flat/64.png', width: 50, ), ], ), Column( children: [ Text( 'vs', style: TextStyle(fontSize: 16), ), SizedBox(height: 8), Text( _matchDetails['team-2'], style: TextStyle(fontWeight: FontWeight.bold), ), SizedBox(height: 8), Image.network( 'https://www.countryflags.io/${_matchDetails['team-2-abbreviation']}/flat/64.png', width: 50, ), ], ), ], ), SizedBox(height: 16), Text( 'Cricbuzz Commentary', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), SizedBox(height: 16), if (_matchDetails['scorecard'] != null) Column( children: _matchDetails['scorecard'].map<Widget>((card) { return Padding( padding: EdgeInsets.only(bottom: 8), child: Row( children: [ Expanded( child: Text( card['title'], style: TextStyle(fontWeight: FontWeight.bold), ), ), Expanded( child: Text( card['value'], textAlign: TextAlign.right, ), ), ], ), ); }).toList(), ), ], ), ), ], ), ), ); } }

This code sets up a `MatchDetailsScreen` widget that displays detailed information about a cricket match, including the teams involved, the current score, and live commentary. The `matchId` argument is used to fetch the specific match details from the CricAPI.

Step 7: Add navigation between screens

Now that we have both a `HomeScreen` and a `MatchDetailsScreen`, we need a way for the user to navigate between them. Update the `ListView.builder` in `home_screen.dart` to include a `GestureDetector` that navigates to the `MatchDetailsScreen` when a match is tapped:

```dart
ListView.builder(
  itemCount: _matches.length,
  itemBuilder: (BuildContext context, int index) {
    final match = _matches[index];

    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => MatchDetailsScreen(matchId: match['unique_id']),
          ),
        );
      },
      child: ListTile(
        leading: SvgPicture.asset(
          'assets/icons/cricket-ball.svg',
          width: 30,
          color: Colors.green,
        ),
        title: Text(match['team-1'] + ' vs ' + match['team-2']),
        subtitle: Text(match['type']),
        trailing: CachedNetworkImage(
          imageUrl: 'https://www.countryflags.io/${match['team-1-abbreviation']}/flat/64.png',
          width: 40,
        ),
      ),
    );
  },
),
This code adds a GestureDetector with an onTap property to each ListTile. When a match is tapped, it creates a new MatchDetailsScreen with the matchId argument set to the corresponding match's unique ID and navigates to it using the Navigator.push method.

Step 8: Test the app

Now that we have a fully functioning live cricket match app, it's time to test it out! To run the app on an emulator or physical device, run the following command in your terminal:

flutter run

This command will build and run the app on the default device or emulator. If you have multiple devices or emulators connected, you can specify which one to use by running flutter run -d <device ID>.

Once the app is running, you should see a list of live cricket matches on the home screen. Tapping on a match should take you to the MatchDetailsScreen where you can view detailed information about the match, including the current score and live commentary.

Conclusion

In this tutorial, we learned how to create a live cricket match app using Flutter and the CricAPI. We started by setting up a new Flutter project and adding dependencies for networking, caching, and SVG rendering. We then created a HomeScreen widget that fetches live cricket match data from the CricAPI and displays it in a list. Finally, we created a MatchDetailsScreen widget that displays detailed information about a specific cricket match and added navigation between the two screens.

With the knowledge gained from this tutorial, you can apply similar techniques to create apps that display live data for other sports, news, weather, and more. Happy coding!

Comments

Popular posts from this blog

Java Code For Calculator With Switch Statement

Welcome to this blog on how to create a calculator in Java using text instructions! In this blog, we'll go through the steps of creating a simple calculator program that can perform basic arithmetic operations. Before we start, let's discuss what a calculator program is and what it does. A calculator program is a software application that performs mathematical calculations. It typically has a graphical user interface (GUI) that allows users to enter numbers and perform various arithmetic operations, such as addition, subtraction, multiplication, and division. In this tutorial, however, we will be creating a simple calculator program using only text instructions. This means that we will not be using a GUI or any visual elements to create our calculator. Instead, we will use the Java programming language to write code that performs the necessary calculations. Here are the steps to create a calculator in Java using text instructions: Step 1: Define the Problem Before we st...

How to Troubleshoot Common Errors in Java Programming: A Comprehensive Guide

How to Troubleshoot Common Errors in Java Programming: A Comprehensive Guide  Introduction: Millions of developers use Java, one of the most widely used programming languages in the world, to build robust and dynamic applications. Java is, however, prone to mistakes, just like any other programming language, which can frustrate developers and give them headaches. Whether you're a novice or a seasoned developer, it's critical to understand how to fix typical Java programming problems. We'll go through how to spot, diagnose, and correct some of the most typical Java programming issues in this book.  Understanding Common Errors in Java Programming Prior to getting started with debugging, it's crucial to understand the typical mistakes that might happen when developing in Java. The most frequent mistakes that you could run across are listed below: Syntax errors: These occur when you make a mistake in your code, such as missing a semicolon or using incorrect syntax. Runtime...

Manual for the Best JavaScript Books for Fledglings

  JavaScript JavaScript is a programming language that is widely used in web development. According to a recent survey of 90,000 individuals, it was the most commonly used programming language for 70% of respondents. This is not surprising given that it forms the foundation of all interactive web pages, is easy to learn, has numerous applications beyond the internet, and supports various programming styles such as basic, object-oriented, and functional. JavaScript allows developers to add dynamic and interactive elements to their websites, making them more engaging and user-friendly. It is used to create everything from simple dropdown menus and image sliders to complex web applications and games. Some of the most popular websites in the world, such as Facebook and Google, rely heavily on JavaScript to provide a smooth and seamless user experience. For beginners interested in learning JavaScript, it is recommended to also learn HTML and CSS, which are the other standard web...