Created
August 28, 2023 20:46
-
-
Save Luckey-Elijah/daab8aaf8c7a9879031f32f21c82a53c to your computer and use it in GitHub Desktop.
discord-like-commands
This file contains 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(const MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: ThemeData(useMaterial3: true), | |
home: const Example(), | |
); | |
} | |
} | |
class Example extends StatefulWidget { | |
const Example({super.key}); | |
@override | |
State<Example> createState() => _ExampleState(); | |
} | |
class _ExampleState extends State<Example> { | |
final availableCommands = const { | |
'/ban', | |
'/softban', | |
'/kick', | |
'/mute', | |
'/addrole', | |
'/delrole', | |
'/role', | |
}; | |
final controller = SearchController(); | |
@override | |
void initState() { | |
super.initState(); | |
controller.addListener(_searchControllerListener); | |
} | |
void _searchControllerListener() { | |
if (controller.isOpen && controller.text.isEmpty) { | |
return controller.closeView(null); | |
} | |
for (final command in availableCommands) { | |
if (command == controller.text) { | |
if (!controller.isOpen) return; | |
return controller.closeView(null); | |
} | |
if (command.startsWith(controller.text)) { | |
if (controller.isOpen) return; | |
return controller.openView(); | |
} | |
} | |
} | |
@override | |
void dispose() { | |
controller.removeListener(_searchControllerListener); | |
super.dispose(); | |
} | |
String body = ''; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Center( | |
child: Column( | |
children: [ | |
SearchAnchor( | |
searchController: controller, | |
builder: (context, controller) { | |
return SearchBar( | |
controller: controller, | |
elevation: MaterialStateProperty.all(12), | |
); | |
}, | |
suggestionsBuilder: (_, controller) { | |
return availableCommands | |
.where((cmd) => cmd.startsWith(controller.text)) | |
.map( | |
(command) => ListTile( | |
title: Text(command), | |
onTap: () => controller.closeView(command), | |
), | |
); | |
}, | |
), | |
Expanded(child: Center(child: Text(body))), | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment