Last active
January 21, 2024 17:08
-
-
Save magicleon94/f93aca95dea818650719209e9025f9d4 to your computer and use it in GitHub Desktop.
Flutter hooks playground
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 'dart:math'; | |
import 'package:flutter/material.dart'; | |
import 'package:flutter_hooks/flutter_hooks.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: Scaffold( | |
appBar: AppBar(), | |
body: Column( | |
crossAxisAlignment: CrossAxisAlignment.center, | |
children: [ | |
Text('Ciao'), | |
Expanded(child: Home()), | |
], | |
), | |
), | |
); | |
} | |
} | |
class Home extends StatefulHookWidget { | |
@override | |
_HomeState createState() => _HomeState(); | |
} | |
class _HomeState extends State<Home> { | |
var previousPage = 0; | |
@override | |
Widget build(BuildContext context) { | |
print('Building Home'); | |
final pageController = usePageController(viewportFraction: 0.9); | |
// ignore: close_sinks | |
final rotationController = useStreamController<double>(); | |
useEffect(() { | |
void _callback() { | |
if (pageController.page.toInt() == pageController.page) { | |
previousPage = pageController.page.toInt(); | |
} | |
rotationController.add(pageController.page - previousPage); | |
} | |
pageController.addListener(_callback); | |
return () => pageController.removeListener(_callback); | |
}, [pageController, widget.key]); | |
return Scaffold( | |
body: Column( | |
children: [ | |
Spacer(flex: 1), | |
Expanded( | |
child: Center( | |
child: PageView.builder( | |
itemCount: 10, | |
controller: pageController, | |
itemBuilder: (_, i) => Card( | |
color: i % 2 == 0 ? Colors.blueAccent : Colors.teal, | |
child: Center(child: Text(i.toString())), | |
), | |
), | |
), | |
), | |
Spacer( | |
flex: 1, | |
), | |
Expanded( | |
flex: 2, | |
child: Center( | |
child: GridView.builder( | |
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( | |
crossAxisCount: 5, | |
mainAxisSpacing: 10, | |
crossAxisSpacing: 10, | |
), | |
itemCount: 10, | |
itemBuilder: (_, __) => HookBuilder( | |
builder: (ctx) { | |
print('Building HookBuilder'); | |
final rotation = | |
useStream(rotationController.stream, initialData: .0); | |
return Transform.rotate( | |
angle: pi * (rotation.data ?? 0), | |
child: Container( | |
height: 150, | |
width: 150, | |
color: Colors.indigo, | |
), | |
); | |
}, | |
), | |
), | |
), | |
), | |
], | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment