Skip to content

Instantly share code, notes, and snippets.

@alefwd
Last active July 25, 2024 06:34
Show Gist options
  • Save alefwd/d73ddbf8d43d12b2796137064a789eae to your computer and use it in GitHub Desktop.
Save alefwd/d73ddbf8d43d12b2796137064a789eae to your computer and use it in GitHub Desktop.
An example of a const class with nested mutable class
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
// global for simplicity
final AleMutableController controller = AleMutableController();
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: const AleConst(),
),
floatingActionButton: FloatingActionButton(
onPressed: _onPressed,
),
),
);
}
void _onPressed() {
controller.mutate();
}
}
// const class
class AleConst extends StatelessWidget {
const AleConst();
@override
Widget build(final BuildContext context) {
return AleMutable();
}
}
// mutable nested class
class AleMutable extends StatelessWidget {
@override
Widget build(final BuildContext context) {
return ListenableBuilder(
builder: (context, child) => Text(controller.state),
listenable: controller,
);
}
}
class AleMutableController extends ChangeNotifier {
String _state = 'ale';
String get state => _state;
void mutate() {
final newState = _state == 'ale' ? 'mike' : 'ale';
_state = newState;
notifyListeners();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment