<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Torben Keller on Medium]]></title>
        <description><![CDATA[Stories by Torben Keller on Medium]]></description>
        <link>https://medium.com/@torben-keller?source=rss-28112203ac02------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*oRPeHqVtyKT80YHF</url>
            <title>Stories by Torben Keller on Medium</title>
            <link>https://medium.com/@torben-keller?source=rss-28112203ac02------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:55:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@torben-keller/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[[Flutter] Avoid loading states in your BLoC’s]]></title>
            <link>https://medium.com/@torben-keller/avoid-loading-states-in-your-blocs-aaacc95597f9?source=rss-28112203ac02------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaacc95597f9</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[bloc]]></category>
            <dc:creator><![CDATA[Torben Keller]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 23:25:50 GMT</pubDate>
            <atom:updated>2023-10-11T15:07:50.498Z</atom:updated>
            <content:encoded><![CDATA[<p><em>For Flutter apps, the Business Logic Component (BLoC) pattern has emerged as a go-to choice for handling business logic. However, I’ve noticed that many developers use BLoC in combination with Freezed union types, and Loading, Loaded, and Error states. This often introduces unnecessary complexity without substantial benefits. In this article, I will show you an alternative and practical method of using asynchronous data within your BLoCs by shifting the responsibility of handling asynchronous calls outside of the BLoC and instead, passing the required values via the constructor.</em></p><h3>Loading States in the BLoC</h3><p>What I often see is similar to this:</p><pre>// my_state.dart<br><br>@freezed<br>class MyState with $MyState {<br>  const factory MyState.loading() = MyStateLoading;<br>  const factory MyState.error(…) = MyStateError;<br>  const factory MyState.loaded(…) = MyStateLoaded;<br>}</pre><pre>// my_event.dart<br><br>@freezed<br>class MyEvent with $MyEvent {<br>  const factory MyEvent.initialize(…) = MyEventInitialize;<br>  const factory MyEvent.doSomething(…) = MyEventDoSomething;<br>  …<br>}</pre><pre>// my_bloc.dart<br><br>class MyBloc extends Bloc&lt;MyEvent, MyState&gt; {<br>  MyBloc() : super(MyState.loading()) {<br>    on&lt;MyEventInitialize&gt;(_initialize());<br>    on&lt;MyEventDoSomething&gt;(_doSomething());<br>    …<br>  };<br><br>  Future&lt;void&gt; _initialize(<br>    MyEventInitialize event,<br>    Emitter&lt;MyState&gt; emit,<br>  ) async {<br>    // … async data loading<br>    emit(MyState.loaded(…));<br>  }<br>  <br>  Future&lt;void&gt; _doSomething(<br>    MyEventDoSomething event,<br>    Emitter&lt;MyState&gt; emit,<br>  ) async {<br>    if(state is! MyStateLoaded){<br>      emit(const MyState.error(…));<br>      return;<br>    }<br>    …<br>  }<br><br>  …<br>}</pre><pre>// my_widget.dart<br><br>@override<br>Widget build(BuildContext context) {<br>  return BlocProvider(<br>    create: (context) =&gt; MyBloc()<br>      ..add(const MyEvent.initialize(…)),<br>    child: …<br>  );<br>}</pre><p>We have a Bloc with an union type for the states and an initialize event. When creating the Bloc it starts in the loading state and we add the initialize event immediately after the instantiation. The initialize event handler then asynchronously loads the data and eventually emits a loaded state. All other event handlers then must check for the loaded state to get access to the data or assume the data is already loaded.</p><h4>Why is this bad?</h4><ul><li><strong>It dilutes the Bloc:</strong> The checks for the loaded state and logic what to do if the initialization failed dilute the Bloc. That is not business logic. Thats application logic.</li><li><strong>More complexity:</strong> The lifecycle of the Bloc in the app is complex. When we access the state of the Bloc through the widget tree, can we assume the data is always loaded? Or not? If yes this is an implicit rule that increases the complexity of your app. If no, you have to add many checks across your app, which also increases the complexity and might result in bugs.</li><li><strong>Hard to test:</strong> We have to mock all dependencies that get used in the initialize event handler. And in theory we must test each event handler, that it only works on a loaded state. This is unnecessary complexity not related to the actual business logic.</li></ul><h3>How to improve this?</h3><p>The general idea is to extract the loading logic from the Bloc into a Service. Then instead of using the BlocProvider as usual, we call the Service. Until the Future is completed, we show some loading indication in the UI. Then when the Future has completed, we add the BlocProvider to the widget tree and create the Bloc with the result from the Service.</p><pre>// my_state.dart<br><br>@freezed<br>  class MyState with $MyState {<br>  const factory MyState(MyData data) = _MyState;<br>}</pre><pre>// my_event.dart<br><br>@freezed<br>class MyEvent with $MyEvent {<br>  const factory MyEvent.doSomething(…) = MyEventDoSomething;<br>  …<br>}</pre><pre>// my_bloc.dart<br><br>class MyBloc extends Bloc&lt;MyEvent, MyState&gt; {<br>  MyBloc(MyData data) : super(MyState(data)) {<br>    on&lt;MyEventDoSomething&gt;(_doSomething());<br>    …<br>  };<br>  <br>  Future&lt;void&gt; _doSomething(<br>    MyEventDoSomething event,<br>    Emitter&lt;MyState&gt; emit,<br>  ) async {<br>    // do business logic<br>    …<br>  }<br><br>  …<br>}</pre><pre>// my_service.dart<br><br>class MyService {<br>  const MyService();<br>  <br>  Future&lt;MyData&gt; loadData(…) async {<br>    // … async data loading<br>  }<br>}</pre><pre>// my_widget.dart<br><br>class _MyWidgetState extends State&lt;MyWidget&gt; {<br>  Future&lt;MyData&gt;? _loadData;<br><br>  @override<br>  void didChangeDependencies() {<br>    super.didChangeDependencies();<br>    _loadData ??= context.read&lt;MyService&gt;().loadData();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return FutureBuilder&lt;MyData&gt;(<br>      future: _loadData,<br>      builder: (context, snapshot) {<br>        if(snapshot.hasError){<br>          return ErrorWidget();<br>        }<br>        if(!snapshot.hasData){<br>          return LoadingWidget();<br>        }<br>        <br>        return BlocProvider(<br>          create: (context) =&gt; MyBloc(snapshot.data!),<br>          child: …<br>        );<br>      }<br>    );<br>  }<br>}</pre><p>Now the Bloc can fully focus on the business logic and if the Bloc is provided via the widget tree, it is always loaded.</p><h4>What if we need the Bloc on multiple pages?</h4><p>When you need a Bloc on multiple pages, it is best practice to create the BlocProvider above the MaterialApp. But then we can not show a loading indicator in the UI. So how to deal with this situation? The solution is to call the Service in your main function. Then the native splash screen will be displayed while loading the data.</p><pre>// main.dart<br><br>Future&lt;void&gt; main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  <br>  final myService = const MyService();<br>  final myData = await myService.loadData(…);<br><br>  runApp(<br>    BlocProvider(<br>      create: (context) =&gt; MyBloc(myData),<br>      child: MyApp(),<br>    );<br>  );<br>}</pre><h3>Conclusion</h3><p>In this article we’ve seen that there is a practical less complex method of using asynchronous data in a BLoC without fetching the data inside the BLoC and using Loading, Loaded and Error states.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaacc95597f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart Error handling using Records (golang style)]]></title>
            <link>https://medium.com/@torben-keller/dart-error-handling-using-records-golang-style-9b1faaec769c?source=rss-28112203ac02------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b1faaec769c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[dartlang]]></category>
            <dc:creator><![CDATA[Torben Keller]]></dc:creator>
            <pubDate>Sat, 10 Jun 2023 02:20:04 GMT</pubDate>
            <atom:updated>2023-06-10T03:00:26.865Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Error handling in dart is a highly discussed very opinionated topic within the community. Dart 3.0 enables a golang inspired style of error handling using Records that could increase code quality while keeping readable code.</em></p><h3>No Checked Exceptions in Dart</h3><p>Darts error handling mechanism works using try/catch and throws. Unfortunately it is not possible to document the potentially arising exceptions in the functions signature. The effective dart documentation recommends to document exceptions in the doc comments (<a href="https://dart.dev/effective-dart/documentation#do-use-prose-to-explain-parameters-return-values-and-exceptions">here</a>) but this will not result in a linter warning nor a compile error when ignoring an exception. This leads to unchecked runtime errors which potentially cause crashes in production systems.</p><p>Google is also not willing to introduce checked exceptions or a linter rule to make thrown exceptions more explicit in the near future. See these issues for more information:</p><ul><li><a href="https://github.com/dart-lang/language/issues/984">Add checked exceptions. · Issue #984 · dart-lang/language</a></li><li><a href="https://github.com/dart-lang/linter/issues/2246">Lint for undocumented exceptions. · Issue #2246 · dart-lang/linter</a></li></ul><h3>Using a Result type</h3><p>To make errors more explicit in dart, you could use a Result type. In the community the Either type from the <a href="https://pub.dev/packages/dartz">dartz</a> package is commonly used as a Result type where Right represents a success composing the return value and Left represents a failure composing the exception. This works well especially in combination with other concepts from functional programming but also leads to a massive use of lambda functions and cascading function calls resulting in less readable code.</p><p>Dart 3.0 introduced sealed classes that could provide a more simple api using Result types. See <a href="https://codewithandrea.com/articles/flutter-exception-handling-try-catch-result-type/">this</a> article from Andrea Bizzotto for more information.</p><h3>Using Records</h3><p>Go (golang) is a programming language developed by google providing a very simple syntax with only 25 keywords. Because of the simplicity of the language, Go is not using the “traditional” try/catch approach. Errors in Go are lifted up as a second result value using a similar syntax as <a href="https://dart.dev/language/records">Records</a> introduced in Dart 3.0. You can find more information about error handling in golang <a href="https://go.dev/blog/error-handling-and-go">here</a>.</p><p>In the first place we create class composing the Exception and StackTrace :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dea83d0ac98415f70221826e8dd39615/href">https://medium.com/media/dea83d0ac98415f70221826e8dd39615/href</a></iframe><p>Now we can define the return type of a function as (ReturnType, FailureResult&lt;Exception&gt;?) . An example implementation of a divide function could look as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c19adde03f29f0f587f4ab64bc1a4ce/href">https://medium.com/media/1c19adde03f29f0f587f4ab64bc1a4ce/href</a></iframe><p>Notice, that x ~/ y can throw an IntegerDivisionByZeroException. When no exception is thrown, we return a new record where the FailureResult is explicitly set to null.</p><p>When an exception is thrown, we catch it and return for the result 0. The convention in Go is to return zero or zero equivalents for primitive data types and the null equivalent of Go for non primitive data types. <br>The second return value is an instance of our previously created FailureResult class containing the catched exception and stack trace.</p><p>We can access the value and exception as the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7cd7653811bd668eb496731c0c42ce9/href">https://medium.com/media/d7cd7653811bd668eb496731c0c42ce9/href</a></iframe><p>This produces the following output:</p><pre>6 / 2 = 3<br>IntegerDivisionByZeroException<br>#0      int.~/ (dart:core-patch/integers.dart:30:7)<br>#1      divide (main.dart:24:19)<br>#2      main (main.dart:63:14)<br>#3      _delayEntrypointInvocation.&lt;anonymous closure&gt; (dart:isolate-patch/isolate_patch.dart:296:19)<br>#4      _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:189:12)</pre><p>Lets have a look more in detail. We execute the divide function and assign the return value to (res, f). After that, we check wether the FailureResult is null or not. If it is null, everything succeeded, if it is non-null there is a failure and we should handle it. This is in the first moment unfamiliar when being used using try/catch but error handling in Go works like that. Just a simple if statement.</p><p>This simplicity is freedom on the consuming side. You can ignore the failure explicitly by using a wildcard, or you can wrap the record with a Future and use the normal async await syntax to access the record and use the value later.</p><p>But no solution is perfect. When using the golang style exception handling you loose the null safety of your result value if it is class without an empty constructor. In the divide function, I returned 0 and the FailureResult. But when the constructor of the class requires something, you can not create and return an instance of your result type. You have to return null for your result value. That means when you checked the failure for null and want to use your result value, you have to use the ! operator to tell the compiler the result value is non null. That is unpleasant and can lead to errors. Also the functions signature looses this information. So when the function in the future returns also nullable values, you can run into runtime errors. The other option is to use an other if statement to check for the nullability of the result value. Also unpleasant but probably better than the ! operator.</p><h3>Conclusion</h3><p>When you are not confident with the current state of error handling in dart, the Go style error handling is a serious option to use. Wether you use a Result type or the record based error handling is a matter of opinion. But both don’t solve the problem of the ecosystem relying on the dart default not checked exception model. If a package changes what exceptions can be thrown it is a breaking change that you are potentially still not aware of. Only checked exceptions or at least a linting rule could solve that for us all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b1faaec769c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Flutter] Why shouldn’t Either be used for error handling?]]></title>
            <link>https://medium.com/@torben-keller/flutter-why-shouldnt-either-be-used-for-error-handling-e1b10a89d883?source=rss-28112203ac02------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1b10a89d883</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Torben Keller]]></dc:creator>
            <pubDate>Sat, 03 Dec 2022 19:41:28 GMT</pubDate>
            <atom:updated>2022-12-03T19:41:28.550Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In the past 4 years of Flutter development I often see tutorials and people using the Either type for error handling. In this article I will discuss why this is not a good idea.</em></p><h3>History</h3><p>The first time I saw somebody using Either for error handling was 3 years ago when Reso Coder introduced it in his popular Clean Architecture TDD course. After the course he also made 2 separate tutorials about functional error handling with Either and since then people adopt it for their projects.</p><h3>The Arguments for using Either</h3><p><em>Unfortunately Reso Coder didn’t really point out </em><strong><em>why</em></strong><em> it is better to use </em>Either<em> for error handling. He just shows that his solution works and how to code it but the big arguments are missing. What I have read between the lines was this:</em></p><ol><li><strong>Using </strong><strong>throws makes errors implicit and not explicit.<br></strong>When you call a function you can not see in the functions signature that and what the function will throw. I.e. in Java you have to add the throws keyword to the function signature so you always know that and what the function throws. Either should address this problem and makes errors explicit to the functions signature.</li><li><strong>When you access the value of a throwing function you should always handle the error.<br></strong>When a function can throw something and you want to access the value you will not get a compiler error when you forget to catch the error. Wrapping the value with Either let you access the value only when you fold it to Right or Left. This ensures you handle the error. Otherwise you will get a compiler error and without compiler errors you create bugs.</li></ol><h3>Why you should avoid using Either nevertheless</h3><p><em>In the first place using </em>Either<em> sounds good. You make errors explicit and get compile safe error handling. But is it worth using </em>Either<em> to achieve this? Short answer: No it is not.</em></p><ol><li><strong>The ecosystem uses throw.<br></strong>All packages you might use will rely on throwing exceptions for error handling. The functions you call will throw exceptions that you have to catch and map to your Either object. That is obvious.<br>But the packages and Flutter itself expect errors to be thrown. A good example for this might be the default FutureBuilder. It stores only thrown errors in the snapshot. The FutureProvider of <a href="https://pub.dev/packages/flutter_riverpod">flutter_riverpod</a> works similar. It stores only thrown errors in the AsyncError object. When you use Either in combination with one of these you would have to fold the loaded value and ignore the already built in error handling functionality. Not elegant in my opinion.</li><li><strong>You can still have thrown exceptions.<br></strong>In dart you can not forbid throwing exceptions. So even when you use Either you can not be 100% sure that no exceptions will be thrown. You probably rely on functions that will throw and have to make sure to catch all exceptions of those functions. But here you can make a mistake let exceptions pass. Then you have both. Exceptions that got thrown and Exceptions in your Either object. Very confusing when you run into this.</li><li><strong>Boilerplate causes bad readability.<br></strong>When you want to use a value from a function that returns an Either you have to fold the Either and pass a callback into the fold method. That means all the code that depends on the value has to be in the callback and get another indention level. When you stack multiple of those folds into each other you get lots of indention. That makes the code extremely hard to read. Also when you stack folds into each other, you have to handle the errors for each fold individually. You can not create one catch block for all function invocations.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b7ee938fd5ce6e14c98c9c5d8c2cdbe/href">https://medium.com/media/2b7ee938fd5ce6e14c98c9c5d8c2cdbe/href</a></iframe><h3>How to make errors explicit without Either?</h3><p>You should make errors explicit using <a href="https://dart.dev/guides/language/effective-dart/documentation#do-use-prose-to-explain-parameters-return-values-and-exceptions">dart doc comments</a>. This is best practice in the dart ecosystem and you should adopt it for your app as well. Unfortunately then you don’t have compile safety when handling errors but as I pointed out, even with using Either errors can be thrown and then you loose your compile safety as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1b10a89d883" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>