Flutter custom widget with callback function parameter
Here is a custom widget that takes 2 parameters, a list of integers and a callback function. The integer list is the data to be displayed by this custom widget, the callback function is invoked when the list item is being tapped, it passes the integer value to the callback function, the parent widget will be able to receive this integer value when this callback function is being invoked. 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 widget.
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) { Listnumbers = 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
Related Posts