Skip to content

Instantly share code, notes, and snippets.

@Andrious
Created September 28, 2023 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Andrious/e7d3ce3b8dcd5495978690a24ae5c3d6 to your computer and use it in GitHub Desktop.
Save Andrious/e7d3ce3b8dcd5495978690a24ae5c3d6 to your computer and use it in GitHub Desktop.
Counter Example App using StateX v. 4.7
import 'package:flutter/material.dart';
import 'package:state_extended/state_extended.dart';
/// Pass the boolean true take make this humble example app more efficient.
void main() => runApp(const StateXCounterPage(useInherited: false));
class StateXCounterPage extends StatefulWidget {
const StateXCounterPage({
super.key,
this.useInherited,
this.title = 'Flutter Demo Home Page',
});
// Fields in a StatefulWidget should always be "final".
final bool? useInherited;
final String title;
@override
//ignore: no_logic_in_create_state
State createState() => _StateXCounterPageState(useInherited);
}
/// Instead of the useInherited parameter, use the StateIn class
//class _StateXCounterPageState extends StateIn<StateXCounterPage> {
class _StateXCounterPageState extends StateX<StateXCounterPage> {
_StateXCounterPageState([useInherited = true])
: super(controller: YourController(), useInherited: useInherited) {
con = controller as YourController;
}
late YourController con;
@override
Widget buildIn(BuildContext context) => MaterialApp(
home: 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:'),
state(
(context) => Text(
'${con.data}',
style: Theme.of(context).textTheme.headlineMedium,
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: con.onPressed,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
),
);
}
class YourController extends StateXController {
// Using a factory constructor on Controllers and implementing the Singleton design pattern
factory YourController() => _this ??= YourController._();
YourController._() : _model = _Model();
static YourController? _this;
final _Model _model;
int get data => _model.integer;
void onPressed() {
// Allow only updating one widget improving performance
if (state!.useInherited) {
_model._incrementCounter();
notifyClients(); // The state() function is then called
} else {
setState(() => _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