Skip to content

Instantly share code, notes, and snippets.

@PlugFox
Created April 18, 2024 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PlugFox/b533f61bbb0fa1a112dc36ad24361124 to your computer and use it in GitHub Desktop.
Save PlugFox/b533f61bbb0fa1a112dc36ad24361124 to your computer and use it in GitHub Desktop.
Focus example
/*
* Focus example
* https://gist.github.com/PlugFox/b533f61bbb0fa1a112dc36ad24361124
* https://dartpad.dev?id=b533f61bbb0fa1a112dc36ad24361124
* Mike Matiunin <plugfox@gmail.com>, 18 April 2024
*/
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runZonedGuarded<void>(
() => runApp(const App()),
(error, stackTrace) => print('Top level exception: error\nstackTrace'), // ignore: avoid_print
);
class App extends StatefulWidget {
const App({super.key});
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
int? focused;
@override
Widget build(BuildContext context) => MaterialApp(
title: 'Focus example',
home: Scaffold(
appBar: AppBar(
title: const Text('Focus example'),
),
body: SafeArea(
child: Center(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
const Text(
'Press Tab and Shift+Tab to navigate between items',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 16),
SizedBox(
height: 248,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 100,
itemExtent: 216,
padding: const EdgeInsets.all(24),
itemBuilder: (context, index) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: SizedBox.square(
dimension: 200,
child: StatefulBuilder(
builder: (context, setState) => AnimatedScale(
duration: const Duration(milliseconds: 450),
scale: focused == index ? 1 : .9,
child: Material(
elevation: 8,
color: focused == index ? Colors.orange : Colors.grey,
borderRadius: BorderRadius.circular(16),
child: Focus(
canRequestFocus: true,
autofocus: index == focused,
onFocusChange: (hasFocus) => setState(() => focused = index),
child: Center(
child: Text(
'#$index',
style: const TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
),
),
),
),
),
),
),
),
),
],
),
),
),
),
),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment