Created
January 9, 2023 21:22
-
-
Save MelbourneDeveloper/83fcabba9c41221bc7e222f24ec7547d to your computer and use it in GitHub Desktop.
Immutable State and StatelessWidgets Without Library
This file contains 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'; | |
@immutable | |
class Counter { | |
const Counter(this.count); | |
final int count; | |
Counter copyWith({int? count}) => Counter(count ?? this.count); | |
} | |
class CounterNotifier extends ValueNotifier<Counter> { | |
CounterNotifier(super.value); | |
void increment() => value = value.copyWith(count: value.count + 1); | |
} | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
MyApp({super.key}); | |
final CounterNotifier counter = CounterNotifier(const Counter(0)); | |
@override | |
Widget build(BuildContext context) => MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: MyHomePage( | |
title: 'Flutter Demo Home Page', | |
counter: counter, | |
), | |
); | |
} | |
class MyHomePage extends StatelessWidget { | |
const MyHomePage({ | |
required this.title, | |
required this.counter, | |
super.key, | |
}); | |
final String title; | |
final CounterNotifier counter; | |
@override | |
Widget build(BuildContext context) => Scaffold( | |
appBar: AppBar( | |
title: Text(title), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
const Text( | |
'You have pushed the button this many times:', | |
), | |
AnimatedBuilder( | |
animation: counter, | |
builder: (context, widget) => Text( | |
'${counter.value.count}', | |
style: Theme.of(context).textTheme.headline4, | |
), | |
), | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: counter.increment, | |
tooltip: 'Increment', | |
child: const Icon(Icons.add), | |
), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment