Flutter custom list widget with item click callback

A custom list widget takes a list of numbers and a callback function for handling list item clicks. my_number_list.dart

import 'package:flutter/material.dart';

class MyNumberList extends StatelessWidget {

  const MyNumberList(this._myNumbers, this._onTap);

  final List _myNumbers;
  final Function(int) _onTap;

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      padding: const EdgeInsets.all(16.0),
      itemCount: _myNumbers.length,
      itemBuilder: (context, index) {

        return ListTile(
          title: Text(
            _myNumbers[index].toString(),
          ),
          onTap: () {
            _onTap(_myNumbers[index]);
          },
        );
      },
    );
  }
}

Using the custom list widget by giving it a list of numbers and a callback function to handle the list item click events. main.dart

import 'dart:math';
import 'package:flutter/material.dart';
import 'my_number_list.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(context) {

    List numbers = List.generate(100, (i) => Random().nextInt(1000));

    onItemPressed(int number) {
      print("$number is pressed");
    }

    return Builder(
        builder: (context) {
          return MaterialApp(
              title: 'Widget with callbacks',
              theme: ThemeData(
                appBarTheme: const AppBarTheme(
                  backgroundColor: Colors.blueAccent,
                  foregroundColor: Colors.black,
                ),
              ),
              home: Scaffold(
                  appBar: AppBar(
                    title: const Text('Widget with callbacks'),
                  ),
                  body: MyNumberList(numbers, onItemPressed)
              )
          );
        }
    );
  }
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search