<?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 Ralph Bergmann on Medium]]></title>
        <description><![CDATA[Stories by Ralph Bergmann on Medium]]></description>
        <link>https://medium.com/@ralphbergmann?source=rss-cc6093afa421------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*P9u71bTN26dPsC177BZoUA.jpeg</url>
            <title>Stories by Ralph Bergmann on Medium</title>
            <link>https://medium.com/@ralphbergmann?source=rss-cc6093afa421------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:42:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ralphbergmann/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[Managing Application State through Dependency Injection]]></title>
            <link>https://medium.com/@ralphbergmann/managing-application-state-through-dependency-injection-906627b7db77?source=rss-cc6093afa421------2</link>
            <guid isPermaLink="false">https://medium.com/p/906627b7db77</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Ralph Bergmann]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 18:44:07 GMT</pubDate>
            <atom:updated>2025-03-30T18:44:07.072Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://ralph-bergmann.github.io/inject.dart/chapter_3_quickstart.html">After setting up the basic structure of our application with dependency injection</a>, we want to explore how a well-designed project structure can work alongside state management through DI. This approach aligns with Flutter’s recommended best practices for <a href="https://docs.flutter.dev/app-architecture/guide">app architecture</a> and <a href="https://docs.flutter.dev/data-and-backend/state-mgmt/simple">state management</a>.</p><p>Before we dive into state management, let’s refactor our application to better separate concerns by extracting the app and home widgets into their own files. This restructuring will provide a cleaner foundation for implementing state management through dependency injection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7etQJdX3bIqD1l-c-9b9MQ.png" /></figure><h3>Refactoring the Application Structure</h3><p>First, let’s reorganize our code to separate the UI components from the dependency injection setup. This creates a more maintainable architecture as our application grows.</p><h4>Extracting Widgets into Feature-Based Files</h4><p>We’ll extract our widgets from main.dart into separate files using a feature-based organization:</p><ol><li>Create a src/features/app directory for the application widget</li><li>Create a src/features/home directory for the home page widget</li><li>Move relevant code while maintaining dependencies and annotations</li></ol><p>Here’s how we’ll refactor each file:</p><p><strong>main.dart</strong> — Will contain only the DI setup and application entry point:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:inject_annotation/inject_annotation.dart&#39;;<br><br>import &#39;main.inject.dart&#39; as g;<br>import &#39;src/features/app/app.dart&#39;;<br><br>void main() {<br>  final mainComponent = MainComponent.create();<br>  final app = mainComponent.myAppFactory.create();<br>  runApp(app);<br>}<br><br>@component<br>abstract class MainComponent {<br>  static const create = g.MainComponent$Component.create;<br><br>  @inject<br>  MyAppFactory get myAppFactory;<br>}</pre><p><strong>my_app.dart</strong> — Contains the app widget and its factory:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:inject_annotation/inject_annotation.dart&#39;;<br><br>import &#39;../home/home.dart&#39;;<br><br>@assistedFactory<br>abstract class MyAppFactory {<br>  MyApp create({Key? key});<br>}<br><br>class MyApp extends StatelessWidget {<br>  @assistedInject<br>  const MyApp({@assisted super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Flutter Demo&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>        useMaterial3: true,<br>      ),<br>      home: const MyHomePage(title: &#39;Flutter Demo Home Page&#39;),<br>    );<br>  }<br>}</pre><p><strong>my_home.dart</strong> — Contains the home page widget:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class MyHomePage extends StatefulWidget {<br>  const MyHomePage({super.key, required this.title});<br><br>  final String title;<br><br>  @override<br>  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();<br>}<br><br>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  int _counter = 0;<br><br>  void _incrementCounter() {<br>    setState(() {<br>      _counter++;<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>        title: Text(widget.title),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: &lt;Widget&gt;[<br>            const Text(<br>              &#39;You have pushed the button this many times:&#39;,<br>            ),<br>            Text(<br>              &#39;$_counter&#39;,<br>              style: Theme.of(context).textTheme.headlineMedium,<br>            ),<br>          ],<br>        ),<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: _incrementCounter,<br>        tooltip: &#39;Increment&#39;,<br>        child: const Icon(Icons.add),<br>      ),<br>    );<br>  }<br>}</pre><p>This refactoring creates a cleaner, more scalable project structure with these technical benefits:</p><ol><li><strong>Separation of Concerns</strong>: Each file now has a distinct responsibility</li><li><strong>Improved Maintainability</strong>: Changes to one feature won’t affect files for other features</li><li><strong>Better Dependency Management</strong>: Import paths clearly show dependencies between features</li><li><strong>Enhanced Discoverability</strong>: New team members can quickly locate components by feature</li><li><strong>DI-Friendly Organization</strong>: Structure supports targeted injection of dependencies where needed</li></ol><p>The resulting directory structure looks like this:</p><pre>flutter_demo/<br>└── lib/<br>    ├── main.dart                 (DI setup and entry point)<br>    └── src/<br>        └── features/<br>            ├── app/<br>            │   └── my_app.dart   (MyApp and MyAppFactory)<br>            └── home/<br>                └── my_home.dart  (MyHomePage)</pre><p>With this structure in place, we’re now ready to implement state management through dependency injection.</p><h4>Implementing State Management with Dependency Injection</h4><p>Now that we have a clean project structure, we’ll implement state management using dependency injection principles. Our architecture will introduce two new components: a CounterRepository for data persistence and a MyHomePageViewModel to connect the UI with this data layer.</p><p>The CounterRepository will handle the persistence of our counter value. It will provide methods to store and retrieve the counter, effectively abstracting the storage mechanism from the rest of the application. This abstraction is powerful because it allows us to change the underlying storage implementation without affecting the components that use it.</p><p>The MyHomePageViewModel will serve as an intermediary between our UI and the data layer. It will depend on the CounterRepository (injected through our DI system) and provide the UI with the state and methods it needs. This creates a clean separation between how data is presented and how it&#39;s stored or processed.</p><p>This architecture demonstrates one of the key benefits of dependency injection: the ability to create a system where components depend on abstractions rather than concrete implementations. When the MyHomePageViewModel receives its CounterRepository through injection, it doesn&#39;t need to know the details of how the repository is implemented or how it&#39;s instantiated.</p><p>This separation creates more maintainable code because changes to one layer don’t necessarily affect others. It also dramatically improves testability since each component can be tested in isolation with mock implementations of its dependencies. The repository could be reused across different features if needed, showcasing how DI promotes code reuse through proper component design.</p><p>After refactoring our application to use the MyHomeViewModel and the CounterRepository for handling the counter value, the project structure now looks like this:</p><pre>flutter_demo/<br>└── lib/<br>    ├── main.dart                                (DI setup and entry point)<br>    └── src/<br>        ├── data/<br>        │   ├── repositories/<br>        │   │   └── counter_repository.dart      (Manages counter state)<br>        │   └── services/<br>        │       └── database.dart                (Simulated database service)<br>        └── features/<br>            ├── app/<br>            │   └── my_app.dart                  (MyApp and MyAppFactory)<br>            └── home/<br>                ├── my_home_page.dart            (MyHomePage UI component)<br>                └── my_home_page_view_model.dart (Home state management)</pre><h4>Making MyHomePage Injectable</h4><p>To make our home page injectable, we create a factory that allows the DI system to instantiate it:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:inject_annotation/inject_annotation.dart&#39;;<br><br>/// Factory to create the [MyHomePage] widget with its dependencies.<br>@assistedFactory<br>abstract class MyHomePageFactory {<br>  MyHomePage create({Key? key, required String title});<br>}<br><br>/// The home page of the application with a simple counter.<br>class MyHomePage extends StatelessWidget {<br>  @assistedInject<br>  const MyHomePage({<br>    @assisted super.key,<br>    @assisted required this.title,<br>  });<br><br>// Widget implementation...<br>}</pre><ol><li>We’ve created a factory (MyHomePageFactory) that allows the DI system to create instances of MyHomePage with all dependencies properly injected.</li><li>We use @assistedInject to mark the constructor as an injection point, while marking runtime parameters like key and title with @assisted.</li><li>Notice that we also changed it to be a StatelessWidget instead of a StatefulWidget. When we later add the view model, we&#39;ll see how we use the view model to manage the state of the widget.</li></ol><h4>Connecting MyHomePage to MyApp</h4><p>In the MyApp widget, we inject the MyHomePageFactory and use it to create the home page:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:inject_annotation/inject_annotation.dart&#39;;<br><br>import &#39;../home/my_home_page.dart&#39;;<br><br>/// Factory to create the [MyApp] widget with the [MyHomePageFactory] injected.<br>@assistedFactory<br>abstract class MyAppFactory {<br>  MyApp create({Key? key});<br>}<br><br>/// The root widget of the application.<br>/// The [MyHomePageFactory] is injected into the widget at compile-time.<br>class MyApp extends StatelessWidget {<br>  @assistedInject<br>  const MyApp({<br>    @assisted super.key,<br>    required this.homePageFactory,<br>  });<br><br>  final MyHomePageFactory homePageFactory;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Flutter Demo&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>        useMaterial3: true,<br>      ),<br>      home: homePageFactory.create(title: &#39;Flutter Demo Home Page&#39;),<br>    );<br>  }<br>}</pre><p>This structure creates a clean dependency chain:</p><ol><li>The MyApp widget depends on MyHomePageFactory (injected)</li><li>The homePageFactory.create() method is called to instantiate the home page</li></ol><p>This approach demonstrates nested widget creation through dependency injection, allowing each component to receive its required dependencies.</p><p>By using factories, we ensure proper dependency injection throughout our widget tree while still allowing for runtime parameters like title and key. This approach gives us the best of both worlds: compile-time dependency injection with runtime flexibility.</p><h3>Adding State Management with View Model</h3><p>Now that we have our basic widget structure with dependency injection, we need to implement state management. We’ll use a view model approach that provides a clean separation between UI and business logic.</p><h4>Creating the View Model</h4><p>First, let’s create a view model class that handles the state and business logic for our counter feature:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:inject_annotation/inject_annotation.dart&#39;;<br><br>import &#39;../../data/repositories/counter_repository.dart&#39;;<br>import &#39;my_home_page.dart&#39;;<br><br>/// The view model for the [MyHomePage] widget.<br>@inject<br>class MyHomePageViewModel extends ChangeNotifier {<br>  MyHomePageViewModel({required CounterRepository repository})<br>      : _repository = repository;<br><br>  final CounterRepository _repository;<br><br>  int count = 0;<br><br>  Future&lt;void&gt; increaseCount() async {<br>    await _repository.increaseCount();<br>    count = await _repository.count;<br>    notifyListeners();<br>  }<br>}</pre><p>The view model has these important characteristics:</p><ol><li>It’s marked with @inject so it can be created by the DI system</li><li>It extends ChangeNotifier to provide change notifications to the UI</li><li>It depends on CounterRepository, which is injected through its constructor</li><li>It manages state (the count variable) and provides a method to update it</li><li>It calls notifyListeners() when the state changes to trigger UI updates</li></ol><p>This pattern creates a clear separation of concerns:</p><ul><li>The view model handles business logic and state management</li><li>The repository handles data operations</li><li>The UI focuses solely on presentation</li></ul><p>Note the constructor implementation pattern:</p><pre>MyHomePageViewModel({required CounterRepository repository})<br>      : _repository = repository;<br><br>final CounterRepository _repository;</pre><p>Rather than using the more concise this.repository syntax and a public field, we deliberately use a private field with manual assignment to enforce strict encapsulation. This approach provides significant architectural benefits:</p><ol><li><strong>True Encapsulation</strong>: Dependencies like _repository remain truly private. If we use a public field, any component that received the view model could potentially access its repository directly. This would violate the encapsulation principle and make it difficult to change the implementation later without breaking existing code.</li><li><strong>Preventing Dependency Leakage</strong>: When a view model is injected into a UI component, we want to ensure the UI can only access the intended public API. Manual assignment to private fields creates a clear boundary that prevents dependency leakage across architectural layers.</li><li><strong>Layer Isolation</strong>: This pattern supports the principle that each layer should only know about its immediate dependencies. The UI knows about the view model but should have no knowledge of or access to the repositories or services the view model uses.</li></ol><p>This small syntax choice reinforces an important architectural principle: components should expose only what their consumers need and nothing more, maintaining clear boundaries between different layers of the application.</p><h4>Injecting the View Model with ViewModelFactory</h4><p>Now, let’s update our MyHomePage to use this view model with the ViewModelFactory pattern:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:inject_annotation/inject_annotation.dart&#39;;<br>import &#39;package:inject_flutter/inject_flutter.dart&#39;;<br><br>import &#39;my_home_page_view_model.dart&#39;;<br><br>/// Factory to create the [MyHomePage] widget with the [MyHomePageViewModel] injected.<br>@assistedFactory<br>abstract class MyHomePageFactory {<br>  MyHomePage create({Key? key, required String title});<br>}<br><br>/// The home page of the application with a simple counter.<br>/// The [viewModelFactory] is injected into the widget at compile-time, while the<br>/// [key] or [title] can be provided at runtime.<br>class MyHomePage extends StatelessWidget {<br>  @assistedInject<br>  const MyHomePage({<br>    @assisted super.key,<br>    @assisted required this.title,<br>    required this.viewModelFactory,<br>  });<br><br>  final String title;<br>  final ViewModelFactory&lt;MyHomePageViewModel&gt; viewModelFactory;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return viewModelFactory(<br>      builder: (context, viewModel, _) {<br>        return Scaffold(<br>          appBar: AppBar(<br>            backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>            title: Text(title),<br>          ),<br>          body: Center(<br>            child: Column(<br>              mainAxisAlignment: MainAxisAlignment.center,<br>              children: &lt;Widget&gt;[<br>                const Text(<br>                  &#39;You have pushed the button this many times:&#39;,<br>                ),<br>                Text(<br>                  &#39;${viewModel.count}&#39;,<br>                  style: Theme.of(context).textTheme.headlineMedium,<br>                ),<br>              ],<br>            ),<br>          ),<br>          floatingActionButton: FloatingActionButton(<br>            onPressed: viewModel.increaseCount,<br>            tooltip: &#39;Increment&#39;,<br>            child: const Icon(Icons.add),<br>          ),<br>        );<br>      },<br>    );<br>  }<br>}</pre><h4>How ViewModelFactory Works</h4><p>The ViewModelFactory&lt;T&gt; is a typedef for a function that returns a ViewModelBuilder&lt;T&gt;:</p><pre>typedef ViewModelFactory&lt;T extends ChangeNotifier&gt; = ViewModelBuilder&lt;T&gt; Function({<br>   Key? key,<br>   required ViewModelWidgetBuilder&lt;T&gt; builder,<br>   Widget? child,<br>});</pre><p>When you call this function in the build method, it:</p><ol><li><strong>Creates a ViewModelBuilder</strong>: This StatefulWidget handles the view model lifecycle</li><li><strong>Passes Your Builder Function</strong>: Your UI-building logic receives the view model instance</li><li><strong>Manages View Model Creation</strong>: The view model is created when the ViewModelBuilder first builds</li><li><strong>Handles View Model Disposal</strong>: When the ViewModelBuilder is disposed, it disposes the view model</li></ol><p>The builder function pattern provides a clean way to access the view model’s state and methods inside your UI code. By using this approach:</p><ol><li>The UI reacts to changes in the view model automatically</li><li>Business logic stays in the view model</li><li>The widget remains a simple StatelessWidget</li><li>Lifecycle management happens behind the scenes</li></ol><p>This creates a maintainable architecture where each component has a clear responsibility.</p><h3>Data Layer: Repository and Database</h3><p>Let’s explore how we implement dependency injection for our data layer components.</p><h4>The Repository Pattern</h4><p>Our CounterRepository acts as a mediator between the UI layer and the data storage:</p><pre>import &#39;package:inject_annotation/inject_annotation.dart&#39;;<br><br>import &#39;../services/database.dart&#39;;<br><br>/// Repository to manage the counter value.<br>/// Uses the [Database] to persist the counter value.<br>@inject<br>@singleton<br>class CounterRepository {<br>  CounterRepository({required Database database}) : _database = database;<br><br>  final Database _database;<br><br>  Future&lt;int&gt; get count async =&gt; _database.selectCount();<br><br>  Future&lt;void&gt; increaseCount() async {<br>    final count = await _database.selectCount();<br>    await _database.updateCount(count + 1);<br>  }<br>}</pre><p>Notice the @singleton annotation - this tells our DI system to create only one instance of the repository throughout the application. This is crucial because:</p><ol><li>We want a single source of truth for data operations</li><li>It ensures consistent state management across the application</li><li>It avoids redundant database connections</li></ol><p>The repository depends on the Database, which is injected through its constructor. This creates a clean separation between data access logic and storage implementation.</p><h4>Providing the Database Through a Module</h4><p>Since we are using a database from a third-party library that we cannot annotate with @inject, we use a module to provide it:</p><pre>import &#39;package:inject_annotation/inject_annotation.dart&#39;;<br><br>/// Module to provide the database instance.<br>/// Modules are used to provide instances of classes from 3rd party libraries<br>/// that can&#39;t be annotated with [inject].<br>@module<br>class DataBaseModule {<br>  @provides<br>  @singleton<br>  Database provideDatabase() =&gt; Database();<br>}<br><br>/// Simulates a 3rd party database library for demonstration purposes.<br>///<br>/// This class mimics what you might find in an actual database package<br>/// like Drift, Isar, or Hive, but with simplified functionality to focus<br>/// on dependency injection concepts. In a real app, you would replace this<br>/// with an actual database implementation.<br>///<br>/// Usage example:<br>/// ```dart<br>/// final db = Database();<br>/// await db.updateCount(5);<br>/// final value = await db.selectCount(); // Returns 5<br>/// ```<br>class Database {<br>  /// In-memory storage for the counter value.<br>  /// In a real database, this would be persisted to disk.<br>  int _count = 0;<br><br>  /// Simulates updating a record in the database.<br>  ///<br>  /// In a real database, this would write to persistent storage.<br>  Future&lt;void&gt; updateCount(int count) async {<br>    _count = count;<br>  }<br><br>  /// Simulates reading a record from the database.<br>  ///<br>  /// In a real database, this would fetch data from persistent storage.<br>  Future&lt;int&gt; selectCount() {<br>    return Future.value(_count);<br>  }<br>}</pre><p>The @module annotation defines a class that provides dependencies. The @provides method tells inject.dart how to create an instance of the Database class. By adding the @singleton annotation, we ensure only one database instance exists in our application.</p><p>This approach demonstrates how to integrate third-party libraries into your dependency injection system, even when you can’t modify their source code.</p><h4>View Models: Why They’re Not Singletons</h4><p>In contrast to the repository and database, view models are deliberately <strong>not</strong> marked as singletons. This is an important architectural decision:</p><ol><li><strong>Lifecycle Alignment</strong>: Each view should have its own view model instance that matches its lifecycle</li><li><strong>State Isolation</strong>: Different instances of the same view should have isolated state</li><li><strong>Memory Efficiency</strong>: View models can be garbage collected when their associated view is disposed</li></ol><p>If view models were singletons, all instances of a view would share the same state, creating unexpected behavior and potential memory leaks. By making each view model instance-specific while keeping the data layer as singletons, we create a clean hierarchy where stable infrastructure is shared while UI state remains isolated.</p><p>This pattern demonstrates a key strength of dependency injection: the ability to configure different scopes for different types of components in your application.</p><h3>Conclusion</h3><p>In this chapter, we’ve explored how dependency injection naturally complements state management in Flutter applications. By separating our application into clean layers — UI components, view models, repositories, and services — we’ve created a maintainable architecture that’s both flexible and testable.</p><p>The key principles we’ve covered include:</p><ol><li>Using dependency injection to provide state management services</li><li>Creating a clear separation between UI and business logic</li><li>Implementing proper lifecycle management with ViewModelFactory</li><li>Leveraging singletons for shared infrastructure like repositories and databases</li></ol><h4>Complete Example</h4><p>You can find the complete source code for all examples in this chapter in the <a href="https://github.com/ralph-bergmann/inject.dart/tree/master/examples/flutter_demo">examples/flutter_demo</a> folder of the inject.dart repository. This working implementation demonstrates all the patterns and practices we&#39;ve discussed.</p><h4>Coming Next: Testing with Dependency Injection</h4><p>In the <a href="https://ralph-bergmann.github.io/inject.dart/chapter_5_testing_with_di.html">next chapter</a>, we’ll explore one of the most powerful benefits of our architecture: testability. We’ll show how to create a separate dependency graph for unit testing that allows us to:</p><ol><li>Test view models by injecting a FakeCounterRepository</li><li>Test repositories with a FakeDatabase implementation</li></ol><p>This testing approach demonstrates how dependency injection doesn’t just make your code more maintainable — it makes it substantially easier to verify and validate your application’s behavior through automated testing.</p><p>By separating concerns and making dependencies explicit, we’ve built a foundation that will continue to pay dividends as your application grows in complexity.</p><p><a href="https://ralph-bergmann.github.io/inject.dart/">inject.dart Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=906627b7db77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to install Kubernetes on Raspberry PI]]></title>
            <link>https://medium.com/karlmax-berlin/how-to-install-kubernetes-on-raspberry-pi-53b4ce300b58?source=rss-cc6093afa421------2</link>
            <guid isPermaLink="false">https://medium.com/p/53b4ce300b58</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Ralph Bergmann]]></dc:creator>
            <pubDate>Fri, 09 Sep 2022 13:10:29 GMT</pubDate>
            <atom:updated>2023-04-26T08:30:07.847Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial (it is more of a step-by-step guide than an article), I will show you how you can install Kubernetes on a Raspberry PI 4 cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJ-IPcJvGv0SmuMGIgU3vw.png" /></figure><h3>Install Raspberry PI OS on each Raspberry</h3><p>First of all, you need to install the OS on each Raspberry. Use the <a href="https://www.raspberrypi.com/software/">Raspberry Pi Imager</a> to write the image on an SD Card.</p><figure><img alt="Raspberry Pi Imager" src="https://cdn-images-1.medium.com/max/680/1*PikUtTmz_usW5bVF_hrLSA.png" /></figure><p>Click the CHOOSE OS button and select Raspberry PI OS Lite (64-bit) from the Raspberry PI OS (other) section.</p><figure><img alt="select Raspberry PI OS Lite (64-bit)" src="https://cdn-images-1.medium.com/max/680/1*UUA-wIaZuN034T8A7ePMOQ.png" /></figure><p>In the Advanced options (the gear icon/button) set the hostname and your username, enable SSH and click SAVE.</p><figure><img alt="settings menu" src="https://cdn-images-1.medium.com/max/680/1*2Pu098NONJQ5xbkOVP9dLg.png" /></figure><p>Now insert the SD Card into a card reader, choose it and write the image.</p><p>Repeat these steps for all SD Cards, but <strong>choose a different hostname</strong> for each one. When you are done with all SD Cards, insert them into the Raspberry PIs and boot them.</p><blockquote><strong>You must perform the following steps on all Raspberry PIs you want to add to your cluster.</strong></blockquote><blockquote>I wrote an <a href="https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html">Ansible Playbook</a> for the following steps. Scroll down to see how to run it and save some time.</blockquote><h3>Update the OS</h3><p>Before we install Kubernetes, we need to update the OS. To do so, login into each Raspberry via SSH and run the following command:</p><pre>$ sudo apt update -y &amp;&amp; sudo apt dist-upgrade -y</pre><p>Sometimes you get a new Kernel, so rebooting the Raspberry is a good idea.</p><pre>$ sudo reboot</pre><h3>Add cgroup flags</h3><p>Add cgroup_enable=cpuset cgroup_enable=memory cgroup_memory=1 to the end of the /boot/cmdline.txt file. <em>The content of this file is one line without any line breaks.</em></p><pre>$ echo &quot; cgroup_enable=cpuset cgroup_enable=memory cgroup_memory=1&quot; | sudo tee -a  /boot/cmdline.txt</pre><h3>Disable and uninstall swap</h3><p>Run the following commands to disable and uninstall the swap file:</p><pre>$ sudo dphys-swapfile swapoff<br>$ sudo dphys-swapfile uninstall<br>$ sudo apt purge -y dphys-swapfile<br>$ sudo apt autoremove -y</pre><p>You can test that swap has been disabled with free -m.</p><figure><img alt="swap disabled" src="https://cdn-images-1.medium.com/max/1015/1*DGTbDFliPLBQ6cVDzmrTxQ.png" /></figure><h3>Install and set up the Container Runtime</h3><blockquote>See also <a href="https://kubernetes.io/docs/setup/production-environment/container-runtimes/">Container Runtimes in the Kubernetes Documentation</a></blockquote><h4>Install containerd</h4><pre>$ sudo apt install -y containerd containernetworking-plugins</pre><h4>Set up containerd with cgroup</h4><blockquote>See also <a href="https://github.com/containerd/containerd/issues/4203#issuecomment-651532765">https://github.com/containerd/containerd/issues/4203#issuecomment-651532765</a></blockquote><p>Replace the content of /etc/containerd/config.toml:</p><pre>$ cat &lt;&lt;EOF | sudo tee /etc/containerd/config.toml<br>version = 2<br>[plugins]<br>  [plugins.&quot;io.containerd.grpc.v1.cri&quot;]<br>    [plugins.&quot;io.containerd.grpc.v1.cri&quot;.containerd]<br>      [plugins.&quot;io.containerd.grpc.v1.cri&quot;.containerd.runtimes]<br>        [plugins.&quot;io.containerd.grpc.v1.cri&quot;.containerd.runtimes.runc]<br>          runtime_type = &quot;io.containerd.runc.v2&quot;<br>          [plugins.&quot;io.containerd.grpc.v1.cri&quot;.containerd.runtimes.runc.options]<br>            SystemdCgroup = true<br>EOF</pre><figure><img alt="/etc/containerd/config.toml" src="https://cdn-images-1.medium.com/max/1015/1*Od5pRaTY0F39DDfdJRr3_w.png" /></figure><h3>Forwarding IPv4 and letting iptables see bridged traffic</h3><blockquote>See also <a href="https://kubernetes.io/docs/setup/production-environment/container-runtimes/#forwarding-ipv4-and-letting-iptables-see-bridged-traffic">Forwarding IPv4 and letting iptables see bridged traffic</a></blockquote><pre>$ cat &lt;&lt;EOF | sudo tee /etc/modules-load.d/k8s.conf<br>overlay<br>br_netfilter<br>EOF<br> <br>$ sudo modprobe overlay<br>$ sudo modprobe br_netfilter<br> <br>$ cat &lt;&lt;EOF | sudo tee /etc/sysctl.d/k8s.conf<br>net.bridge.bridge-nf-call-iptables  = 1<br>net.bridge.bridge-nf-call-ip6tables = 1<br>net.ipv4.ip_forward                 = 1<br>EOF<br>$ sudo sysctl --system</pre><h3>Install kubeadm</h3><blockquote>See also <a href="https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/install-kubeadm/">Installing kubeadm</a></blockquote><pre>$ sudo apt update<br>$ sudo apt install -y apt-transport-https ca-certificates curl<br><br>// Download the Google Cloud public signing key:<br>$ sudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg<br><br>// Add the Kubernetes apt repository:<br>$ echo &quot;deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main&quot; | sudo tee /etc/apt/sources.list.d/kubernetes.list<br><br>// Update `apt` package index, install kubelet, kubeadm and kubectl, and pin their version:<br>$ sudo apt update<br>$ sudo apt install -y kubelet kubeadm kubectl<br>$ sudo apt-mark hold kubelet kubeadm kubectl</pre><h3>Install Cluster Networking</h3><blockquote><a href="https://github.com/flannel-io/flannel">Flannel</a> is a simple and easy way to configure a layer 3 network fabric designed for Kubernetes. (<a href="https://github.com/flannel-io/flannel#flannel">Flannel</a>)</blockquote><pre>$ wget https://github.com/flannel-io/flannel/releases/download/v0.19.2/flanneld-arm64<br>$ sudo chmod +x flanneld-arm64<br>$ sudo cp flanneld-arm64 /usr/local/bin/flanneld<br>$ sudo mkdir -p /var/lib/k8s/flannel/networks</pre><p>In a later step, we will add Flannel to the cluster.</p><h3>Ansible for lazy people</h3><blockquote><a href="https://www.ansible.com/">Ansible</a> is an IT automation tool. It can configure systems, deploy software, and orchestrate more advanced IT tasks such as continuous deployments or zero downtime rolling updates. (<a href="https://docs.ansible.com/ansible/latest/index.html#about-ansible">Ansible Documentation</a>)</blockquote><p>I wrote an <a href="https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html#intro-to-playbooks">Ansible Playbook</a> to automate all the steps above. To run the playbook, you first need to <a href="https://docs.ansible.com/ansible/latest/installation_guide/index.html">install Ansible</a>. On macOS, you can install it with <a href="https://formulae.brew.sh/formula/ansible">brew install ansible</a> (what I did). You also need an <a href="https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html#how-to-build-your-inventory">inventory</a>. Mine looks like this:</p><pre>[raspis]<br>10.0.0.[11:14]<br><br>[raspis:vars]<br>ansible_user=ralph<br><br>[k8s_main]<br>10.0.0.11<br><br>[k8s_worker]<br>10.0.0.[12:14]</pre><p>The playbook uses the IP addresses from the raspis group to run all the tasks on these hosts.</p><pre>---<br>- name: Playbook to install the necessary things to run k8s on Raspberry PIs<br>  hosts: raspis<br>  become: yes<br>  gather_facts: no<br>  tasks:<br>    - name: Update repositories cache and upgrade system<br>      ansible.builtin.apt:<br>        update_cache: yes<br>        upgrade: dist<br>        cache_valid_time: 3600<br>        autoclean: yes<br>        autoremove: yes<br><br>    - name: Check if a reboot is needed<br>      register: reboot_required_file<br>      stat:<br>        path: /var/run/reboot-required<br>        get_md5: no<br><br>    - name: Reboot if needed<br>      ansible.builtin.reboot:<br>        msg: &quot;Reboot initiated by Ansible for kernel updates&quot;<br>        connect_timeout: 5<br>        reboot_timeout: 300<br>        pre_reboot_delay: 0<br>        post_reboot_delay: 30<br>        test_command: uptime<br>      when: reboot_required_file.stat.exists<br><br>    - name: Install vim and aptitude<br>      ansible.builtin.apt:<br>        pkg:<br>          - vim<br>          - aptitude<br><br>    - name: Create Aptitude config directory<br>      ansible.builtin.file:<br>        path: /root/.aptitude/<br>        state: directory<br>        recurse: yes<br>        owner: root<br>        group: root<br>        mode: &#39;0700&#39;<br><br>    - name: Configure Aptitude<br>      ansible.builtin.copy:<br>        content: |<br>          aptitude &quot;&quot;;<br>          aptitude::Keep-Unused-Pattern &quot;&quot;;<br>          aptitude::Delete-Unused-Pattern &quot;&quot;;<br>          aptitude::UI &quot;&quot;;<br>          aptitude::UI::Prompt-On-Exit &quot;false&quot;;<br>          aptitude::UI::Default-Grouping &quot;task,status&quot;;<br>          aptitude::AutoClean-After-Update &quot;true&quot;;<br>          aptitude::Clean-After-Install &quot;true&quot;;<br>          aptitude::Forget-New-On-Update &quot;true&quot;;<br>        dest: /root/.aptitude/config<br>        backup: yes<br>        owner: root<br>        group: root<br>        mode: &#39;0644&#39;<br><br>    - name: Modify ls alias<br>      ansible.builtin.lineinfile:<br>        path: /home/ralph/.bashrc<br>        backup: yes<br>        regexp: &#39;^    alias ls=&#39;&#39;ls --color=auto&#39;&#39;$&#39;<br>        line: &#39;    alias ls=&#39;&#39;ls --color=auto -lahpG&#39;&#39;&#39;<br><br><br>    # disable swap<br><br>    - name: Check whether a package called dphys-swapfile is installed<br>      ansible.builtin.package_facts:<br>        manager: auto<br><br>    - name: Turn off &quot;dphys-swapfile&quot;<br>      ansible.builtin.command: dphys-swapfile swapoff<br>      when: &quot;&#39;dphys-swapfile&#39; in ansible_facts.packages&quot;<br><br>    - name: Uninstall &quot;dphys-swapfile&quot;<br>      ansible.builtin.command: dphys-swapfile uninstall<br>      when: &quot;&#39;dphys-swapfile&#39; in ansible_facts.packages&quot;<br><br>    - name: Remove and purge &quot;dphys-swapfile&quot; package<br>      ansible.builtin.apt:<br>        pkg: dphys-swapfile<br>        state: absent<br>        purge: yes<br>        autoclean: yes<br>        autoremove: yes<br>      when: &quot;&#39;dphys-swapfile&#39; in ansible_facts.packages&quot;<br><br><br>    # Configure cgroup<br><br>    - name: Enable cgroup in /boot/cmdline.txt<br>      ansible.builtin.lineinfile:<br>        path: /boot/cmdline.txt<br>        backrefs: yes<br>        regexp: &#39;^console(.*) rootwait$&#39;<br>        line: &#39;\g&lt;0&gt; cgroup_enable=cpuset cgroup_enable=memory cgroup_memory=1&#39;<br><br><br>    # Install and configure Container Runtime<br><br>    - name: Install Container Runtime<br>      ansible.builtin.apt:<br>        pkg:<br>          - containerd<br>          - containernetworking-plugins<br><br>    - name: Configure containerd<br>      ansible.builtin.copy:<br>        content: |<br>          version = 2<br>          [plugins]<br>            [plugins.&quot;io.containerd.grpc.v1.cri&quot;]<br>              [plugins.&quot;io.containerd.grpc.v1.cri&quot;.containerd]<br>                [plugins.&quot;io.containerd.grpc.v1.cri&quot;.containerd.runtimes]<br>                  [plugins.&quot;io.containerd.grpc.v1.cri&quot;.containerd.runtimes.runc]<br>                    runtime_type = &quot;io.containerd.runc.v2&quot;<br>                    [plugins.&quot;io.containerd.grpc.v1.cri&quot;.containerd.runtimes.runc.options]<br>                      SystemdCgroup = true<br>        dest: /etc/containerd/config.toml<br>        backup: yes<br>        owner: root<br>        group: root<br>        mode: &#39;0644&#39;<br><br><br>    # Forwarding IPv4 and letting iptables see bridged traffic<br><br>    - name: create /etc/modules-load.d/k8s.conf<br>      ansible.builtin.copy:<br>        content: |<br>          overlay<br>          br_netfilter<br>        dest: /etc/modules-load.d/k8s.conf<br>        backup: yes<br>        owner: root<br>        group: root<br>        mode: &#39;0644&#39;<br><br>    - name: modprobe overlay<br>      ansible.builtin.command: modprobe overlay<br><br>    - name: modprobe br_netfilter<br>      ansible.builtin.command: modprobe br_netfilter<br><br>    - name: Create /etc/sysctl.d/k8s.conf<br>      ansible.builtin.copy:<br>        content: |<br>          net.bridge.bridge-nf-call-iptables  = 1<br>          net.bridge.bridge-nf-call-ip6tables = 1<br>          net.ipv4.ip_forward                 = 1<br>        dest: /etc/sysctl.d/k8s.conf<br>        backup: yes<br>        owner: root<br>        group: root<br>        mode: &#39;0644&#39;<br><br>    - name: sysctl --system<br>      ansible.builtin.command: sysctl --system<br><br><br>    # Install kubeadm<br><br>    - name: Install apt-transport-https ca-certificates<br>      ansible.builtin.apt:<br>        pkg:<br>          - apt-transport-https<br>          - ca-certificates<br>          - curl<br><br>    - name: Download the Google Cloud public signing key<br>      ansible.builtin.get_url:<br>        url: https://packages.cloud.google.com/apt/doc/apt-key.gpg<br>        dest: /usr/share/keyrings/kubernetes-archive-keyring.gpg<br>        owner: root<br>        group: root<br>        mode: &#39;0644&#39;<br><br>    - name: Add the Kubernetes apt repository<br>      ansible.builtin.apt_repository:<br>        repo: &quot;deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main&quot;<br>        state: present<br>        filename: kubernetes<br>        update_cache: yes<br><br>    - name: Install kubelet kubeadm kubectl<br>      ansible.builtin.apt:<br>        pkg:<br>          - kubelet<br>          - kubeadm<br>          - kubectl<br><br>    - name: Hold kubelet<br>      dpkg_selections:<br>        name: kubelet<br>        selection: hold<br><br>    - name: Hold kubeadm<br>      dpkg_selections:<br>        name: kubeadm<br>        selection: hold<br><br>    - name: Hold kubectl<br>      dpkg_selections:<br>        name: kubectl<br>        selection: hold<br><br><br>    # Download and install Flannel<br><br>    - name: Download and install Flannel<br>      ansible.builtin.get_url:<br>        url: https://github.com/flannel-io/flannel/releases/download/v0.19.2/flanneld-arm64<br>        dest: /usr/local/bin/flanneld<br>        owner: root<br>        group: root<br>        mode: &#39;0755&#39;<br><br>    - name: Create Flannel networks directory<br>      ansible.builtin.file:<br>        path: /var/lib/k8s/flannel/networks<br>        state: directory<br>        recurse: yes<br>        owner: root<br>        group: root<br>        mode: &#39;0755&#39;<br><br><br>    # reboot<br><br>    - name: reboot<br>      reboot:</pre><p>You can then run the playbook:</p><pre>$ ansible-playbook &lt;filename&gt;.yaml</pre><blockquote><strong>Perform the following steps only on the main host in your cluster.</strong></blockquote><h3>Initialize the Kubernetes cluster</h3><pre>$ sudo kubeadm init --pod-network-cidr=10.244.0.0/16</pre><p>I found nothing about the pod-network-cidr parameter and what IP address it needs to be…. but it works so far.</p><figure><img alt="kubeadm init" src="https://cdn-images-1.medium.com/max/1024/1*T_1JNOmp0LmKJRRPZaEdUg.png" /></figure><p>In the log, you will see a kubeadm join command. Save it in a secure space. You need it later to let the hosts join your cluster. But everyone with this command and internet access to your cluster can also join the cluster with this command.</p><p>Copy the Kubernetes config into your home directory:</p><pre>$ mkdir -p $HOME/.kube<br>$ sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config<br>$ sudo chown $(id -u):$(id -g) $HOME/.kube/config</pre><h3>Add Flannel to the cluster</h3><pre>$ kubectl apply -f https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml</pre><h3>Install MetalLB (External LoadBalancer)</h3><blockquote><a href="https://metallb.universe.tf/">MetalLB</a> hooks into your Kubernetes cluster, and provides a network load-balancer implementation. In short, it allows you to create Kubernetes services of type LoadBalancer in clusters that don’t run on a cloud provider, and thus cannot simply hook into paid products to provide load balancers. (<a href="https://metallb.universe.tf/concepts/">MetalLB</a>)</blockquote><p>In short: you need it to access the pods in your cluster from outside.</p><h4>Add MetalLB to the cluster</h4><pre>$ kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.12.1/manifests/namespace.yaml<br>$ kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.12.1/manifests/metallb.yaml</pre><h4>Configure MetalLB</h4><pre>$ cat &lt;&lt;EOF | kubectl apply -f -<br>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  namespace: metallb-system<br>  name: config<br>data:<br>  config: |<br>    address-pools:<br>    - name: default<br>      protocol: layer2<br>      addresses:<br>      - 10.0.0.200-10.0.0.250<br>---<br>EOF</pre><p>The addresses must be from the range of your local network. You must also reserve these IP addresses so that your DHCP server can’t assign them to other clients in your network.</p><h3>Mostly done: add the hosts to the cluster</h3><p>Now it’s time to add the hosts to the cluster. On each host run the kubeadm join command you got earlier.</p><figure><img alt="add hosts to the cluster" src="https://cdn-images-1.medium.com/max/1024/1*efQP1HIbQ9yOVfbzsnOiDA.png" /></figure><p>kubectl get nodes -o wide shows all hosts in your cluster</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeVZVH20lcnPAAsZ1vKzYg.png" /></figure><p>You are now done. The cluster is set up, and you can start using it.</p><h3>A simple test</h3><p>Install a small and straightforward pod to test the cluster. The pod does nothing more than respond immediately with ping? pong!</p><pre>$ cat &lt;&lt;EOF | kubectl apply -f -<br>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: ping<br>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: ping<br>  namespace: ping<br>  labels:<br>    app: ping<br>spec:<br>  selector:<br>    matchLabels:<br>      app: ping<br>  replicas: 2<br>  template:<br>    metadata:<br>      labels:<br>        app: ping<br>    spec:<br>      containers:<br>        - name: ping<br>          image: dasralph/ping:arm64_0.0.5<br>          ports:<br>            - containerPort: 8080<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: ping<br>  namespace: ping<br>  labels:<br>    app: ping<br>spec:<br>  type: LoadBalancer<br>  selector:<br>    app: ping<br>  ports:<br>    - port: 80<br>      targetPort: 8080<br>      protocol: TCP<br>---<br>EOF</pre><p>The script installs the pod two times and creates a service for that. Your cluster should now look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEYvXpHuHElvawbc70d1pw.png" /></figure><p>The ping service got an EXTERNAL IP, in this case 10.0.0.200. You can invoke the ping service with curl 10.0.0.200/ping -v. It will also return the IP address of the pod that responded to your request. You will get different IP addresses if you call the curl command repeatedly. This means that not always the same pod responds to your request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rYWIlstlAZWoM_3lA3aw2g.png" /></figure><p>If you want, you can delete the whole ping service with all of its pods with:</p><pre>$ kubectl delete namespace ping</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53b4ce300b58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/karlmax-berlin/how-to-install-kubernetes-on-raspberry-pi-53b4ce300b58">How to install Kubernetes on Raspberry PI</a> was originally published in <a href="https://medium.com/karlmax-berlin">Karlmax Berlin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sub-modules for Xcode]]></title>
            <link>https://medium.com/karlmax-berlin/sub-modules-for-xcode-acb6b1e5f567?source=rss-cc6093afa421------2</link>
            <guid isPermaLink="false">https://medium.com/p/acb6b1e5f567</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[submodules]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Ralph Bergmann]]></dc:creator>
            <pubDate>Mon, 01 Feb 2021 00:26:33 GMT</pubDate>
            <atom:updated>2023-05-05T09:06:23.984Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been developing software for around 20 years — sometimes for myself, but mostly for clients. For me, it’s much more than a job: it’s fun to solve a problem with elegant and beautiful code. And, of course, you sleep so much better when it’s also maintainable, testable, and reusable — all those fancy buzzwords!</p><p>However, over any project&#39;s lifespan, the development team usually changes. Your client might ask for new features, while libraries are often updated or become deprecated. To carry out these maintenance tasks, a good project architecture is vital. Otherwise, you spend too much time troubleshooting tasks. When the budget runs out, both you and your boss will be frustrated — your client, too, when you don’t make the deadline.</p><p>As a good developer, you will be familiar with <a href="https://twitter.com/unclebobmartin">Uncle Bob</a>’s <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Clean Architecture</a>. In short, this architecture involves splitting your code into modules.</p><p>For Android developers, splitting the project into sub-modules is such a simple task — just ask Android Studio (or IntelliJ IDEA, I’m not sure if other IDEs also have such a feature) to <a href="https://developer.android.com/studio/projects/add-app-module">create a sub-module</a>.</p><p>But how do you split an Xcode project into modules? Well, that’s exactly what I’m going to show you here.</p><h3><strong>Let’s start</strong></h3><p>Open Xcode and create a new, empty workspace. You can’t do this from the Xcode Welcome screen, but you can use the ⌃ ⌘ N (control + command + n) shortcut. Create a new empty folder and call it modules. You can choose a different name, but for this article, I will use modules.</p><p>Add a new project to this workspace with ⇧ ⌘ N (shift + command + n). In the opening dialog, select the iOS App template and call it main.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*vRqspmlQs51jqQ3lXUWd1Q@2x.png" /></figure><p>Make sure you create it in the modules folder and also choose to add it to the app workspace and app group.</p><p>Add another new project, but now select the iOS Framework template and call it core. Create this in the modules folder too and also add it to the app workspace and app group.</p><p>Your folder structure should now look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*JMI3Nevakm-aWnYDEva2RA@2x.png" /></figure><h3><strong>Link it together</strong></h3><p>It’s now time to link the core project/module into the main project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnaAOMrM_ikVM-SCHjLm9w@2x.png" /></figure><p>Select the main target of the main project and drag and drop the core.framework into the Frameworks, Libraries, and Embedded Content section.</p><h3>A simple test</h3><p>To test it, create a new Swift File (⌘ N) in the core project with this simple method:</p><pre>import Foundation<br><br>public func name() -&gt; String {<br>    return &quot;Ralph&quot;<br>}<br>@ralph-bergmann</pre><p>In the main project, change the ContentView.swift. Add the import core statement and call the name() method:</p><pre>import SwiftUI<br>import core<br><br>struct ContentView: View {<br>    var body: some View {<br>        Text(&quot;Hello, \(name())!&quot;).padding()<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*qW9n5JhIEBRDIbQR0U4yHg@2x.png" /></figure><p>Xcode may display an error regarding the minimum deployment target. To fix this, change it to 13.0 in both main and core projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*if8SSy6Vr0NlsxDaQyx0sQ@2x.png" /></figure><h3>Add dependencies</h3><p>Right now, I’m using <a href="https://cocoapods.org/">CocoaPods</a> for dependency management because I’m not so familiar with <a href="https://developer.apple.com/documentation/swift_packages">Swift Packages</a>.</p><p>In the modules folder, create a Podfile file with this content and call pod install.</p><pre>workspace &#39;app.xcworkspace&#39;<br>platform :ios, &#39;13.0&#39;<br>use_frameworks!<br><br>def core_pods<br>  pod &#39;SwiftDate&#39;, &#39;~&gt; 6.3.1&#39;<br>end<br><br>def main_pods<br>  # add pods for the main target here<br>end<br><br>target &#39;core&#39; do<br>  project &#39;core/core.xcodeproj&#39;<br>  <br>  core_pods<br>end<br><br>target &#39;main&#39; do<br>  project &#39;main/main.xcodeproj&#39;<br>  <br>  core_pods<br>  main_pods<br>end</pre><p>The pod install command initializes CocoaPods for this workspace (because we haven’t done that so far) and adds the SwiftDate pod as a dependency on the core project.</p><p>We can now use SwiftDate (I only use this to show how to add a dependency). Change the ContentView.swift and Name.swift file in the core project as follows:</p><pre>import SwiftUI<br>import core<br><br>struct ContentView: View {<br>    var body: some View {<br>        Text(&quot;Today in one year is: \(nextYear())&quot;).padding()<br>    }<br>}<br><br>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}</pre><pre>import Foundation<br>import SwiftDate<br><br><br>public func nextYear() -&gt; String {<br>    let nextYear = (Date() + 1.years)<br>    return nextYear.weekdayName(.default)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*Gs_RL_BclisWqvIj6DQ2mg@2x.png" /></figure><h3>Done</h3><p>You can find the complete project at:</p><p><a href="https://github.com/ralph-bergmann/xcode-submodules">GitHub - ralph-bergmann/xcode-submodules</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acb6b1e5f567" width="1" height="1" alt=""><hr><p><a href="https://medium.com/karlmax-berlin/sub-modules-for-xcode-acb6b1e5f567">Sub-modules for Xcode</a> was originally published in <a href="https://medium.com/karlmax-berlin">Karlmax Berlin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Versioning with Flutter]]></title>
            <link>https://medium.com/karlmax-berlin/versioning-with-flutter-299869e68af4?source=rss-cc6093afa421------2</link>
            <guid isPermaLink="false">https://medium.com/p/299869e68af4</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Ralph Bergmann]]></dc:creator>
            <pubDate>Tue, 01 May 2018 10:20:36 GMT</pubDate>
            <atom:updated>2023-05-05T09:17:40.843Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Please note: This is my first article since I left university. So please be patient.<br>2nd note: My Java/Kotlin/Swift/Dart is much better than my English ;-)</blockquote><blockquote><strong>Update January 31th, 2019</strong></blockquote><p>Does it bother you to increase the version in the Android as well as in the iOS part again and again? You can be helped.</p><p>Every time you want to create a new version you have to increase the build number in Android as well as in iOS: You have to modify the app/build.gradle file and the Info.plist file.</p><p>Would it be nice to have just one place to do that?</p><blockquote>T̶h̶e̶ ̶f̶o̶l̶l̶o̶w̶i̶n̶g̶ ̶d̶e̶p̶e̶n̶d̶s̶ ̶o̶n̶ ̶#̶1̶6̶8̶5̶7̶.̶ ̶C̶u̶r̶r̶e̶n̶t̶l̶y̶,̶ ̶i̶t̶ ̶i̶s̶n̶’̶t̶ ̶m̶e̶r̶g̶e̶d̶,̶ ̶s̶o̶ ̶y̶o̶u̶ ̶h̶a̶v̶e̶ ̶t̶o̶ ̶w̶a̶i̶t̶ ̶a̶ ̶l̶i̶t̶t̶l̶e̶ ̶b̶i̶t̶.̶ ̶B̶u̶t̶ ̶a̶s̶ ̶w̶e̶ ̶s̶a̶y̶ ̶i̶n̶ ̶G̶e̶r̶m̶a̶n̶y̶:̶ ̶V̶o̶r̶f̶r̶e̶u̶d̶e̶ ̶i̶s̶t̶ ̶d̶i̶e̶ ̶s̶c̶h̶ö̶n̶s̶t̶e̶ ̶F̶r̶e̶u̶d̶e̶ ̶(̶I̶ ̶h̶a̶t̶ ̶t̶h̶i̶s̶ ̶s̶e̶n̶t̶e̶n̶c̶e̶.̶ ̶P̶a̶r̶e̶n̶t̶s̶ ̶t̶e̶l̶l̶ ̶t̶h̶i̶s̶ ̶t̶o̶ ̶t̶h̶e̶i̶r̶ ̶c̶h̶i̶l̶d̶’̶s̶ ̶b̶e̶f̶o̶r̶e̶ ̶C̶h̶r̶i̶s̶t̶m̶a̶s̶ ̶w̶h̶e̶n̶ ̶t̶h̶e̶ ̶c̶h̶i̶l̶d̶r̶e̶n̶ ̶c̶a̶n̶’̶t̶ ̶w̶a̶i̶t̶ ̶t̶o̶ ̶g̶e̶t̶ ̶t̶h̶e̶ ̶p̶r̶e̶s̶e̶n̶t̶s̶)̶.̶</blockquote><p>O̶k̶a̶y̶,̶ ̶w̶e̶ ̶a̶s̶s̶u̶m̶e̶ ̶i̶t̶ ̶i̶s̶ ̶m̶e̶r̶g̶e̶d̶.̶</p><p>If you create a new Flutter project the pubspec.yaml file has a version property like this:</p><pre>name: hello<br>description: A new Flutter project.<br>version: 1.0.0+1<br>dependencies:<br>  flutter:<br>    sdk: flutter<br>...</pre><p>Flutter uses this value to set the version in both Android and iOS for you. You only need to call flutter run or flutter build or press the play button in IntelliJ / Android Studio / the IDE of your choice.</p><h3>The Format</h3><p>Flutter expects an exact format of the version property.</p><p>It has two parts separated by a +. The first part is the build name (versionName Android / CFBundleShortVersionString iOS), and the second part is the build number (versionCode Android / CFBundleVersion iOS).</p><p>The build name can have up to 3 integers separated by dots. The build number is just one integer.</p><h3>How to modify them?</h3><p>You can still edit the pubspec.yaml file by hand, but sometimes you need a way to modify them automatically, for example, when your CI builds a new version.</p><p>To change the version automatically, you have two options —-build-name and --build-number. These two options are options of the flutter build command:</p><pre>$ flutter build apk --build-name=1.0.3<br>$ flutter build apk --build-number=3<br>$ flutter build apk --build-name=1.0.3 --build-number=3</pre><p>I use <a href="https://fastlane.tools/">Fastlane</a> to do my CI builds. My fastfile looks like this:</p><pre>lane :alphaBuild do<br>  # Return the number of commits in current git branch<br>  build_number = number_of_commits()<br>  Dir.chdir &quot;..&quot; do<br>    sh(&quot;flutter&quot;, &quot;packages&quot;, &quot;get&quot;)<br>    sh(&quot;flutter&quot;, &quot;clean&quot;)<br>    sh(&quot;flutter&quot;, &quot;build&quot;, &quot;apk&quot;, &quot;--build-number=#{build_number}&quot;)<br>  end<br>end</pre><h3>How to update an old Flutter project?</h3><p>You can also do the above with an old Flutter project, but you need to make some changes.</p><h4>Flutter Part</h4><p>All you have to do is to add the version property to your pubspec.yaml file. It should look like this:</p><pre>name: hello<br>description: A new Flutter project.<br>version: 1.0.0+1         # add this<br>dependencies:<br>  flutter:<br>    sdk: flutter<br>...</pre><h4>Android Part</h4><p>Every time you call flutter run or flutter build Flutter updates the local.properties file. You only need to use the values in your app/build.gradle file.</p><p>To do that, modify your app/build.gradle file that it looks like this:</p><pre>def localProperties = new Properties()<br>def localPropertiesFile = rootProject.file(&#39;local.properties&#39;)<br>if (localPropertiesFile.exists()) {<br>    localPropertiesFile.withReader(&#39;UTF-8&#39;) { reader -&gt;<br>        localProperties.load(reader)<br>    }<br>}<br><br>def flutterRoot = localProperties.getProperty(&#39;flutter.sdk&#39;)<br>if (flutterRoot == null) {<br>    throw new GradleException(&quot;Flutter SDK not found. Define location with flutter.sdk in the local.properties file.&quot;)<br>}<br><br>def flutterVersionCode = localProperties.getProperty(&#39;flutter.versionCode&#39;)<br>if (flutterVersionCode == null) {<br>    throw new GradleException(&quot;versionCode not found. Define flutter.versionCode in the local.properties file.&quot;)<br>}<br><br>def flutterVersionName = localProperties.getProperty(&#39;flutter.versionName&#39;)<br>if (flutterVersionName == null) {<br>    throw new GradleException(&quot;versionName not found. Define flutter.versionName in the local.properties file.&quot;)<br>}<br><br>apply plugin: &#39;com.android.application&#39;<br>apply from: &quot;$flutterRoot/packages/flutter_tools/gradle/flutter.gradle&quot;<br><br>android {<br>    compileSdkVersion 27<br><br>    lintOptions {<br>        disable &#39;InvalidPackage&#39;<br>    }<br><br>    defaultConfig {<br>        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).<br>        applicationId &quot;com.example.hello&quot;<br>        minSdkVersion 16<br>        targetSdkVersion 27<br>        versionCode flutterVersionCode.toInteger()<br>        versionName flutterVersionName<br>        testInstrumentationRunner &quot;android.support.test.runner.AndroidJUnitRunner&quot;<br>    }<br><br>    buildTypes {<br>        release {<br>            // TODO: Add your own signing config for the release build.<br>            // Signing with the debug keys for now, so `flutter run --release` works.<br>            signingConfig signingConfigs.debug<br>        }<br>    }<br>}</pre><p>Read the values from the local.properties file (lines 14 to 22) and use them (lines 39 and 40).</p><h4>iOS Part</h4><p>flutter run and flutter build updates the Generated.xcconfig file too, just use its values.</p><p>Change the CFBundleShortVersionString value to $(FLUTTER_BUILD_NAME) (line 18) and the CFBundleVersion value to $(FLUTTER_BUILD_NUMBER) (line 21) in the info.plist file.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>&lt;dict&gt;<br> &lt;key&gt;CFBundleDevelopmentRegion&lt;/key&gt;<br> &lt;string&gt;en&lt;/string&gt;<br> &lt;key&gt;CFBundleExecutable&lt;/key&gt;<br> &lt;string&gt;$(EXECUTABLE_NAME)&lt;/string&gt;<br> &lt;key&gt;CFBundleIdentifier&lt;/key&gt;<br> &lt;string&gt;$(PRODUCT_BUNDLE_IDENTIFIER)&lt;/string&gt;<br> &lt;key&gt;CFBundleInfoDictionaryVersion&lt;/key&gt;<br> &lt;string&gt;6.0&lt;/string&gt;<br> &lt;key&gt;CFBundleName&lt;/key&gt;<br> &lt;string&gt;hello&lt;/string&gt;<br> &lt;key&gt;CFBundlePackageType&lt;/key&gt;<br> &lt;string&gt;APPL&lt;/string&gt;<br> &lt;key&gt;CFBundleShortVersionString&lt;/key&gt;<br> &lt;string&gt;$(FLUTTER_BUILD_NAME)&lt;/string&gt;<br> &lt;key&gt;CFBundleSignature&lt;/key&gt;<br> &lt;string&gt;????&lt;/string&gt;<br> &lt;key&gt;CFBundleVersion&lt;/key&gt;<br> &lt;string&gt;$(FLUTTER_BUILD_NUMBER)&lt;/string&gt;<br> &lt;key&gt;LSRequiresIPhoneOS&lt;/key&gt;<br> &lt;true/&gt;<br> &lt;key&gt;UILaunchStoryboardName&lt;/key&gt;<br> &lt;string&gt;LaunchScreen&lt;/string&gt;<br> &lt;key&gt;UIMainStoryboardFile&lt;/key&gt;<br> &lt;string&gt;Main&lt;/string&gt;<br> &lt;key&gt;UIRequiredDeviceCapabilities&lt;/key&gt;<br> &lt;array&gt;<br>  &lt;string&gt;arm64&lt;/string&gt;<br> &lt;/array&gt;<br> &lt;key&gt;UISupportedInterfaceOrientations&lt;/key&gt;<br> &lt;array&gt;<br>  &lt;string&gt;UIInterfaceOrientationPortrait&lt;/string&gt;<br>  &lt;string&gt;UIInterfaceOrientationLandscapeLeft&lt;/string&gt;<br>  &lt;string&gt;UIInterfaceOrientationLandscapeRight&lt;/string&gt;<br> &lt;/array&gt;<br> &lt;key&gt;UISupportedInterfaceOrientations~ipad&lt;/key&gt;<br> &lt;array&gt;<br>  &lt;string&gt;UIInterfaceOrientationPortrait&lt;/string&gt;<br>  &lt;string&gt;UIInterfaceOrientationPortraitUpsideDown&lt;/string&gt;<br>  &lt;string&gt;UIInterfaceOrientationLandscapeLeft&lt;/string&gt;<br>  &lt;string&gt;UIInterfaceOrientationLandscapeRight&lt;/string&gt;<br> &lt;/array&gt;<br> &lt;key&gt;UIViewControllerBasedStatusBarAppearance&lt;/key&gt;<br> &lt;false/&gt;<br>&lt;/dict&gt;<br>&lt;/plist&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*8PdkGSbE9ESXTrLRVzoQEA.png" /></figure><p>Open the project in Xcode, select the Build Settings tab of the Runner target and search for versioning. Change the value of Current Project Version to $(FLUTTER_BUILD_NUMBER).</p><h3>Bonus</h3><blockquote>T̶h̶e̶ ̶f̶o̶l̶l̶o̶w̶i̶n̶g̶ ̶d̶e̶p̶e̶n̶d̶s̶ ̶o̶n̶ ̶#̶1̶6̶9̶3̶4̶.̶ ̶C̶u̶r̶r̶e̶n̶t̶l̶y̶,̶ ̶i̶t̶ ̶i̶s̶n̶’̶t̶ ̶m̶e̶r̶g̶e̶d̶,̶ ̶s̶o̶ ̶y̶o̶u̶ ̶h̶a̶v̶e̶ ̶t̶o̶ ̶w̶a̶i̶t̶ ̶a̶ ̶l̶i̶t̶t̶l̶e̶ ̶b̶i̶t̶.̶ ̶B̶u̶t̶ ̶a̶s̶ ̶w̶e̶ ̶s̶a̶y̶ ̶i̶n̶ ̶G̶e̶r̶m̶a̶n̶y̶̶…</blockquote><blockquote><strong>It was never merged, but you can use the </strong><a href="https://pub.dartlang.org/packages/package_info"><strong>package_info</strong></a><strong> plugin instead.</strong></blockquote><p>Now that our Flutter project knows the version it would be nice to access it to show it somewhere, in an <a href="https://docs.flutter.io/flutter/material/AboutListTile-class.html">about dialog</a> for example.</p><p>With <a href="https://github.com/flutter/flutter/pull/16934">#16934</a> Flutter generates a lib/build_config.g.dart file which looks like this:</p><pre>// GENERATED CODE - DO NOT MODIFY BY HAND<br><br>class BuildConfig {<br>  static const bool kDebug = true;<br>  static const String kModeName = &quot;debug&quot;;<br>  static const String kFlavor = null;<br>  static const String kVersionName = &quot;1.0.0&quot;;<br>  static const int kVersionNumber = 1;<br>}</pre><p>You can now easily use it to show the version or to do other fancy things depending on the build, for example, if it is a debug build or which flavor was build.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=299869e68af4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/karlmax-berlin/versioning-with-flutter-299869e68af4">Versioning with Flutter</a> was originally published in <a href="https://medium.com/karlmax-berlin">Karlmax Berlin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>