Skip to content

Instantly share code, notes, and snippets.

@Andrious
Created November 1, 2018 18:59
Show Gist options
  • Save Andrious/68dd50f14401f957b78dc79fb7c66022 to your computer and use it in GitHub Desktop.
Save Andrious/68dd50f14401f957b78dc79fb7c66022 to your computer and use it in GitHub Desktop.
Where's the View? The Second Approach to implementing the MVC Library Package, mvc_pattern.
import 'package:mvc_pattern/mvc_pattern.dart';
/// Notice 'the rest of the app' has no idea this Dart file even exists.
import 'Model.dart';
class Controller extends ControllerMVC {
Controller() {
con = this;
}
static Controller con;
@override
initState() {
/// Demonstrating how the 'initState()' is easily implemented.
_counter = Model.counter;
}
int get displayThis => _counter;
int _counter;
void whatever() {
/// The Controller knows how to 'talk to' the Model. It knows the name, but Model does the work.
_counter = Model.incrementCounter();
}
}
import 'package:flutter/material.dart';
import 'MyHomePage.dart';
/// Dependency Injection of 'the Controller' in the design pattern.
import 'Controller.dart';
void main() => runApp(MVCCounterApp());
class MVCCounterApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class Model {
static int get counter => _counter;
static int _counter = 0;
static int incrementCounter() {
return ++_counter;
}
}
import 'package:flutter/material.dart';
import 'package:mvc_pattern/mvc_pattern.dart';
/// Dependency Injection of 'the Controller' in the design pattern.
import 'Controller.dart';
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
// Fields in a Widget subclass are always marked "final".
static final String title = 'Flutter Demo Home Page';
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends StateMVC {
_MyHomePageState():super(Controller()){
_con = Controller.con;
}
Controller _con;
@override
@protected
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(MyHomePage.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
MyHomePage.title,
),
Text(
'${_con.displayThis}',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(_con.whatever);
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment