Skip to content

Instantly share code, notes, and snippets.

@hawkkiller
Created April 25, 2022 07:54
Show Gist options
  • Save hawkkiller/c6686e0d526fcb301e9d33cbb7794b2e to your computer and use it in GitHub Desktop.
Save hawkkiller/c6686e0d526fcb301e9d33cbb7794b2e to your computer and use it in GitHub Desktop.
An example of using intents and actions API
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:meta/meta.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(
const MyApp(),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: const Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
const MyWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ModelInh(
model: Model(),
child: Builder(builder: (context) {
final model = ModelInh.of(context).model;
return Actions(
actions: {
ModifyIntent: CountAction(model),
},
child: Builder(
builder: (context) {
return StreamBuilder<int>(
initialData: 0,
stream: model.stream,
builder: (context, d) {
return Column(children: [
Text('Count: ${d.data}'),
TextButton(
child: const Text('Add'),
onPressed: () => Actions.invoke(
context,
ModifyIntent(d.data! + 1),
),
)
]);
},
);
},
),
);
}),
);
}
}
class ModelInh extends InheritedWidget {
const ModelInh({
Key? key,
required Widget child,
required this.model,
}) : super(key: key, child: child);
final Model model;
static ModelInh of(BuildContext context) {
ModelInh? inh;
final result =
context.getElementForInheritedWidgetOfExactType<ModelInh>()?.widget;
inh = result is ModelInh ? result : null;
assert(inh != null, 'No Model found in context');
return inh ?? _notInScope();
}
@alwaysThrows
static Never _notInScope() => throw 'No Model found in context';
@override
bool updateShouldNotify(ModelInh oldWidget) {
return false;
}
}
class Model {
Model();
final _controller = StreamController<int>.broadcast();
Stream<int> get stream => _controller.stream;
void setCount(int c) {
_controller.add(c);
}
}
class ModifyIntent extends Intent {
const ModifyIntent(this.count);
final int count;
}
class CountAction extends Action<ModifyIntent> {
CountAction(this.model);
final Model model;
@override
void invoke(covariant ModifyIntent intent) {
model.setCount(intent.count);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment