Created
March 27, 2025 21:31
-
-
Save knaeckeKami/caa536bacefede01447d3f623b2715d5 to your computer and use it in GitHub Desktop.
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(const MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return const MaterialApp( | |
debugShowCheckedModeBanner: false, | |
home: Scaffold(body: Center(child: _Example())), | |
); | |
} | |
} | |
class _Example extends StatefulWidget { | |
const _Example(); | |
@override | |
State<_Example> createState() => _ExampleState(); | |
} | |
class _ExampleState extends State<_Example> { | |
Widget build(BuildContext context) { | |
return Column( | |
children: [ | |
// can be const | |
const ImprovedText( | |
debugLabel: "const", | |
textBuilder: _myText, | |
styleBuilder: _bodyMedium, | |
), | |
// cant be const yet because function literals cant be const | |
ImprovedText( | |
debugLabel: "not const", | |
textBuilder: | |
(context) => MaterialLocalizations.of(context).searchFieldLabel, | |
styleBuilder: (context) => Theme.of(context).textTheme.bodyMedium, | |
), | |
TextButton(child: Text("rebuild"), onPressed: () => setState(() {})), | |
], | |
); | |
} | |
} | |
TextStyle? _bodyMedium(BuildContext context) { | |
return Theme.of(context).textTheme.bodyMedium; | |
} | |
String _myText(BuildContext context) { | |
return MaterialLocalizations.of(context).searchFieldLabel; | |
} | |
class ImprovedText extends StatelessWidget { | |
final TextStyle? Function(BuildContext) styleBuilder; | |
final String Function(BuildContext) textBuilder; | |
final String? debugLabel; | |
const ImprovedText({ | |
required this.styleBuilder, | |
required this.textBuilder, | |
this.debugLabel, | |
}); | |
Widget build(BuildContext context) { | |
print("rebuild $debugLabel"); | |
return Text(textBuilder(context), style: styleBuilder(context)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment