Skip to content

Instantly share code, notes, and snippets.

@mmanflori
Created March 27, 2019 14:14
Show Gist options
  • Save mmanflori/9077eef5b99bfe9856850fcb788f61be to your computer and use it in GitHub Desktop.
Save mmanflori/9077eef5b99bfe9856850fcb788f61be to your computer and use it in GitHub Desktop.
tut 11 komplett
import 'package:flutter/material.dart';
import 'zaehler_bloc.dart';
import 'zaehler_ereignis.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(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _bloc = ZaehlerBloc();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child:StreamBuilder(
stream: _bloc.zaheler,
initialData: 0,
builder: (BuildContext context, AsyncSnapshot<int> snapshot){
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'${snapshot.data}',
style: Theme.of(context).textTheme.display1,
),
],
);
},
),
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
FloatingActionButton(
onPressed: ()=>_bloc.zaehlerEventSink.add(AdditionsEreignis()),
tooltip: 'Increment',
child: Icon(Icons.add),
),
SizedBox(width: 10.0,),
FloatingActionButton(
onPressed: ()=>_bloc.zaehlerEventSink.add(SubtraktionsEreignis()),
tooltip: 'Decrement',
child: Icon(Icons.remove),
),
],
),
);
}
@override
void dispose() {
super.dispose();
_bloc.dispose();
}
}
import 'dart:async';
import 'zaehler_ereignis.dart';
class ZaehlerBloc {
int _zaehler = 0;
final _zaehlerStateController = StreamController<int>();
StreamSink<int> get _inZaehler =>
_zaehlerStateController.sink; // die Variable ist privat
Stream<int> get zaheler =>
_zaehlerStateController.stream; // die Variable ist öffentlich
final _zaehlerEventController = StreamController<ZaehlerEreignis>();
Sink<ZaehlerEreignis> get zaehlerEventSink => _zaehlerEventController.sink;
ZaehlerBloc() {
_zaehlerEventController.stream.listen(_mapEventToState);
}
void _mapEventToState(ZaehlerEreignis event) {
if (event is AdditionsEreignis)
_zaehler++;
else
_zaehler--;
_inZaehler.add(_zaehler);
}
void dispose() {
_zaehlerStateController.close();
_zaehlerEventController.close();
}
}
abstract class ZaehlerEreignis {
}
class AdditionsEreignis extends ZaehlerEreignis {
}
class SubtraktionsEreignis extends ZaehlerEreignis {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment