Created
June 30, 2023 20:47
-
-
Save Andrious/c3896795659c82daf5c78e427ba030bf to your computer and use it in GitHub Desktop.
Counter example app demonstrating the StateX class
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:fluttery_framework/view.dart'; | |
import 'package:fluttery_framework/controller.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends AppStatefulWidget { | |
MyApp({Key? key}) : super(key: key); | |
@override | |
AppState createAppState() => View(); | |
} | |
class View extends AppState { | |
View() | |
: super( | |
title: 'Flutter Demo', | |
home: const MyHomePage(), | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
); | |
} | |
class MyHomePage extends StatefulWidget { | |
const MyHomePage({Key? key, this.title = 'Flutter Demo Home Page'}) | |
: super(key: key); | |
// Fields in a StatefulWidget should always be "final". | |
final String title; | |
@override | |
State createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends StateX<MyHomePage> { | |
_MyHomePageState() : super(controller: Controller()) { | |
con = controller as Controller; | |
} | |
late Controller con; | |
@override | |
Widget buildAndroid(BuildContext context) => Scaffold( | |
appBar: AppBar( | |
title: Text(widget.title), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
const Text('You have pushed the button this many times:'), | |
Text( | |
'${con.counter}', | |
style: Theme.of(context).textTheme.headlineMedium, | |
), | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
/// Try this alternative approach. | |
/// The Controller merely mimics the Flutter's API | |
// onPressed: con.onPressed, | |
onPressed: () => setState(con.incrementCounter), | |
tooltip: 'Increment', | |
child: const Icon(Icons.add), | |
), | |
); | |
} | |
class Controller extends StateXController { | |
factory Controller() => _this ??= Controller._(); | |
Controller._() | |
: _model = _Model(), | |
super(); | |
static Controller? _this; | |
final _Model _model; | |
/// You're free to mimic Flutter's own API | |
/// The Controller is able to talk to the View (the State object) | |
void onPressed() => setState(() => _model._incrementCounter()); | |
int get counter => _model.integer; | |
/// The Controller knows how to 'talk to' the Model. | |
void incrementCounter() => _model._incrementCounter(); | |
} | |
class _Model { | |
int get integer => _integer; | |
int _integer = 0; | |
int _incrementCounter() => ++_integer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment