Skip to content

Instantly share code, notes, and snippets.

@Andrious
Created July 14, 2022 16:51
Show Gist options
  • Save Andrious/0ca1dd1b2409f8eb31c3809ed9c0a4b8 to your computer and use it in GitHub Desktop.
Save Andrious/0ca1dd1b2409f8eb31c3809ed9c0a4b8 to your computer and use it in GitHub Desktop.
Example app demonstrating the StateX class
import 'package:flutter/material.dart';
import 'package:state_extended/state_extended.dart';
void main() => runApp(const MaterialApp(home: MyHomePage()));
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()) {
con = controller as Controller;
}
late Controller con;
@override
Widget build(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.data}',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: con.onPressed,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
class Controller extends StateXController {
// Using a factory constructor on Controllers and implementing the Singleton design pattern
factory Controller() => _this ??= Controller._();
Controller._()
: model = _Model(),
super();
static Controller? _this;
final _Model model;
int get data => model.integer;
void onPressed() => 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