Skip to content

Instantly share code, notes, and snippets.

@savioserra
Created February 13, 2020 21:56
Show Gist options
  • Save savioserra/6ee6e402e031468c3f7a9cdc1ff1a0df to your computer and use it in GitHub Desktop.
Save savioserra/6ee6e402e031468c3f7a9cdc1ff1a0df to your computer and use it in GitHub Desktop.
ObservableFuture
import 'package:mobx/mobx.dart';
part 'mainpage.controller.g.dart';
class ExampleModel {
final String observacao;
ExampleModel(this.observacao);
}
class MainPageController = _MainPageControllerBase with _$MainPageController;
abstract class _MainPageControllerBase with Store {
_MainPageControllerBase() {
reaction<List<ExampleModel>>(
(_) => future.value,
(value) => setObservacao(value?.elementAt(0)?.observacao ?? ""),
);
when((_) => future.value != null, () => print("nao esta nulo"));
}
@observable
ObservableFuture<List<ExampleModel>> future;
@observable
String observacao = "";
@action
Future<void> getModel() async {
future = Future.delayed(
Duration(seconds: 1),
() => [ExampleModel("example observacao")],
).asObservable();
}
@action
void outro() {
future = Future.delayed(
Duration(seconds: 1),
() => [ExampleModel("example observacao")],
).asObservable();
}
@action
void setObservacao(String value) {
observacao = value;
}
}
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:mobx/mobx.dart';
import 'package:mobx_example/mainpage.controller.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final controller = MainPageController();
final textController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Example"),
),
body: Column(
children: [
Observer(
builder: (_) => Container(
color: Colors.red,
child: Column(children: [
for (var model in (controller.future?.value ?? []))
Text(model.observacao)
]),
),
),
Observer(builder: (_) {
if (textController.text != controller.observacao) {
textController.text = controller.observacao;
}
return Column(
children: [
Text(controller.observacao ?? ""),
TextField(
onChanged: controller.setObservacao,
controller: textController,
),
RaisedButton(
onPressed: () => controller.getModel(),
child: Text("Fetch"),
),
],
);
}),
],
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment