How to make ListView Builder Ui in flutter with Source Code

To create a beautiful ListView in Flutter that displays a list of books, ListView ui in Flutter – where each row contains an image (loaded using CachedNetworkImage), a title, and a formatted date and time, follow these steps. The CachedNetworkImage package will be used to handle loading and caching images efficiently.

Step-by-Step Guide to Creating a ListView Builder with Cached Network Images

Step 1: Set Up Your Flutter Project

First, make sure you have Flutter installed, and create a new Flutter project:

flutter create listview_example
cd listview_example

Step 2: Add Dependencies

Add the cached_network_image dependency to your pubspec.yaml file to handle image loading and caching:

dependencies:
  flutter:
    sdk: flutter
  cached_network_image: ^3.2.3 # Ensure to check for the latest version

Run flutter pub get to install the new dependency.

Step 3: Implement the ListView in main.dart

Now, let’s modify the lib/main.dart file to implement a ListView.builder with images, titles, and formatted date and time.

import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:intl/intl.dart'; // For date formatting

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,  // Remove debug banner
      title: 'ListView Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ListViewExample(),
    );
  }
}

class ListViewExample extends StatelessWidget {
  final List<Book> books = List.generate(
    10,
    (index) => Book(
      title: 'Book Title ${index + 1}',
      imageUrl: 'https://via.placeholder.com/150', // Placeholder image URL
      dateTime: DateTime.now().subtract(Duration(days: index)), // Dynamic date
    ),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Books List'),
      ),
      body: ListView.builder(
        scrollDirection: Axis.horizontal,  // Set the scroll direction to horizontal
        itemCount: books.length,
        itemBuilder: (context, index) {
          return Container(
            width: 200,  // Set a fixed width for each item
            child: BookListItem(book: books[index]),
          );
        },
      ),
    );
  }
}

class BookListItem extends StatelessWidget {
  final Book book;

  BookListItem({required this.book});

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
      elevation: 4,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      child: ListTile(
        leading: ClipRRect(
          borderRadius: BorderRadius.circular(8.0),
          child: CachedNetworkImage(
            imageUrl: book.imageUrl,
            placeholder: (context, url) => CircularProgressIndicator(),
            errorWidget: (context, url, error) => Icon(Icons.error),
            width: 50,
            height: 50,
            fit: BoxFit.cover,
          ),
        ),
        title: Text(
          book.title,
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        subtitle: Text(
          DateFormat('yyyy-MM-dd – kk:mm').format(book.dateTime), // Format date and time
          style: TextStyle(color: Colors.grey[600]),
        ),
      ),
    );
  }
}

class Book {
  final String title;
  final String imageUrl;
  final DateTime dateTime;

  Book({required this.title, required this.imageUrl, required this.dateTime});
}

Output

Remove background color from here

 body: Container(
        // decoration: BoxDecoration(
        //   gradient: LinearGradient(
        //     colors: [
        //       Colors.blue[200]!,
        //       Colors.blue[600]!
        //     ], // Gradient background
        //     begin: Alignment.topLeft,
        //     end: Alignment.bottomRight,
        //   ),
        // ),

Explanation of the Code

  1. Dependencies:
  • We use cached_network_image to load and cache images efficiently.
  • intl is used for formatting the date and time.
  1. Data Model (Book Class):
  • The Book class represents a book with a title, an image URL, and a DateTime object.
  1. Sample Data:
  • A list of Book objects is generated dynamically with different dates and titles.
  1. ListView Implementation:
  • The ListView.builder widget creates a scrollable list of BookListItem widgets. Each BookListItem represents a row in the list. ListView ui in Flutter with source code.
  1. Custom ListTile (BookListItem):
  • Card Widget: Used to give each row a card-like appearance with rounded corners and elevation.
  • ListTile Widget: Displays the book image (leading), title (title), and formatted date and time (subtitle).
  • CachedNetworkImage Widget: Displays the book cover image. It shows a loading indicator while the image is loading and an error icon if the image fails to load.
  1. Date Formatting:
  • The date and time are formatted using DateFormat('yyyy-MM-dd – kk:mm') to create a readable string. ListView ui in Flutter

Step-by-Step Guide to Run the App

  1. Save the Code: Ensure you save your changes to main.dart.
  2. Run the App: Use the following command to run the app on a connected device or emulator:
   flutter run

What to Expect

When you run the app, you will see a list of books displayed using a ListView. Each row shows:

  • An image (loaded and cached from the network).
  • The book title in bold.
  • The date and time formatted nicely in grey text.

The rows have a card-like appearance with rounded corners and a shadow effect to enhance the UI.

Customization Tips

  • Change the Image URL: Replace the placeholder URL with actual URLs to display real book covers.
  • Customize the Date Format: Modify the DateFormat string to change how dates and times are displayed.
  • Styling: You can further customize the TextStyle for titles and subtitles to match your design needs.

Related Articles

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top