SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Downloaden Sie, um offline zu lesen
BLoC
Be Reactive in Flutter
Giacomo Ranieri
GDG Torino
@ilconteranieri
Il vostro Speaker
Giacomo Ranieri
Consulente
GDG Lead
Nerd
Ballerino
Sommario
La programmazione reattiva
Programmazione reattiva in flutter
BLoC come soluzione
Librerie di supporto
Conclusioni
La Programmazione
Reattiva
Cos’è ?
Orientata alla asincronicità
Stream di dati
Manipolazione tramite funzioni
x |
Valori Errore Fine
Stream
Un Esempio
1 1 1 1 1
Click Stream
1 2 3 4 5
Counter Stream
clickStream.map(f).scan(g)
map( click diventa 1 )
scan( somma )
La Programmazione
Reattiva in Flutter
Flutter è reattivo
Nato nel boom della programmazione reattiva
Ispirato a React
UI Reattiva
Partiamo dalla base
Widget con stato
Callback
class MyHomePage extends StatefulWidget {
...}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return ...
Text(
'$_counter',
),
...
Incrementer(_incrementCounter),
);
}
}
class Incrementer extends StatelessWidget {
final Function _incrementCounter;
const Incrementer(this._incrementCounter);
@override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
);
}
}
class MyHomePage extends StatefulWidget {
...}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return ...
Text(
'$_counter',
),
...
Incrementer(_incrementCounter),
);
}
}
class Incrementer extends StatelessWidget {
final Function _incrementCounter;
const Incrementer(this._incrementCounter);
@override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
);
}
}
Aggiungiamo un modello
Model
ScopedModel
ScopedModelDescendant<>
class MyHomePage extends StatefulWidget {
...}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return ScopedModel(
model: CounterModel(),
child: ...
ScopedModelDescendant<CounterModel>(
builder: (context, child, model) {
return Text(
model.counter.toString(),
);
},
),
...
Incrementer(),
);
}
}
class Incrementer extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ScopedModelDescendant<CounterModel>(
builder: (context, child, model) {
return FloatingActionButton(
onPressed: () => model.increment(),
tooltip: 'Increment',
child: Icon(Icons.add),
);
},
);
}
}
class CounterModel extends Model {
int _counter = 0;
int get counter => _counter;
void increment() {
_counter++;
notifyListeners();
}
}
class MyHomePage extends StatefulWidget {
...}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return ScopedModel(
model: CounterModel(),
child: ...
ScopedModelDescendant<CounterModel>(
builder: (context, child, model) {
return Text(
model.counter.toString(),
);
},
),
...
Incrementer(),
);
}
}
class Incrementer extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ScopedModelDescendant<CounterModel>(
builder: (context, child, model) {
return FloatingActionButton(
onPressed: () => model.increment(),
tooltip: 'Increment',
child: Icon(Icons.add),
);
},
);
}
}
class CounterModel extends Model {
int _counter = 0;
int get counter => _counter;
void increment() {
_counter++;
notifyListeners();
}
}
BLoC come
soluzione
E alla fine arriva BLoC
Stream
StreamBuilder
Business Logic
E alla fine arriva BLoC
class CounterBloc {
int _counter = 0;
Sink<int> get increment => _incrementController.sink;
final _incrementController = StreamController<int>();
Stream<String> get count => _countSubject.stream;
final _countSubject = BehaviorSubject<String>();
CounterBloc() {
_incrementController.stream.listen((event) {
_counter += event;
_countSubject.add('$_counter');
});
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Provider<CounterBloc>(
create: (context) => CounterBloc(),
child: MaterialApp(
...
home: MyHomePage(title: 'Counter'),
),
);
}
}
class MyHomePage extends StatefulWidget {
...}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
final counterBloc = Provider.of<CounterBloc>(context);
return ...
StreamBuilder(
stream: counterBloc.count,
builder: (context, snapshot) {
return Text(
snapshot.data,
);
},
),
...
Incrementer(),
);
}
}
class Incrementer extends StatelessWidget {
@override
Widget build(BuildContext context) {
final counterBloc = Provider.of<CounterBloc>(context);
return FloatingActionButton(
onPressed: () => counterBloc.increment.add(1),
tooltip: 'Increment',
child: Icon(Icons.add),
);
}
}
Librerie di supporto
Per costruire i BLoC
Package bloc
Cubit
Bloc
Per sfruttare i BLoC
Package flutter_bloc
BlocProvider e MultiBlocProvider
BlocBuilder
Concludiamo
Bello ma non bellissimo
+ Forte separazione dei ruoli tra widget
+ Aggiornamenti puntuali della UI
+ Facilmente testabile
- Complesso da usare
Grazie!
Giacomo Ranieri
GDG Torino
@ilconteranieri

Weitere ähnliche Inhalte

Ähnlich wie BLoC - Be Reactive in flutter

Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonfNataliya Patsovska
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법Jeado Ko
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every dayVadym Khondar
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"GeeksLab Odessa
 
Flutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdfFlutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdfKaty Slemon
 
React 101 by Anatoliy Sieryi
React 101 by Anatoliy Sieryi React 101 by Anatoliy Sieryi
React 101 by Anatoliy Sieryi Binary Studio
 
N Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React NativeN Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React NativeAnton Kulyk
 
MOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app developmentMOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app developmentanistar sung
 
This is a C# project . I am expected to create as this image shows. .pdf
This is a C# project . I am expected to create as this image shows. .pdfThis is a C# project . I am expected to create as this image shows. .pdf
This is a C# project . I am expected to create as this image shows. .pdfindiaartz
 
ASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CSASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CStutorialsruby
 
ASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CSASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CStutorialsruby
 
Scripting languages
Scripting languagesScripting languages
Scripting languagesteach4uin
 
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinWill your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinBarry Gervin
 
Week 8
Week 8Week 8
Week 8A VD
 

Ähnlich wie BLoC - Be Reactive in flutter (20)

mobl
moblmobl
mobl
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonf
 
GWT MVP Case Study
GWT MVP Case StudyGWT MVP Case Study
GWT MVP Case Study
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
 
Google Web Toolkit
Google Web ToolkitGoogle Web Toolkit
Google Web Toolkit
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
 
Flutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdfFlutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdf
 
React 101 by Anatoliy Sieryi
React 101 by Anatoliy Sieryi React 101 by Anatoliy Sieryi
React 101 by Anatoliy Sieryi
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
 
N Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React NativeN Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React Native
 
MOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app developmentMOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app development
 
This is a C# project . I am expected to create as this image shows. .pdf
This is a C# project . I am expected to create as this image shows. .pdfThis is a C# project . I am expected to create as this image shows. .pdf
This is a C# project . I am expected to create as this image shows. .pdf
 
ASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CSASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CS
 
ASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CSASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CS
 
Scripting languages
Scripting languagesScripting languages
Scripting languages
 
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinWill your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
 
Android 3
Android 3Android 3
Android 3
 
Week 8
Week 8Week 8
Week 8
 
Web-First Design Patterns
Web-First Design PatternsWeb-First Design Patterns
Web-First Design Patterns
 

Kürzlich hochgeladen

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 

Kürzlich hochgeladen (20)

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

BLoC - Be Reactive in flutter

  • 1. BLoC Be Reactive in Flutter Giacomo Ranieri GDG Torino @ilconteranieri
  • 2. Il vostro Speaker Giacomo Ranieri Consulente GDG Lead Nerd Ballerino
  • 3. Sommario La programmazione reattiva Programmazione reattiva in flutter BLoC come soluzione Librerie di supporto Conclusioni
  • 5. Cos’è ? Orientata alla asincronicità Stream di dati Manipolazione tramite funzioni x | Valori Errore Fine Stream
  • 6. Un Esempio 1 1 1 1 1 Click Stream 1 2 3 4 5 Counter Stream clickStream.map(f).scan(g) map( click diventa 1 ) scan( somma )
  • 8. Flutter è reattivo Nato nel boom della programmazione reattiva Ispirato a React UI Reattiva
  • 9. Partiamo dalla base Widget con stato Callback
  • 10. class MyHomePage extends StatefulWidget { ...} class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return ... Text( '$_counter', ), ... Incrementer(_incrementCounter), ); } } class Incrementer extends StatelessWidget { final Function _incrementCounter; const Incrementer(this._incrementCounter); @override Widget build(BuildContext context) { return FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ); } }
  • 11. class MyHomePage extends StatefulWidget { ...} class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return ... Text( '$_counter', ), ... Incrementer(_incrementCounter), ); } } class Incrementer extends StatelessWidget { final Function _incrementCounter; const Incrementer(this._incrementCounter); @override Widget build(BuildContext context) { return FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ); } }
  • 13. class MyHomePage extends StatefulWidget { ...} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return ScopedModel( model: CounterModel(), child: ... ScopedModelDescendant<CounterModel>( builder: (context, child, model) { return Text( model.counter.toString(), ); }, ), ... Incrementer(), ); } } class Incrementer extends StatelessWidget { @override Widget build(BuildContext context) { return ScopedModelDescendant<CounterModel>( builder: (context, child, model) { return FloatingActionButton( onPressed: () => model.increment(), tooltip: 'Increment', child: Icon(Icons.add), ); }, ); } } class CounterModel extends Model { int _counter = 0; int get counter => _counter; void increment() { _counter++; notifyListeners(); } }
  • 14. class MyHomePage extends StatefulWidget { ...} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return ScopedModel( model: CounterModel(), child: ... ScopedModelDescendant<CounterModel>( builder: (context, child, model) { return Text( model.counter.toString(), ); }, ), ... Incrementer(), ); } } class Incrementer extends StatelessWidget { @override Widget build(BuildContext context) { return ScopedModelDescendant<CounterModel>( builder: (context, child, model) { return FloatingActionButton( onPressed: () => model.increment(), tooltip: 'Increment', child: Icon(Icons.add), ); }, ); } } class CounterModel extends Model { int _counter = 0; int get counter => _counter; void increment() { _counter++; notifyListeners(); } }
  • 16. E alla fine arriva BLoC Stream StreamBuilder Business Logic
  • 17. E alla fine arriva BLoC
  • 18. class CounterBloc { int _counter = 0; Sink<int> get increment => _incrementController.sink; final _incrementController = StreamController<int>(); Stream<String> get count => _countSubject.stream; final _countSubject = BehaviorSubject<String>(); CounterBloc() { _incrementController.stream.listen((event) { _counter += event; _countSubject.add('$_counter'); }); } } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return Provider<CounterBloc>( create: (context) => CounterBloc(), child: MaterialApp( ... home: MyHomePage(title: 'Counter'), ), ); } }
  • 19. class MyHomePage extends StatefulWidget { ...} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { final counterBloc = Provider.of<CounterBloc>(context); return ... StreamBuilder( stream: counterBloc.count, builder: (context, snapshot) { return Text( snapshot.data, ); }, ), ... Incrementer(), ); } } class Incrementer extends StatelessWidget { @override Widget build(BuildContext context) { final counterBloc = Provider.of<CounterBloc>(context); return FloatingActionButton( onPressed: () => counterBloc.increment.add(1), tooltip: 'Increment', child: Icon(Icons.add), ); } }
  • 21. Per costruire i BLoC Package bloc Cubit Bloc
  • 22. Per sfruttare i BLoC Package flutter_bloc BlocProvider e MultiBlocProvider BlocBuilder
  • 24. Bello ma non bellissimo + Forte separazione dei ruoli tra widget + Aggiornamenti puntuali della UI + Facilmente testabile - Complesso da usare