Last active
June 26, 2022 15:59
-
-
Save rjpower/02aa39ef7799d520d4f6e7c3d332da23 to your computer and use it in GitHub Desktop.
flutter_hooks reproducer
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'; | |
import 'package:flutter_hooks/flutter_hooks.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
enum ChildType { a, b } | |
class ChildState<T> { | |
final Stream<T> childStream; | |
final ChildType childType; | |
ChildState(this.childStream, this.childType); | |
} | |
Stream<String> aStream() { | |
return Stream.periodic(const Duration(milliseconds: 500), (i) => 'EventA'); | |
} | |
Stream<String> bStream() { | |
return Stream.periodic(const Duration(milliseconds: 500), (i) => 'EventB'); | |
} | |
Stream<ChildState> stream() { | |
return Stream.periodic(const Duration(seconds: 1), (i) { | |
return i % 2 == 0 | |
? ChildState(aStream(), ChildType.a) | |
: ChildState(bStream(), ChildType.b); | |
}); | |
} | |
class MyApp extends HookWidget { | |
static final _stream = stream(); | |
@override | |
Widget build(BuildContext context) { | |
final snapshot = useStream(_stream); | |
return MaterialApp( | |
debugShowCheckedModeBanner: false, | |
home: Scaffold( | |
body: Center( | |
child: snapshot.hasData | |
? ChildStatusWidget(snapshot.requireData) | |
: const CircularProgressIndicator()), | |
), | |
); | |
} | |
} | |
class ChildStatusWidget extends HookWidget { | |
final ChildState state; | |
const ChildStatusWidget(this.state); | |
@override | |
Widget build(BuildContext context) { | |
final preserveState = useState(true); | |
final snapshot = | |
useStream(state.childStream, | |
preserveState: preserveState.value); | |
return Column(children: [ | |
Text( | |
'Hello, World! ${state.childType} ${snapshot.data}', | |
style: Theme.of(context).textTheme.headline4, | |
), | |
ElevatedButton( | |
child: Text('PreserveState: ${preserveState.value}'), | |
onPressed: () { | |
preserveState.value = !preserveState.value; | |
}), | |
]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment