Created
February 29, 2024 07:46
-
-
Save asartalo/215f8d78403a95cda28c88644c7d5f25 to your computer and use it in GitHub Desktop.
Workaround for Flutter ListView and MenuAnchor focus interaction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class Task { | |
final String name; | |
final int id; | |
const Task(this.id, this.name); | |
} | |
final tasks = [ | |
const Task(1, 'First Task'), | |
const Task(2, 'Second Task'), | |
const Task(3, 'Third Task'), | |
const Task(4, 'Fourth Task'), | |
]; | |
final menuItems = [ | |
'Something Something', | |
'Edit Task', | |
'Delete Task', | |
]; | |
class MyApp extends StatelessWidget { | |
MyApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
debugShowCheckedModeBanner: false, | |
home: ListView.builder( | |
itemCount: tasks.length, | |
itemBuilder: (context, index) { | |
final task = tasks[index]; | |
final focusNode = FocusNode(); | |
return Material( | |
key: Key(task.id.toString()), | |
type: MaterialType.transparency, | |
child: ListTile( | |
title: Text(task.name), | |
onTap: () async {}, | |
focusNode: focusNode, | |
trailing: MenuAnchor( | |
onClose: () { | |
focusNode.unfocus(); | |
}, | |
menuChildren: menuItems | |
.map( | |
(item) => MenuItemButton( | |
child: Text(item), | |
onPressed: () {}, | |
), | |
) | |
.toList(), | |
builder: (context, controller, child) => IconButton( | |
icon: const Icon(Icons.more_vert), | |
onPressed: () { | |
if (controller.isOpen) { | |
controller.close(); | |
} else { | |
controller.open(); | |
} | |
}, | |
), | |
), | |
), | |
); | |
}, | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment