<?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 Suat Özkaya on Medium]]></title>
        <description><![CDATA[Stories by Suat Özkaya on Medium]]></description>
        <link>https://medium.com/@suatozkaya?source=rss-72c7134943------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lrtLmfgh6KTjCaS55C6fOg.jpeg</url>
            <title>Stories by Suat Özkaya on Medium</title>
            <link>https://medium.com/@suatozkaya?source=rss-72c7134943------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 22:31:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@suatozkaya/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[Uploading files to AWS S3 bucket with presigned URLs in Flutter & Dart]]></title>
            <link>https://medium.com/@suatozkaya/uploading-files-to-aws-s3-bucket-with-presigned-urls-in-flutter-dart-fd9ffcf82a74?source=rss-72c7134943------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd9ffcf82a74</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[presigned-url]]></category>
            <category><![CDATA[aws-s3]]></category>
            <dc:creator><![CDATA[Suat Özkaya]]></dc:creator>
            <pubDate>Sat, 08 Jul 2023 19:30:13 GMT</pubDate>
            <atom:updated>2023-07-08T19:30:13.382Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s say we have a presigned URL from a back-end server, and our goal is to upload a file to an S3 bucket using a POST request in <strong>Flutter Web &amp; Native Platforms</strong>. In this story, I will explain a straightforward solution that is easy to understand and implement.</p><blockquote>TL;DR: 👉🏽 <a href="https://github.com/ozkayas/upload-aws-s3-demo">Github Repo</a> for ‘show me the code’ers.</blockquote><blockquote>(I assume you already know what a “presigned URL”, if you do not please <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html">read this</a>.)</blockquote><blockquote>⚠️ Also note that, we will focus solely on the necessary logic for understanding the concept, without going into details about programming best practices like separation of concerns, state management, and layered architecture, etc.</blockquote><h4>Step 1: Picking a file</h4><p>There are many packages available on pub.dev with picking and drag-and-dropping abilities. You can choose any of them, but the tricky part is that these packages may return the selected object as an XFile or PlatformFile. Additionally, if our code is run on Flutter WEB, browsers cannot access the file in the same way as native apps can. This is because there are two distinct File classes for native and web platforms, namely dart:html and dart:io. Due to these complexities, we will aim to find the most basic and easiest implementation that can work for any situation.</p><p>Let’s choose <a href="https://pub.dev/packages/file_picker">file_picker</a> and <a href="https://pub.dev/packages/desktop_drop">desktop_drop</a> packages, since they are well maintained and popular. (<em>Since this is a simple example to I will just use setStates and do all the stuff in the Widget Layer. Please forgive me the Gods of architecture and State Management 😀)</em></p><p>The basic UI and related code is here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5223b030e5847664844386c6eef6bafc/href">https://medium.com/media/5223b030e5847664844386c6eef6bafc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*xUBsXkMMaefZzI_FpAvJoQ.gif" /><figcaption>Left: Flutter Web &amp; Right: Flutter MacOS app</figcaption></figure><p>Now, we will add browse &amp; pick ability:</p><pre>class _UploadFileViewState extends State&lt;UploadFileView&gt; {<br>   bool isDragging = false;<br>   ValueNotifier&lt;Object?&gt; selectedFile = ValueNotifier&lt;Object?&gt;(null); <br><br>  Future&lt;void&gt; _selectFile() async {<br>   final FilePickerResult? result = await FilePicker.platform.pickFiles(<br>     allowMultiple: false,<br>     type: FileType.custom,<br>     dialogTitle: ‘Select a file to upload’,<br>     allowedExtensions: [‘xls’, ‘xlsx’, ‘pdf’],<br>     );<br>     if (result != null &amp;&amp; result.files.isNotEmpty) {<br>       final PlatformFile file = result.files.single;<br>       selectedFile.value = file;<br>       }<br>   } <br><br>  void _onDragDone(DropDoneDetails urls) async {<br>   final droppedFile = urls.files.first;<br>   selectedFile.value = droppedFile;<br>   }<br><br>....<br><br>  /// TEXT WIDGET ADDED ///<br><br>  ValueListenableBuilder&lt;Object?&gt;(<br>    valueListenable: selectedFile,<br>    builder: (context, file, _) {<br>      return Text(<br>        &#39;Selected file Type: ${file.runtimeType}&#39;,<br>        style: const TextStyle(color: Colors.white),<br>      );<br>    },<br>  ),</pre><p>Here we added 2 methods, _selectFile and _onDragDone and putting the selected file by the packages into a ValueNotifier named selectedFile. Then we show the file type of this selected file in a Text Widget on the bottom as follows:</p><ul><li>file_picker → PlatformFile</li><li>desktop_drop → XFile</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*cIokSeqhKGUGgFR9ugbOjg.gif" /><figcaption>Web and MacOs apps</figcaption></figure><p>Now, regardless of the platform or package used, we are able to select a file, and we can proceed to the second step.</p><h4>Step 2: Configuring a request method for presigned Url</h4><p>Your presigned URL that you get from your back-end can be different than the example here, as per the requirements of your back-end service may change. I saw different cases that required PUT or POST requests. In our example we must use a POST request and our presigned Url looks something similar to this:</p><pre>&quot;presigned_upload_url&quot;: &quot;{<br>    &quot;url&quot;: &quot;https://mytestbucket.s3.amazonaws.com/&quot;, <br>    &quot;fields&quot;: {&quot;key&quot;:&quot;inputdata/user1/myDataFile.xlsx&quot;, <br>                &quot;AWSAccessKeyId&quot;:&quot;ASIAABCXXXXXXXXXXXX&quot;, <br>                &quot;x-amz-security-token&quot;:&quot;abcxyzloremipsum&quot;, <br>                &quot;policy&quot;:&quot;abcxyzloremipsum&quot;, <br>                &quot;signature&quot;:&quot;abcxyzloremipsum&quot;}}&quot;<br>}</pre><p>We have 2 main fields here:</p><ol><li>url: we will be sending the request to this resource</li><li>fields: we will add to as form fields to our MultiPartFile request</li></ol><p>Let’s say we created a simple Request Model as below and save our signedURL data in an instance of this UploadData class.</p><pre>class UploadData {<br>  final String url;<br>  final Map&lt;String, String&gt; fields;<br><br>  UploadData({<br>    required this.url,<br>    required this.fields,<br>  });<br><br>  factory UploadData.fromJson(Map&lt;String, dynamic&gt; json) {<br>    return UploadData(<br>      url: json[&#39;url&#39;],<br>      fields: Map&lt;String, String&gt;.from(json[&#39;fields&#39;]),<br>    );<br>  }<br>}</pre><p>We are adding a method in our network service which uses the <a href="https://pub.dev/packages/http">http</a> package:</p><pre>Future&lt;bool&gt; uploadToS3({<br>  required String uploadUrl,<br>  required Map&lt;String, String&gt; data,<br>  required List&lt;int&gt; fileAsBinary,<br>  required String filename,<br>}) async {<br>  var multiPartFile = http.MultipartFile.fromBytes(&#39;file&#39;, fileAsBinary, filename: filename);<br>  var uri = Uri.parse(uploadUrl);<br>  var request = http.MultipartRequest(&#39;POST&#39;, uri)<br>    ..fields.addAll(data)<br>    ..files.add(multiPartFile);<br>  http.StreamedResponse response = await request.send();<br>  if (response.statusCode == 204) {<br>    print(&#39;Uploaded!&#39;);<br>    return true;<br>  }<br>  return false;<br>}</pre><p>Let’s try to understand what’s happening here, essentially:</p><p><strong>MultiPartFile.fromBytes :</strong> we are uploading a file, so the appropriate http method is MultiPartFile and we prefer .fromBytes here because we are trying to escape the FileType differences we already discussed in the Step.1</p><p><strong>uploadUrl:</strong> we will make a POST request to this resource and already stored it in UploadData.url</p><p><strong>data:</strong> fields to be added as form fields of request, already stored in UploadData.fields</p><p><strong>filename:</strong> this may already been agreed with us and back-end, so the presignedURL data contains in the “key” field.</p><p>This method returns a boolean to notice about the result, but this is up to your architecture and decision.</p><p>Now we are ready for the next step: to establish a connection between selecting a file and sending it in a Post request.</p><h4>Step 3: Send the selected file to the network service for uploading</h4><p>To begin, we start by creating an instance of the network service and a dummy uploadData instance in the state. This will allow us to manage the network requests and handle the upload process effectively.</p><pre>//Network service should be injected in a real app<br>NetworkService networkService = NetworkService();<br><br>///Sample data for uploadData, replace with your own data<br>UploadData uploadData = UploadData(<br>  url: &#39;https://mytestbucket.s3.amazonaws.com/&#39;,<br>  fields: {<br>    &quot;key&quot;: &quot;inputdata/user1/myDataFile.xlsx&quot;,<br>    &quot;AWSAccessKeyId&quot;: &quot;ASIAABCXXXXXXXXXXXX&quot;,<br>    &quot;x-amz-security-token&quot;: &quot;abcxyzloremipsum&quot;,<br>    &quot;policy&quot;: &quot;abcxyzloremipsum&quot;,<br>    &quot;signature&quot;: &quot;abcxyzloremipsum&quot;,<br>  },<br>);</pre><p>Now our method to be called when the user presses ‘UPLOAD’ button</p><pre>void uploadSelectedFile() async {<br>  final (selectedFileBytes, selectedFileName) = await getFileBytesAndName(selectedFile.value);<br><br>  await networkService.uploadToS3(<br>    uploadUrl: uploadData.url,<br>    data: uploadData.fields,<br>    fileAsBinary: selectedFileBytes,<br>    filename: selectedFileName,<br>  );<br>}</pre><p>Here we have the first two parameters from uploadData instance, however for the bytes and fileName we are calling a helper method.</p><pre>Future&lt;(List&lt;int&gt;, String)&gt; getFileBytesAndName(Object? file) async {<br>  List&lt;int&gt; bytes;<br>  String fileName;<br><br>  if (file is XFile) {<br>    bytes = await file.readAsBytes();<br>    fileName = file.name;<br>  } else if (file is PlatformFile) {<br>    if (kIsWeb) {<br>      bytes = file.bytes!;<br>    } else {<br>      bytes = await getFileBytes(file);<br>    }<br>    fileName = file.name;<br>  } else {<br>    throw Exception(&#39;Invalid file type&#39;);<br>  }<br>  return (bytes, fileName);<br>}</pre><p>It’s important to note that depending on the type of the selected file and the platform our Flutter app is running on, we have three different methods available for obtaining the file bytes. The appropriate method will be chosen accordingly to ensure compatibility and proper handling of the file data.</p><p>If we have a PlatformFile and we are <strong>not</strong> on web, then we use another helper method getFileBytes. The <strong>File</strong> class here is from the dart:io library.</p><pre>Future&lt;List&lt;int&gt;&gt; getFileBytes(PlatformFile platformFile) async {<br>  // Get the file path from the PlatformFile object<br>  String? filePath = platformFile.path;<br><br>  // Read the file as bytes, File is from the dart:io library<br>  File file = File(filePath!);<br>  List&lt;int&gt; fileBytes = await file.readAsBytes();<br><br>  return fileBytes;<br>}</pre><p>Thanks for reading, feel free to comment and all the basic codes can be found on this <a href="https://github.com/ozkayas/upload-aws-s3-demo">Github Repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd9ffcf82a74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Change the default AppBar Buttons for the whole app]]></title>
            <link>https://medium.com/@suatozkaya/change-the-default-appbar-buttons-for-the-whole-app-f9b5ff3773f7?source=rss-72c7134943------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9b5ff3773f7</guid>
            <dc:creator><![CDATA[Suat Özkaya]]></dc:creator>
            <pubDate>Sun, 01 May 2022 10:40:59 GMT</pubDate>
            <atom:updated>2022-05-01T10:40:59.983Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>TLDR;</em></strong><em> 👉🏽 </em><a href="https://dartpad.dev/?id=b241142d081306b9fb2c2c1bf53da79c"><em>Click here to check and test on DartPad for the full code</em></a></p><p>We all love the default backButton and drawerButton coming with AppBar 👇🏼</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*UhX2bdxHEfnaNsM3tWYYUA.png" /><figcaption>iOS default backButton</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*uL5Y9qeHnc1lXekFJI_I4Q.png" /><figcaption>iOS default drawerButton</figcaption></figure><p>And if we prefer to use another Icon for a <strong>specific page</strong>, we can use the leading property of AppBar. as follows;</p><h4>For backButton:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*cLmjAR0zAItxUumx8oGLgw.png" /><figcaption>Sad smiley set as backButton</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6af357262a5cccdd26b680ce0029916a/href">https://medium.com/media/6af357262a5cccdd26b680ce0029916a/href</a></iframe><h4>For drawerButton:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*JWEOpbI86HM8yJWUSa1-qg.png" /><figcaption>Happy smiley set as drawerButton</figcaption></figure><p><em>❗️here we also need a </em><em>Builderto reach the Scaffold</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/686b51d0399c49abc226118f8b469934/href">https://medium.com/media/686b51d0399c49abc226118f8b469934/href</a></iframe><p>❓But wait, these implementations are valid just for <strong>the specific pages</strong>. How can we change <strong>the default</strong> iconDatas for the whole app ?</p><p>🤷🏻‍♂ ️Unfortunately, there is not a property called defaultBackButton or defaultDrawerButton.</p><p>So, how can we change these defaults in the whole app, on dozens of pages? We have to find a more convenient way of implementation.</p><h4>Custom AppBar</h4><p>A very simple solution can be just creating our own custom AppBar and implement any default icons as we wish.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2f055d458556bce2d83a0aacd275be1/href">https://medium.com/media/a2f055d458556bce2d83a0aacd275be1/href</a></iframe><p>In this simple example, I only added some primitive properties as instance fields <em>(Lines 2–5) </em>but you can add as per your implementation detail.</p><p>The default icons and related business logic are defined between lines 17–42.</p><p>And then you can just use CustomAppBar just as your default AppBar</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ba8dfdb336476dd91d4097a18389705/href">https://medium.com/media/5ba8dfdb336476dd91d4097a18389705/href</a></iframe><p>👉🏽 <a href="https://dartpad.dev/?id=b241142d081306b9fb2c2c1bf53da79c">Click here to check and test on DartPad for the full code</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*LgOi84bB-uW1niYoOMgedg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9b5ff3773f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart Constructors 101]]></title>
            <link>https://medium.com/@suatozkaya/dart-constructors-101-3bf36339ea0?source=rss-72c7134943------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bf36339ea0</guid>
            <dc:creator><![CDATA[Suat Özkaya]]></dc:creator>
            <pubDate>Thu, 21 Apr 2022 15:38:29 GMT</pubDate>
            <atom:updated>2022-04-21T15:38:29.972Z</atom:updated>
            <content:encoded><![CDATA[<h3>👉🏽 Part 2: Factory Constructors</h3><h4>A beginner-friendly tutorial for Dart constructors</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*3UegETRurTyunmG3QpXE4g.png" /></figure><p>For Part 1: <a href="https://medium.com/p/69c5b9db5230">Generative Constructors</a></p><p><strong>Why do we need another type of constructor?</strong></p><p>A generative constructor always creates a new instance, however in some cases we would like to <strong>return an existing instance</strong> of a class/subclass, or even <strong>return nothing</strong>.</p><p>Let’s compare named generative vs. factory:</p><pre>class <strong>User</strong> {<br>  <strong>String</strong> name;<br>  <strong>int</strong> id;</pre><pre>// <em>Named generative constructor</em><br>  <strong>User</strong>.<strong>fromJson</strong>(Map&lt;String,Object&gt; json)<br>       : name = json[&#39;name&#39;] as String,<br>         id = json[&#39;id&#39;] as int;</pre><pre>// <em>Factory constructor<br>  </em><strong>factory</strong><em> </em><strong>User.fromJson(</strong>Map&lt;String,Object&gt; json<strong>) {<br>       </strong>final id = json[&#39;id&#39;] as int;<br>       final name = json[&#39;name&#39;] as String;<br>       <strong>return User</strong>(id:id, name:name);</pre><pre>}</pre><p><strong>Generative:</strong></p><ul><li>always creates the instance itself</li><li>simply assigns values to instance fields in an initializer list, with no extra business logic. <em>(actually, we can call a static method here, but I am not sure if it is a best practice)</em></li></ul><p><strong>Factory:</strong></p><ul><li>calls the default constructor to create the instance and just returns it</li><li>we can handle any business logic in the body of the factory</li><li>we can throw an error instead of returning a new instance <em>( for example; if </em>id<em>is not a valid positive integer )</em></li></ul><p>Now, let’s see some common use cases of factory constructors.</p><h4>Singletons</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f28eaf7a63695c30dc7c7de695ec636/href">https://medium.com/media/7f28eaf7a63695c30dc7c7de695ec636/href</a></iframe><p>Here we have 2 constructors; a private named (._internal) and a factory constructor. When the factory is called, it checks whether an instance already exists. If null, we are calling the internal constructor to create a new instance and assign it to the_instance. <a href="https://dartpad.dev/?id=3eba2921ee1e6fbaabed492d98d65468"><strong>Click here</strong></a> to run this code snippet above to see the creation dates of all three instances 🧐</p><h4>Return a cached instance</h4><p>Let&#39;s say we need to fetch a certain object from a database of cached objects, and if the needed object is not available we would like to create one and add it to our database. Thus, next time we need it, we will get it from the database again.</p><p>For example, we need brushes with different colors in our app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/239d9782125310d1233f5234e28d8aa6/href">https://medium.com/media/239d9782125310d1233f5234e28d8aa6/href</a></iframe><p>Here we have 2 constructors; a private default constructor, and a factory. Whenever a brush with the desired color is demanded, the factory checks whether it is already in _cache box, if exists returns it, or else creates a new one, put it in the _cache and then returns this new instance. <em>(Have a look at the </em><a href="https://api.dart.dev/stable/2.15.1/dart-core/Map/putIfAbsent.html"><em>putIfAbsent method</em></a><em>, which is really versatile) </em><a href="https://dartpad.dev/?id=1f92c75ae7da88ed90d792d031a78729"><strong>Click to run this code on DartPad</strong></a></p><h4>Create a subclass instance</h4><p>Think about the following class — subclass hierarchy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2WfdLMsrfSbnkBTsQxcJng.png" /></figure><p>We want to create any of the current and future subclass instances depending on some business logic. That means, the client code <em>(the code that needs an instance) </em>does not know the creation logic and just asks for the appropriate instance as:</p><pre>Shape newShape = Shape();  <em>//may also supply some arguments</em></pre><p>For instance:</p><pre>abstract class Shape {<br>  <strong>factory</strong> Shape(String type) {<br>    if (type == &#39;circle&#39;) <strong>return Circle(); </strong><em>// return circle instance</em><br>    if (type == &#39;square&#39;) <strong>return Square(); </strong><em>// return square instance</em><br>    throw &quot;Can&#39;t create $type.&quot;;           <em>// return nothing but err</em><br>  }<br>}</pre><pre><br>Shape circle = Shape(&#39;circle&#39;);  <em>// a circle instance</em><br>Shape square = Shape(&#39;square&#39;);  <em>// a square instance</em></pre><p>In such a case you cannot use a generative constructor and <strong>should use a factory constructor</strong> in the parent class. And as you see the factory gives the option to throw an error after some decision-making. For the full implementation detail checkout this <a href="https://developers.google.com/codelabs/from-java-to-dart#3">official documentation here</a>.</p><blockquote>There exists some other detail regarding constructors, for example: forwarding, implementing assertions, etc. However, my concern here is to give a beginner-friendly tutorial for whoever is confused about all these :)</blockquote><p>Let me know if something is missing or needs to be updated. 😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bf36339ea0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart Constructors 101]]></title>
            <link>https://medium.com/@suatozkaya/dart-constructors-101-69c5b9db5230?source=rss-72c7134943------2</link>
            <guid isPermaLink="false">https://medium.com/p/69c5b9db5230</guid>
            <dc:creator><![CDATA[Suat Özkaya]]></dc:creator>
            <pubDate>Thu, 21 Apr 2022 15:37:44 GMT</pubDate>
            <atom:updated>2022-04-21T15:37:44.453Z</atom:updated>
            <content:encoded><![CDATA[<h3>👉🏽 Part 1: Generative Constructors</h3><h4>A beginner-friendly tutorial for Dart constructors</h4><p><em>Recently I have been working on a project where we are building a design system and I found myself creating and refactoring lots of constructors for these component widget classes. I realized that some details were not still clear to me. So I decided to do a deep dive into Dart Constructors.</em></p><p>Basically, constructors are just methods that create an object, a new instance of a class. Apart from syntax, each language may offer its own way, options, and easiness to developers, during this initiating process.</p><p>Let’s say we need a class named…. 🤔 … “User” 😀 ( a very creative name )</p><pre>class User {  <br>  String name;  <br>  int id;<br>}</pre><p>First and foremost, we can classify constructors into two main categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*3UegETRurTyunmG3QpXE4g.png" /></figure><ul><li><strong>Generative Constructors: </strong>creates a <strong>new instance</strong> of a class.</li><li><strong>Factory Constructors: </strong>gives us more flexible options such as performing extra work before returning the instance. Also lets us return an existing object, a subclass, or even null.</li></ul><p>For now, we will dismiss ‘factory constructors’ and just focus on ‘generative constructors’ in Part 1. Later, understanding factories will be… easy peasy 😉</p><h4><strong>Default Constructor</strong></h4><p>Any time we create a class, even if we do not define it implicitly, Dart gives us a default constructor behind the scenes.</p><pre>class User{<br>  String name;  <br>  int id;<br>}</pre><pre>User aNewUser = User();</pre><p>However, most of the time we need to create a <strong>customized object</strong> because you know each user has his/her own name and id. So we need custom constructors at this point.</p><h4>Custom Constructor</h4><p>We just need a simple method in our class and supply the arguments which need to be customized:</p><pre>class User {<br>  String name;<br>  int id;</pre><pre>// custom constructor with positional required parameters<br>  User(String name, int id) {<br>    this.name = name;<br>    this.id = id;  <br>  }</pre><pre>}</pre><pre>User user001 = User(&#39;Bob&#39;, 30);</pre><p>In this case, the arguments passed to the constructor are required (not optional) and their order (position) of them is relevant. Hence we can call name and id as <strong>positional required</strong> parameters.</p><p>And of course, Dart has other options for parameters:</p><ul><li>A parameter can be <strong>named </strong>as an alternative to <strong>positional</strong></li><li>A parameter can be <strong>optional </strong>instead of <strong>required</strong></li></ul><p>But before explaining these alternative parameter types, let me remind you that there is a shorter way (syntactic sugar) for creating constructors more easily. If property (instance field) names are the same as parameter names, then why are we always typing the same things again and again and again…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*uCfDYIsIMQmBaS1sjLQw8Q.png" /></figure><p>Instead of getting parameters, passing them to the body and assigning them to this.xxx , why don’t we just directly perform this assignment in parentheses as below?</p><pre><strong>// Long form</strong><br>User(String name, int id) {<br>    this.id = id;<br>    this.name = name;<br>  }</pre><pre><strong>// Short form</strong><br>User(this.name, this.id)</pre><p>⚠️ <em>This short form is the recommended styling by Dart documents 👉🏽h</em><a href="https://dart-lang.github.io/linter/lints/prefer_initializing_formals.html"><em>ttps://dart-lang.github.io/linter/lints/prefer_initializing_formals.html</em></a></p><p>So our class now looks as below. All are the same: again we have positional required parameters, but now our constructor is in a shorter, developer-friendly form. And from now on, I will be using this shorter form.</p><pre>class User {<br>  String name;<br>  int id;</pre><pre>  User(this.name, this.id);</pre><pre>}</pre><pre>User user001 = User(&#39;Bob&#39;, 30);</pre><p>⚠️ <em>You can still use curly braces for any</em> <em>initialization code here!</em></p><p>Ok, now we can get back to the parameter options that Dart supplies.</p><p>Let’s say we added a field called address that is optional. Then we just need to wrap this argument with ‘square brackets’ [……].</p><pre>class User {<br>  String name; //<em>required</em><br>  int id; //<em>required</em><br>  <strong>String? address; <em>//optional</em></strong></pre><pre>User(this.name, this.id, <strong>[this.address]</strong>);</pre><pre>}</pre><pre>User user001 = User(&#39;Bob&#39;, 30, &#39;Ankara&#39;);</pre><p>⚠️ Since the address field is optional, we must either define it as nullable or assign a default value during construction =&gt; User(this.name, this.id, [this.address = &#39;Ankara&#39;])</p><p>Most of the time, using positional arguments is not a convenient solution since there may be lots of arguments. And we have another solution: <strong>named arguments. </strong>Let’s say we want to define address as required named and phone as optional named arguments:</p><pre>class User {<br>  String name;   //<em>positional required</em><br>  int id;        //<em>positional required</em><br>  <strong>String address; //<em>named required</em><br>  String? phone;  //<em>named optional</em></strong></pre><pre>User(this.name, this.id, <strong>{required this.address, this.phone}</strong>);</pre><pre>}</pre><pre>User user001 = User(&#39;Bob&#39;, 30, address:&#39;Ankara&#39;, phone:&#39;555-00-00&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpy6mKg-3X6gxix_GNGrPA.png" /><figcaption>A brief summary of all options</figcaption></figure><h4>Named Constructors</h4><p>In Dart, we also have the option to give constructors explicit names. Very well-known examples may be either ‘<strong>fromJson</strong>’ named constructor of data classes or <strong>EdgeInsets</strong> named constructors in Flutter.</p><pre>class <strong>User</strong> {<br>  <strong>String</strong> name;<br>  <strong>int</strong> id;</pre><pre>  // <em>Custom generative constructor</em><br>  <strong>User</strong>(this.name, this.id);</pre><pre>  // <em>Named generative constructor</em><br>  <strong>User</strong>.<strong>fromJson</strong>(String json)<br>       : // <em>some initialization code here</em></pre><pre>}</pre><p><em>⚠️ Implementing </em><strong><em>fromJson</em></strong><em> as a factory constructor would be better in most cases, we will discuss this in part2</em></p><p><em>⚠️</em> <em>Reminder: We generally also have a </em><strong><em>toJson</em></strong><em> method in a similar case, and this </em><strong><em>toJson </em></strong><em>is a method, not a constructor!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JJQhn0eINREDQUYSU_Uww.png" /><figcaption>EdgeInsets class, Flutter framework</figcaption></figure><p>As you see in the example above, we have the flexibility to demand any parameter from the developer and initialize a new EdgetInsets object with any possibility. Named constructors obviously improve readability and gives us limitless ways to create objects with various configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*tV5JkY1LPNZ9ohnyGXMAkg.png" /></figure><h4>Initializer List</h4><p>In some cases, we need to tweak the initialization of instance variables with given arguments. We can initialize desired variables after a colon (:) and separate them with commas. You can see this case in the EdgeInsets example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-cTo0MhoSGaK2cF22kipQ.png" /></figure><p>There are other details such as redirecting (forwarding), constructor bodies, const keyword, etc. However, this level of detail is sufficient for this article. <a href="https://medium.com/p/3bf36339ea0">The next article</a> will cover the factory constructors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69c5b9db5230" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get anything from Dart enums?]]></title>
            <link>https://medium.com/@suatozkaya/how-to-get-anything-from-dart-enums-ad53734325ca?source=rss-72c7134943------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad53734325ca</guid>
            <category><![CDATA[extension]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[enum]]></category>
            <dc:creator><![CDATA[Suat Özkaya]]></dc:creator>
            <pubDate>Tue, 19 Oct 2021 07:38:57 GMT</pubDate>
            <atom:updated>2021-10-19T07:38:57.868Z</atom:updated>
            <content:encoded><![CDATA[<p>I like using enums because I can easily create my own data types which could only have pre-defined values and maintain better code readability.</p><p>Recently, I was developing an online payment app where Flutter creates lots of very similar form views for different types of payments. For example; ‘mobile payment’, ‘credit card payment’, etc. So I decided to create an enum called PaymentType with all possible types.</p><p>For simplicity let’s say we only have 4 payment types as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6f3d02181da874b887723183b136529/href">https://medium.com/media/c6f3d02181da874b887723183b136529/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1wTM0eXtcIXam1zA1WNWdg.png" /></figure><p>In the business logic, there are many scenarios where the app chooses between texts, icons, methods, and routes based on the payment type. Therefore, I had to use lots of switch statements in my classes and this pushed me to manage this mess more efficiently.</p><p>Here is what I discovered while digging the internet and documentation:</p><h4>describeEnum()</h4><p>If you’d like to fetch the description part (i.e. the text after ‘.’) of an enum, Flutter <a href="https://api.flutter.dev/flutter/foundation/describeEnum.html">foundation library</a> (<em>Not Dart!</em>) gives us describeEnum() function.</p><pre>print(PaymentType.Mobile); // &gt; &#39;Mobile&#39;</pre><pre>print(PaymentType.CreditCard); // &gt; &#39;CreditCard&#39;</pre><h4><strong>But this also does not seem very handy 🤷🏻‍♂️</strong></h4><h4>We need a better solution 🤔</h4><h4>Extension methods</h4><p>Actually, extension methods are not specific to enums. Check out the following video for a better introduction👇</p><p>I will not discuss extensions in detail within the scope of this story, and besides my Dart knowledge is not that advanced 🤓</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FD3j0OSfT9ZI&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DD3j0OSfT9ZI&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FD3j0OSfT9ZI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f21f8f0d602c6bf1cd5294155636f9c/href">https://medium.com/media/1f21f8f0d602c6bf1cd5294155636f9c/href</a></iframe><p>What I want is simply calling some getters on my enums and receive a String for Text Widgets, an IconData for Icon Widget, anything I already attached to that enum type.</p><p>Here’s what I mean:</p><pre>Text(PaymentType.Wifi.description) --&gt; Text(&#39;Internet Payment&#39;)<br>or<br>Icon(PaymentType.Mobile.icon) --&gt; Icon(Icons.phone_iphone)</pre><p>All we need to do is defining an extension on a enum class. Then adding some getters as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b80419907dc9039a27f19bee7ccf2533/href">https://medium.com/media/b80419907dc9039a27f19bee7ccf2533/href</a></iframe><p>There are also related packages on pub.dev such as: <a href="https://pub.dev/packages/enum_to_string">enum_to_string</a>, <a href="https://pub.dev/packages/super_enum">super_enum</a>, etc.</p><p>Please feel free to comment and help me improve 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad53734325ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter & GetX: Basic Authentication Flow]]></title>
            <link>https://medium.com/@suatozkaya/flutter-getx-basic-authentication-flow-de3d0313d5ae?source=rss-72c7134943------2</link>
            <guid isPermaLink="false">https://medium.com/p/de3d0313d5ae</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-getx]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[getx]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Suat Özkaya]]></dc:creator>
            <pubDate>Sat, 02 Oct 2021 20:01:09 GMT</pubDate>
            <atom:updated>2021-10-04T08:48:41.247Z</atom:updated>
            <content:encoded><![CDATA[<p>🤔 How to handle user authentication easily with GetX eco-system 💙.</p><p>I have been using GetX for my recent Flutter projects and its ease of use and simplicity gives me extra time to focus more on business logic of my apps.</p><p>My goal: Implementing a traditional client-server authentication flow based on MVVM pattern.</p><p><strong>Authentication Token</strong></p><p>The authentication logic is build around an identifier String called (authToken)‘authentication token.’ This token is obtained from back-end after a successful login, generally persisted locally on device and used in subsequent data requests from the server.</p><p><strong>Basic Authentication Flow</strong></p><p>First things first, in our main.dart file GetStorage is initialized for data persistency and GetMaterialApp is added to the top of widget tree.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/310914e654bb300cc41108ef3b62b711/href">https://medium.com/media/310914e654bb300cc41108ef3b62b711/href</a></iframe><p>home:SplashView() =&gt; A splash Screen during app initialization gives us the opportunity to check for network connection status, various settings, login status of the user, etc.</p><p>Now, let us just focus on authentication related components in this scenario:</p><ul><li><strong>Splash Screen:</strong> Actually we should create a ViewModel also for splash screen, however for sake of simplicity I will skip it. Splash Screen contains a FutureBuilder that waits for initialization services and checks.</li><li><strong>Authentication Manager: </strong>Manages authentication related operations, for example requests the authToken from cache manager and decides if user is already logged or not. So we should have a bool property called isLogged</li><li><strong>Cache Manager: </strong>Responsible for persisting data on device and return it when requested. Here, I preferred defining it as a <a href="https://dart.dev/guides/language/language-tour#adding-features-to-a-class-mixins">mixin</a>. Cache manager uses <a href="https://pub.dev/packages/get_storage">get_storage</a> (GetX 💙), a simple to use alternative to shared_preferences</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQNacDNGL64FLBQuJs3A9A.png" /><figcaption>Splash Screen initializes required services</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4e500f51bdbe8d2950d5e672700509e/href">https://medium.com/media/b4e500f51bdbe8d2950d5e672700509e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e976a40d8f616aef5d8a4fc2ada10f06/href">https://medium.com/media/e976a40d8f616aef5d8a4fc2ada10f06/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f706db02865df956ed0ee94d7d64fa0/href">https://medium.com/media/1f706db02865df956ed0ee94d7d64fa0/href</a></iframe><p>At this step we can check if any token already exists in device (I will not take into account the token expiration scenarios)</p><p>When the future method resolves successfully we add the OnBoard widget to widget tree. OnBoard widget returns an Obx (StreamBuilder counterpart of GetX ) that listens to any changes to isLogged and navigate between HomeView and LoginView <strong>declaratively</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18b8741e29b7669ded55a95427742d66/href">https://medium.com/media/18b8741e29b7669ded55a95427742d66/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHE-gJCoaeIKdnXHu4ej1Q.png" /><figcaption>Reactive navigation flow</figcaption></figure><p>Now if authentication manager decides to set isLogged = true then HomeView is reactively added to widget tree, if not so, LoginView is added and presented to the user to enter credentials.</p><p>At this step we have to add the following entities to the flow.</p><p><strong>Login View Model: </strong>The view model for login view.</p><p><strong>Login Service: </strong>A Basic network service to communicate with back-end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nU0R9IO8caJ_AUuvk1A7vA.png" /></figure><p>Here, the flow is as follows;</p><ul><li>User enters email/password, view model request a login and authToken via ‘login service’</li><li>If a token is:</li><li>→ successfully received, send token and request login to authentication manager. Authentication manager saves token and sets isLogged = true . Onboard screen reactively rebuilds widget tree and switches HomeView.</li><li>→ not received or null returned, we can simply show user a dialog about the error (user doesn’t exist, password incorrect, etc.)</li><li><strong>Logout</strong>: We simply add a logout button to our HomeView, which calls logOut method of Authentication Manager. isLogged is set to false, onboard reactively rebuilds and switches to LoginView. Any user specific persisted data is cleared, including token, user preferences, user info, etc. (<em>Actually we should implement a Home View Model here, however I also skip it for simplicity</em>)</li></ul><p>The final flow could be visualized as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74kIdO23Zxlqisle3tFETA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*OplV0stilKrcO6BWzaG4nw.gif" /></figure><p><strong>Adding a Register Option</strong></p><p>We also have to add a registering choice along with sign-in option to the user. We can simply achieve this by creating a second Form in LoginView widget. According to users choice LoginView rebuilds and loads appropriate form.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f51fa6225b9032e4098b9e6204692e7e/href">https://medium.com/media/f51fa6225b9032e4098b9e6204692e7e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*v3AjXqEsuRcDvxqwmAwQ_A.gif" /></figure><p><strong>Models</strong></p><p>We need models to encapsulate the data to be carried between classes. In this article I am using a fake API service <a href="https://reqres.in/">https://reqres.in/</a> and created models according to request/response models with respect to this fake service. These are respectively:</p><ul><li>LoginRequestModel:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0700e09380eff6f5b77757a99e0df935/href">https://medium.com/media/0700e09380eff6f5b77757a99e0df935/href</a></iframe><ul><li>RegisterRequestModel:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83bdaad8740600beb3f7f148d32d17e9/href">https://medium.com/media/83bdaad8740600beb3f7f148d32d17e9/href</a></iframe><ul><li>Login Response Model: Api service returns just the authToken , so this is very simple in this example:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47edcf5e591b6904f9fb8371eae8b852/href">https://medium.com/media/47edcf5e591b6904f9fb8371eae8b852/href</a></iframe><ul><li>Request Response Model:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e0ff6494df6bbba64c9d0c3c64ba61a/href">https://medium.com/media/7e0ff6494df6bbba64c9d0c3c64ba61a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0XB5dUfUA-TTXAYTYSZ_A.png" /><figcaption>Models flow between Login View Model — Login Service</figcaption></figure><p>We should also implement a UserModel that encapsulates user specific data such as username, email, phone, etc. after a successful login. However in our example, we simply get email &amp; password as register/login data. So we must either request such information from the user right after a fresh login, or implement a settings/profile page and let the user complete it later. Then of course save userModel via Cache Manager.</p><p><strong>Github repo:</strong></p><p><a href="https://github.com/ozkayas/auth_manager">GitHub - ozkayas/auth_manager: Authentication manager structure with GetX</a></p><p>In this article, I tried to implement a simple authentication flow on MVVM pattern and GetX eco-system was capable of performing all the following functionalities:</p><ul><li>State management</li><li>Dependency Injection</li><li>Navigation</li><li>Data persistence in device</li><li>Network requests</li><li>Showing dialogs</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de3d0313d5ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: Herkesin Bilmesi Gereken Temel Layout Kuralları]]></title>
            <link>https://medium.com/@suatozkaya/flutter-herkesin-bilmesi-gereken-temel-layout-kurallar%C4%B1-3395762b518e?source=rss-72c7134943------2</link>
            <guid isPermaLink="false">https://medium.com/p/3395762b518e</guid>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[constraints]]></category>
            <category><![CDATA[flutter-layout]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Suat Özkaya]]></dc:creator>
            <pubDate>Thu, 02 Sep 2021 11:01:00 GMT</pubDate>
            <atom:updated>2021-09-03T06:55:11.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wYHSLVoMooassRxMwR9Hdg.png" /></figure><blockquote>Dikkat: Bu yazı <a href="https://medium.com/@marcglasberg"><strong>Marcelo Glasberg</strong></a> tarafından yazılmış ve <a href="https://flutter.dev/docs/development/ui/layout/constraints">Flutter resmi dokümanlarının</a> da bir parçası olan ‘<a href="https://medium.com/flutter-community/flutter-the-advanced-layout-rule-even-beginners-must-know-edc9516d1a2"><strong>Flutter: The Advanced Layout Rule Even Beginners Must Know</strong></a>’ adlı makalenin tarafımdan Türkçeye çevirisidir.</blockquote><blockquote>Bu çalışmaya izin verdiğin için teşekkürler Marcelo!</blockquote><p>Flutter öğrenen biri width:100 genişliğinde olan bir widget’ın neden 100 piksel olmadığını sorduğunda ne dersiniz? Widget’ı bir Center ile sarmasını <em>(wrapping)</em>, değil mi?</p><p><strong>Hayır bunu yapmayın!</strong></p><p>Çünkü bunu yaparsanız size “FittedBoxneden çalışmıyor?”, “Column neden ekrandan taşıyor (<em>overflowing</em>)?” veya “ IntrinsicWidthneye yarar?” gibi sorularla tekrar tekrar gelecektir.</p><p>Bunun yerine ona Flutter Layout kurallarının HTML dünyasından çok farklı olduğunu anlatın <em>(ki muhtemelen oradan gelmiştir), </em>ve şu kuralı ezberletin.</p><blockquote>👉 <strong>Kısıtlamalar aşağı, boyutlar yukarı akar. Pozisyonu parent belirler.</strong></blockquote><p>Bu kural bilinmeden Flutter layoutu gerçekten anlaşılamaz, bu yüzden bunun erkenden öğrenilmesi gerektiğine inanıyorum.</p><p>Biraz daha açarsak:</p><ul><li>Bir widget kendi <strong>kısıtlamalarını</strong> <em>(constraints)</em> <strong>parent</strong> widget’ından alır. Bir “kısıtlama” yalnızca 4 özellik tarafınan belirlenir: minimum &amp; maksimum genişlik ve minimum &amp; maksimum yükseklik.</li><li>Ardından, bu widget çocuklarının <em>(children)</em> üzerinden bir bir geçer. Çocuklarına sırasıyla kısıtlamalarının ne olduğunu (her çocuk için farklı olabilir) söyler ve ardından her çocuğa hangi boyutta olmak istediğini sorar.</li><li>Sonrasında ise, widget çocuklarını (yatay olarak x ekseninde ve dikey olarak y ekseninde) birer birer konumlandırır.</li><li>En sonunda, parent widget’ına kendi boyutunu söyler (elbette orijinal kısıtlamalar dahilinde).</li></ul><p>Örneğin, Padding içeren bir Column ve iki çocuğunun yerleşimini ele alalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*-8qKPItXMrt_C45m.png" /></figure><blockquote><strong><em>Column Widget’ımız ile çocukları (children) ve parent’ı arasında şu şekilde bir iletişim gerçekleşir:</em></strong></blockquote><blockquote><strong>Widget: </strong>Hey parent, kısıtlamalarım neler?</blockquote><blockquote><strong>Parent: </strong>Genişliğin 90 ve 300 piksel aralığında, uzunluğun ise 30 ve 85 piksel aralığında olmalı</blockquote><blockquote><strong>Widget</strong>: Hmm, bana 5 piksel padding gerekiyor. Bu durumda çocuklarımın yerleşeceği alan en fazla 295 piksel genişlik, 75 piksel yükseklikte olabilir.</blockquote><blockquote><strong>Widget:</strong> Hey ilk çocuğum <em>(mor kutu-first child), sen </em><em>0-290 genişlik ve </em><em>0-75 yükseklik aralığında olmalısın.</em></blockquote><blockquote><strong>İlk Çocuk:</strong> Peki, öyleyse 290 piksel genişlik ve 20 piksek yükseklikte olmak isterim.</blockquote><blockquote><strong>Widget:</strong> Hm, ikinci çocuğumu ilkinin altına, sütun olarak yerleştirmeliyim. Bu durumda ikinci çocuğuma sadece 55 piksek yükseklikte alan kalıyor.</blockquote><blockquote><strong>Widget:</strong> Hey ikinci çocuk (yeşil kutu), <em>sen </em><em>0-290 genişlik ve </em><em>0-55 yükseklik aralığında olmalısın.</em></blockquote><blockquote><strong>İkinci Çocuk:</strong> 140 piksel genişlik ve 30 piksek yükseklikte olmak isterim.</blockquote><blockquote><strong>Widget:</strong> Çok güzel, bu durumda pozisyon olarak da ilk çocuğum x:5, y:5 posizyonunda yerleşebilir. İkinci çocuğum ise x:80, y:25 pozisyonuna yerleşebilir.</blockquote><blockquote><em>Tüm bu iletişim ve hesaplardan sonra Column Widget’ımız bu kez kendi parent Widget’ına dönerek ihtiyacı olan alanı bildirir.</em></blockquote><blockquote><strong>Widget:</strong> Hey parent, benim 300 piksel genişlik ve 60 piksel yüksekliğe ihtiyacım var.</blockquote><p>(<em>çn. Bu örnekte, Column çocuklarını ortalamaya çalışıyor, ayrıca bu pozisyonlar Column Widget’ının kendi alanın sol üst köşesini </em><em>X=0,Y=0 kabul ettiğimizde ortaya çıkan bağıl koordinatlardır</em>)</p><h3>Limitler</h3><p>Yukarıda açıklanan yerleşim kuralının bir sonucu olarak, Flutter’ın bir kaç önemli yerleşim sınırlaması vardır:</p><ul><li>Bir Widget <strong>istediği herhangi bir boyuta sahip olamaz</strong>. Parent’ın ona dayatacağı kısıtlamalar olabilir ve boyutu işte bu kısıtlamalar dahilinde kalacaktır.</li><li>Bir Widget ekranda <strong>nerede belireceğini bilemez ve buna kendi karar veremez</strong>. Bu karar parent Widget tarafından verilir.</li><li>Bu kuralların bir sonucu olarak, bir parent’ın pozisyonu ve boyutları da kendi parent’a bağlıdır. Bu yüzden tüm widget ağacını göz önüne alıp hesaplamalar yapmadan ekranda öğelerin nerede belireceğini bilmek mümkün değildir.</li></ul><h3>Örnekler:</h3><ul><li>Aşağıdaki CodePen’i çalıştırın. Run Pen butonuna tıkladıktan sonra sağ altta belirecek olan Rerun butonuna basmalısınız.</li><li>Veya Dartpad kullanalım: <a href="https://dartpad.dev/60174a95879612e500203084a0588f94">https://dartpad.dev/60174a95879612e500203084a0588f94</a></li><li>Veyahut kodun son halini bu <a href="https://github.com/marcglasberg/flutter_layout_article">Github Reposunda</a> bulabilirsiniz.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fmarcglasberg%2Fembed%2Fpreview%2FExVmwed%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DExVmwed&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fmarcglasberg%2Fpen%2FExVmwed&amp;image=https%3A%2F%2Fassets.codepen.io%2F4424308%2Finternal%2Fscreenshots%2Fpens%2FExVmwed.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dtrue%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1588611373%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/6efeebd41104b58e8cfd04d9ac5be1ad/href">https://medium.com/media/6efeebd41104b58e8cfd04d9ac5be1ad/href</a></iframe><h3>Örnek 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*xEzXShuEaCYMn9cS58cd9w.png" /></figure><pre>Container(color:Colors.red)</pre><p>Bu container’ın parent öğesi cihaz ekranı. Ekran Container ‘ı kendiyle aynı boyutta olmaya zorlar. Neticede, Container tüm ekranı kaplar ve her yer kırmızı olur.</p><h3>Örnek 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*xEzXShuEaCYMn9cS58cd9w.png" /></figure><pre>Container(width: 100, height: 100, color: Colors.red)</pre><p>Kırmızı Container 100 x 100 boyutlarında olmak ister, ancak olamaz. Çünkü parentı olan ekran, onu tüm ekranı doldurmaya zorlar. Container tüm ekranı kaplar ve her yer kırmızı olur.</p><h3>Örnek 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*I6mJleNRHh9irCn1RPqq6A.png" /></figure><pre>Center(<br>   child: Container(width: 100, height: 100, color: Colors.red)<br>)</pre><p>Burada ekran Center ‘ı ekranı doldurmaya zorlar ve Center ekranı doldurur.</p><p>Center çocuğu olan Container ‘a ekran boyutu kısıtı dahilinde hangi boyutta olmak istediğini sorar. Burada Container istediği şekilde 100 x 100 boyutunu seçebilir.</p><h3>Örnek 4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*f1Ht-L3YOj6Hq-j2soLvnA.png" /></figure><pre>Align(<br>   alignment: Alignment.bottomRight,<br>   child: Container(width: 100, height: 100, color: Colors.red),<br>)</pre><p>Bu örnekte Center yerine Align kullanılmış.</p><p>Align çocuğu Container a istediği boyutta olabileceğini söyler, gelen yanıta göre eğer müsait alan varsa onu ekran ortasına koymak yerine sağ-alt köşeye hizalar.</p><h3>Örnek 5</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*xEzXShuEaCYMn9cS58cd9w.png" /></figure><pre>Center(<br>   child: Container(<br>      color: Colors.red,<br>      width: double.infinity,<br>      height: double.infinity,<br>   )<br>)</pre><p>Center ekran tarafından tüm alanı kaplamaya zorlanır, ve tüm ekranı Center ile dolar.</p><p>Container ‘a ekran boyutları kısıtlaması dahilinde ne kadar alan istediği sorulur. Container sonsuz boyutta olmak ister, ancak Center tarafından ona verilen kısıtlama ekran boyutlarıdır. Neticede Container ekran boyutlarını geçemez ve tüm ekranı kırmızı yapacak şekilde kaplar.</p><h3><strong>Örnek 6</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*xEzXShuEaCYMn9cS58cd9w.png" /></figure><pre>Center(child: Container(color: Colors.red))</pre><p>Center ekran tarafından tüm alanı kaplamaya zorlanır, ve Center tüm ekranı kaplar.</p><p>Container ‘a ekran boyutları kısıtlaması dahilinde ne kadar alan istediği sorulur. Container için herhangi bir çocuk widget veya boyutlama tanımlanmamıştır. Bu durumda Container olabildiğince büyük olmayı seçer ve tüm ekranı kaplar.</p><p>Peki Containerneden bu kararı verir? Bu bir tasarım kararıdır, yani Container widgetı tasarlanırken bu şekilde davranmasını kararı verilmiştir. Elbette bu karar başka şekilde de verilebilirdi. Container ‘ın hangi koşullarda nasıl davranacağı kararları için ilgili dokümanını okumanız gerekiyor.</p><h3>Örnek 7</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*CTvUiZph3633b2UPb3ys9A.png" /></figure><pre>Center(<br>   child: Container(<br>      color: Colors.red,<br>      child: Container(color: Colors.green, width: 30, height: 30),<br>   )<br>)</pre><p>Center ekran tarafından tüm alanı kaplamaya zorlanır, ve Center tüm ekranı kaplar.</p><p>Container ‘a ekran boyutları kısıtlaması dahilinde ne kadar alan istediği sorulur. Container için herhangi bir boyutlama tanımlanmamıştır ancak bir çocuğu vardır. İşte bu durumda Container çocuğu boyutunda olmayı seçer. [<em>Bu da bir önceki örnekteki gibi bir tasarım kararıdır. (ç.n.)]</em></p><p>Kırmızı Container çocuğuna istediği boyutu seçebileceğini ancak ekran boyutu kısıtlaması olduğunu söyler. Yeşil Container boyutunu 30 x 30 olarak bildirir.</p><p>Neticede, yeşil Container istediği boyut olan 30 x 30 alanı alır, kırmızı Container çocuğu kadar alan kaplamayı tercih ettiğinden o da 30 x 30 alan kaplar. Ancak bunlar aynı boyutta olduğundan yeşil ekranda üstte kalır ve kırmızı bize görünmez.</p><h3>Örnek 8</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*ZOod8HRRukrgY2UDCbNeXQ.png" /></figure><pre>Center(<br>   child: Container(<br>     color: Colors.red,<br>     padding: const EdgeInsets.all(20.0),<br>     child: Container(color: Colors.green, width: 30, height: 30),<br>   )<br>)</pre><p>Kırmızı Container kendini çocuğu kadar boyutlandırmak ister, ancak kendine verilen padding de hesaba katılmalıdır. Bu yüzden 70 x 70 boyutlarında olmaya karar verir (30 x 30 üzerine her kenardan 20 piksel padding eklenmekte). Bu padding sebebiyle boyutları artan kırmızı Container yeşilin arkasından bu kez görülebilmektedir.</p><h3>Örnek 9</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*xEzXShuEaCYMn9cS58cd9w.png" /></figure><pre>ConstrainedBox(<br>   constraints: BoxConstraints(<br>      minWidth: 70, <br>      minHeight: 70,<br>      maxWidth: 150, <br>      maxHeight: 150,<br>   ),<br>   child: Container(color: Colors.red, width: 10, height: 10),<br>)</pre><p>Container ‘ın 70 –150 piksel arasında olacağını tahmin edebilirsiniz, çünkü ConstrainedBox tarafından getirilen kısıtlamalar bunlar olarak görülüyor. Ancak ConstrainedBox kendi parent widget’ından gelen kısıtlamalara ilaveler ekleyebilir.</p><p>Burada, ConstrainedBox ekran tarafından tüm ekran boyutunda olmaya zorlanır ve <strong>ilave</strong> constraints parametresini göz ardı ederek kısıtlama olarak Container ‘a tüm ekran boyutu kısıtlamasını iletir.</p><h3>Örnek 10</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*vxNKvJbJkkkPtKt-DzJvfQ.png" /></figure><pre>Center(<br>   child: ConstrainedBox(<br>      constraints: BoxConstraints(<br>         minWidth: 70, <br>         minHeight: 70,<br>         maxWidth: 150, <br>         maxHeight: 150,<br>      ),<br>      child: Container(color: Colors.red, width: 10, height: 10),<br>   )    <br>)</pre><p>Burada ConstrainedBox istediği boyutu seçme özgürlüğüne sahiptir, çünkü Center onu bu konuda kısıtlamayacaktır. ConstrainedBox ise çocuğu olan Container ‘a <strong>ilave</strong> constraints parametresini empoze eder.</p><p>Nihayetinde Container 70 ve 150 piksel arasında olmalıdır. Container 10 piksel olmak ister ancak bu kısıtlamadan dolayı 70 (minimum değer) boyutunu alır.</p><h3><strong>Örnek 11</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*eyNEviUhE8EN7SoJVkQvkg.png" /></figure><pre>Center(<br>  child: ConstrainedBox(<br>     constraints: BoxConstraints(<br>        minWidth: 70, <br>        minHeight: 70,<br>        maxWidth: 150, <br>        maxHeight: 150,<br>        ),<br>     child: Container(color: Colors.red, width: 1000, height: 1000),<br>  )  <br>)</pre><p>Burada ConstrainedBox Center tarafından kısıtlanılmaz. ConstrainedBox ise çocuğu olan Container ‘a <strong>ilave</strong> constraints parametresini empoze eder.</p><p>Nihayetinde Container 70 ve 150 piksel arasında olmalıdır. Container 1000 piksel olmak ister ancak bu kısıtlamadan dolayı 150 (maksimum değer) boyutunu alır.</p><h3>Örnek 12</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*_vLjPfs4FSQWPKRfBB5VNg.png" /></figure><pre>Center(<br>   child: ConstrainedBox(<br>      constraints: BoxConstraints(<br>         minWidth: 70, <br>         minHeight: 70,<br>         maxWidth: 150, <br>         maxHeight: 150,<br>      ),<br>      child: Container(color: Colors.red, width: 100, height: 100),<br>   ) <br>)</pre><p>Bu örnekte de ConstrainedBox Center tarafından kısıtlanmamıştır ve çocuğu olan Container ‘a <strong>ilave</strong> constraints parametresini empoze eder.</p><p>Nihayetinde Container 70 ve 150 piksel arasında olmalıdır. Container 100 piksel olmak ister, bu değer kısıtlamalar dahilinde olduğu için bu isteği yerine gelir ve 100 piksel olarak ekrana boyanır.</p><h3>Örnek 13</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*UrGiVP6rE_eUm43YmVkgJA.png" /></figure><pre>UnconstrainedBox(<br>   child: Container(color: Colors.red, width: 20, height: 50),<br>)</pre><p>Ekran UnconstrainedBox ‘ı tüm ekranı kaplamaya zorlar. Öte yandan UnconstrainedBox , çocuğu olan Container için her hangi bir kısıtlama getirmez.</p><h3><strong>Örnek 14</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*NImh83wi4eqXbgGJ2-4_hw.png" /></figure><pre>UnconstrainedBox(<br>   child: Container(color: Colors.red, width: 4000, height: 50),<br>);</pre><p>Ekran UnconstrainedBox ‘ı tüm ekranı kaplamaya zorlar. Öte yandan UnconstrainedBox , çocuğu olan Container için her hangi bir kısıtlama getirmez.</p><p>Kısıtlaması olmayan Container 4000 piksel genişliğe sahiptir ve ekran kadar olan UnconstrainedBox ‘a sığmaz. Bu yüzden de UnconstrainedBox ekrandan taşma uyarısı <em>(overflow warning)</em> verir.</p><h3><strong>Örnek 15</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*59LPi6McPFR4-oFoiLsoIQ.png" /></figure><pre>OverflowBox(<br>   minWidth: 0.0,<br>   minHeight: 0.0,<br>   maxWidth: double.infinity,<br>   maxHeight: double.infinity,   <br>   child: Container(color: Colors.red, width: 4000, height: 50),<br>);</pre><p>Ekran OverflowBox ‘ı tüm ekranı kaplamaya zorlar. Öte yandan OverFlowBox , çocuğu olan Container için her hangi bir kısıtlama getirmez.</p><p>Bu şekilde bir kullanımda OverflowBox UnconstrainedBox çok benzer, aradaki fark ise ekrana sığmayan çocuğu olması durumunda OverflowBox herhangi bir taşma hatası vermez.</p><p>Örnekte Container 4000 piksel genişliktedir ve OverflowBox ‘a sığmayacağı aşikardır, yine de OverflowBox ekranda elinden geldiğince çocuğunu gösterir ve herhangi bir hata vermez.</p><h3>Örnek 16</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*mIMxfIHnnEXgRNAZmEKazw.png" /></figure><pre>UnconstrainedBox(<br>   child: Container(<br>      color: Colors.red, <br>      width: double.infinity, <br>      height: 100,<br>   )<br>)</pre><p>Bu kod ekranda hiç bir şey boyamaz ve konsolda bir hata alırız.</p><p>UnconstrainedBox çocuğuna herhangi bir kısıtlama getirmez, ancak çocuğu olan Container sonsuz boyut istemektedir.</p><p>Flutter kısıtlanmamış sonsuz boyutları ekrana çizemez ve şu uyarıyı fırlatır: BoxConstraints forces an infinite width</p><h3>Örnek 17</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*I6mJleNRHh9irCn1RPqq6A.png" /></figure><pre>UnconstrainedBox(<br>   child: LimitedBox(<br>      maxWidth: 100,<br>      child: Container( <br>         color: Colors.red,<br>         width: double.infinity, <br>         height: 100,<br>      )<br>   )<br>)</pre><p>Burada herhangi bir hata almayız, çünkü LimitedBox parent widgetı UnconstrainedBox ‘tan herhangi bir kısıtlama almamaktadır, yani sonsuz boyut almaktadır. Bu koşul altındaki LimitedBox kendi çocuğuna maksimum 100 piksel genişlik kısıtlaması getirmektedir.</p><p>Dikkat, eğer UnconstrainedBox yerine bir Center kullansaydık ne olurdu? LimitedBox çocuğuna bir limit kısıtlaması getiremezdi ve Container 100 piksel genişlikten daha büyük olurdu. Bunun sebebi şudur: LimitedBox ‘ın limit kısıtlaması ancak kendisi sonsuz boyut kısıtlaması altındaysa geçerli oluyor.</p><p>İşte bu da ConstrainedBox ve LimitedBox arasındaki farkı ortaya koyuyor.</p><h3>Örnek 18</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*w3LnbmHovK9SVHJxjVcgpg.png" /></figure><pre>FittedBox(<br>   child: Text(&#39;Some Example Text.&#39;),<br>)</pre><p>Ekran FittedBox ‘ı tüm ekran boyutunda olmaya zorlar. Text doğal bir genişliğe <em>(buna intrinsic width denir) </em>sahiptir çünkü metindeki karakter sayısı, font büyüklüğü, vb değişkenlerden etkilenir.</p><p>FittedBox Text ‘e istediği boyutta olma izni verir, ancak Text istediği boyutu FittedBox ‘a ilettikten sonra, FittedBox tarafından mevcut olan genişliğe sığdıracak şekilde tekrar boyutlandırılır.</p><h3>Örnek 19</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*1vbgqwI5pV9DVFlV7oIjTg.png" /></figure><pre>Center(<br>   child: FittedBox(<br>      child: Text(&#39;Some Example Text.&#39;),<br>   )<br>)</pre><p>Peki FittedBox ‘ı bir Center içine yerleştirirsek ne olur? Center istediği boyutta olması için FittedBox ‘a izin verir, ekran boyutuna kadar.</p><p>FittedBox daha sonra kendisini Text ‘e göre boyutlandırır ve Text ‘in istediği boyuta sahip olmasına izin verir. Hem FittedBox hem de Text aynı ölçüdelerdir ve ilave bir boyutlandırma gerçekleşmez.</p><h3>Örnek 20</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*qspcQSJ67lNmQXRmnE3O4g.png" /></figure><pre>Center(<br>   child: FittedBox(<br>      child: Text(&#39;This is some very very very large text that is too big to fit a regular screen in a single line.&#39;),<br>   )<br>)</pre><p>Peki ya FittedBox bir Center içerisinde, ancak Text metni ekrana sığmayacak kadar uzun ise ne olur?</p><p>FittedBox kendini Text kadar genişletmek ister ancak ekrandan daha büyük olamaz. Bu durumda kendini ekrana göre ayarlayacak, Text ‘i ise ekrana sığacak şekilde boyutlandıracaktır.</p><h3>Örnek 21</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*Vvhm6FyQkwSK-iCRzISjWw.png" /></figure><pre>Center(<br>   child: Text(&#39;This is some very very very large text that is too big to fit a regular screen in a single line.&#39;),<br>)</pre><p>Öte yandan, eğer FittedBox ‘ı aradan çıkartırsak Text ekrandan maksimum değeri alacaktır, ve ekrana sığacağı şekilde metni satırlara yayılacaktır.</p><h3>Örnek 22</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*mIMxfIHnnEXgRNAZmEKazw.png" /></figure><pre>FittedBox(<br>   child: Container(<br>      height: 20.0, <br>      width: double.infinity,<br>   )<br>)</pre><p>Dikkat, FittedBox sadece <strong>sınırlandırılmış </strong><em>(genişlik ve yüksekliği sonsuz atanmamış)</em><strong> </strong>bir widgetı boyutlandırabilir. Aksi halde, ekrana çizilmez ve konsola hata mesajı verilir.</p><h3>Örnek 23</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*_XgKAL2J-XdZGqJp1Hflyg.png" /></figure><pre>Row(<br>   children:[<br>      Container(color: Colors.red, child: Text(&#39;Hello!&#39;)),<br>      Container(color: Colors.green, child: Text(&#39;Goodbye!)),<br>   ]<br>)</pre><p>Ekran Row ‘u tüm ekran boyutunda olmaya zorlar.</p><p>Aynı bir UnconstrainedBox gibi davranan Row ise çocuklarına herhangi bir kısıtlama getirmez, ve istedikleri boyutu seçmelerine imkan verir. Daha sonra Row çocuklarını sırasıyla yan yana dizer, ve herhangi bir fazla alan boş olarak kalır.</p><h3>Örnek 24</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*V_qZN5MesfwvFfkW-D7yiQ.png" /></figure><pre>Row(<br>   children:[<br>      Container(color: Colors.red, child: Text(&#39;This is a very long text that won’t fit the line.&#39;)),<br>      Container(color: Colors.green, child: Text(&#39;Goodbye!&#39;)),<br>   ]<br>)</pre><p>Row çocuklarına herhangi bir kısıtlama getirmediğinden, çocukların mevcut olan genişliğe sığmayacak kadar büyük olmaları oldukça muhtemel bir durumdur. Böyle bir halde ise, UnconstrainedBox durumundaki gibi, Row ekrandan taşma uyarısı (overflow warning) verecektir.</p><h3>Örnek 25</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*QKQLKs9gDEz1nHAFNr2AUA.png" /></figure><pre>Row(<br>   children:[<br>      Expanded(<br>         child: Container(color: Colors.red, child: Text(&#39;This is a very long text that won’t fit the line.&#39;))<br>      ),<br>      Container(color: Colors.green, child: Text(&#39;Goodbye!&#39;)),<br>   ]<br>)</pre><p>Row ‘a bağlı bir çocuk widget Expanded ile sarmalanırsa, Row artık bu çocuğa kendi boyutunu belirleme özgürlüğü tanımaz.</p><p>Bunun yerine Expanded genişliği diğer çocuklara göre belirlenir, ve artık genişliği belli olan Expanded bu çocuğa kendi boyutuna gelmesini zorlar.</p><p>Diğer bir deyişle, Expanded kullanıldığında, orijinal çocuğun genişliği anlamsız hale gelir ve yok sayılır.</p><h3>Örnek 26</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*BJFwInhH9qx4FGfRoRc7Jw.png" /></figure><pre>Row(<br>   children:[<br>      Expanded(<br>         child: Container(color: Colors.red, child: Text(‘This is a very long text that won’t fit the line.’)),<br>      ),<br>      Expanded(<br>         child: Container(color: Colors.green, child: Text(‘Goodbye!’),<br>      ),<br>   ]<br>)</pre><p>Eğer Row ‘un tüm çocukları Expanded ile sarmalanırsa ne olur? Bu durumda her bir Expanded flex parametrelerine göre orantısal bir boyut alır ve sonra da her bir Expandedkendi çocuğunu bu boyuta sığmaya zorlar.</p><p>Başka bir deyişle, Expanded çocuklarının tercih ettiği genişlikleri görmezden gelir.</p><h3>Örnek 27</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*ZvH2xHERW1gQyb6x9bqdpQ.png" /></figure><pre>Row(children:[<br>  Flexible(<br>    child: Container(color: Colors.red, child: Text(&#39;This is a very long text that won’t fit the line.&#39;))),<br>  Flexible(<br>    child: Container(color: Colors.green, child: Text(‘Goodbye!’))),<br>  ]<br>)</pre><p>Expanded yerine Flexible kullandığınızda değişecek olan şey ise şudur: Flexible çocuğuna kendiyle <strong>aynı veya daha küçük</strong> boyutta olma izni verirken Expanded ise çocuğunu kendi<strong> tam boyutuna </strong>zorlar.</p><p>Fakat hem Flexible hem de Expanded çocuklarının genişliklerini göz ardı eder.</p><p>Bunun bir anlamı da, Row çocukların orijinal boyutlarına orantılı olarak genişletilmesinin <strong>imkansız</strong> olduğudur. Row ya çocukların orijinal genişliğini kullanır, ya da Expanded ve Flexible kullanımıyla çocukların orijinal genişliklerini tamamen göz ardı eder.</p><p><em>(Not: bu özellik için Marcelo Glasberg’in </em><a href="https://pub.dev/packages/assorted_layout_widgets"><em>assorted_layout_widgets</em></a><em> adlı bir paketi mevcut. Bu paket içerisinde çocukları orijinal boyutlara göre orantılayan özel bir Row widgetı bulabilirsiniz)</em></p><h3>Örnek 28</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*Xgpug0SGinm1uBJKVnxgrQ.png" /></figure><pre>Scaffold(<br>   body: Container(<br>      color: blue,<br>      child: Column(<br>         children: [<br>            Text(&#39;Hello!&#39;),<br>            Text(&#39;Goodbye!&#39;),<br>         ]<br>      )))</pre><p>Scaffold ekran boyutunda olmaya zorlanır dolayısıyla tüm ekran Scaffold ile kaplanır.</p><p>Scaffold Container ‘a ekrandan büyük olmayacak şekilde istediği boyutta olabileceğini söyler.</p><p><em>Not</em>: Bir widget çocuğuna belirli bir boyuttan küçük olabileceğini söylediğinde kastedilen şey çocuğa “gevşek” kısıtlama (loose constraints) getirilmesidir. Bu konuya tekrar geleceğiz.</p><h3>Örnek 29</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*K0H15VbPHBwAxu8DLntl2w.png" /></figure><pre>Scaffold(<br>   body: <strong>SizedBox.expand</strong>(<br>      child: Container(<br>         color: blue,<br>         child: Column(<br>            children: [<br>               Text(&#39;Hello!&#39;),<br>               Text(&#39;Goodbye!&#39;),<br>            ],<br>         ))))</pre><p>Scaffold ‘un çocuğunu Scaffold ile aynı boyutta olacak şekilde istediğimiz bir durumda, çocuğu SizedBox.expand ile sarmalayabiliriz.</p><p>Not: Eğer bir widget çocuğuna tam olarak belirli bir boyutta olmasını söylüyorsa, burada widget “sıkı” kısıtlama (tight constraints) yapıyordur.</p><h3>Sıkı x Gevşek / Kısıtlamalar</h3><p>Çoğu zaman sıkı veya gevşek (tight x loose constraints) kısıtlamalardan bahsedildiğini duyarız, bu yüzden bunların ne anlama geldiğini bilmekte fayda var.</p><p>Sıkı bir kısıtlama tek bir olasılık içerir, tam olarak belirli bir boyut. Başka bir deyişle, sıkı kısıtlama durumunda minimum genişlik maksimum genişliğe eşit, minimum yükseklik ise maksimum yüksekliğe eşittir.</p><p>Flutterda box.dart dosyasını açıp BoxConstraints yapıcısını incelediğinizde göreceğiniz şudur:</p><pre>BoxConstraints.tight(Size size)<br>   : minWidth = size.width,<br>     maxWidth = size.width,<br>     minHeight = size.height,<br>     maxHeight = size.height;</pre><p>Örnek 2&#39;ye tekrar dönüp baktığınızda, kırmızı Container ‘ın ekranla aynı boyuta zorlandığını görürsünüz. Bunu yapan ekrandır, ve tabii ki bunu Container ‘a <strong>sıkı</strong> kısıtlama ileterek sağlar.</p><p>Öte yandan, <strong>gevşek</strong> bir kısıtlama ise maksimum genişlik/yüksekliği belirler, ama aynı zamanda, bunlardan istediği kadar <strong>küçük</strong> olabilme izni verir. Bu durumda, <strong>gevşek</strong> kısıtlamada minimum genişlik/yükseklik <strong>sıfır</strong> değerindedir.</p><pre>BoxConstraints.loose(Size size)<br>   : minWidth = 0.0,<br>     maxWidth = size.width,<br>     minHeight = 0.0,<br>     maxHeight = size.height;</pre><p>Örnek 3&#39;e tekrar bakarsanız Center Container ‘a daha küçük olabilme ama en fazla da ekran kadar olma izni verir. Tabii ki Center bunu yaparken Container ‘a gevşek kısıtlamalar iletir. Neticede Center ‘ın amacı ekrandan aldığı (parent) sıkı kısıtlamaları, kendi çocuğu olan Container ‘a gevşek kısıtlama olarak dönüştürerek iletmektir.</p><h3>Belirli widgetlar için layout kurallarını öğrenmek</h3><p>Genel yerleşim kurallarını bilmek elbette gerekli ancak kendi başına yeterli değil.</p><p>Genel kurallar uygulanırken her bir widget’ın oldukça özgürlüğü vardır, bu nedenle sadece widget’ın adına bakarak nasıl davranacağını bilmenin bir yolu yoktur.</p><p>Tahminde bulunsanız da muhtemelen yanılacaksınız. Bir widget’ın dokümanlarını ve kaynak kodunu incelemeden tam olarak nasıl davranacağını tam olarak bilemezsiniz.</p><p>Yerleşimle ilgili kaynak kodlar genellikle karmaşıktır, bu yüzden ilgili dokümanları incelemek genellikle daha iyi bir yol. Yine de, eğer kaynak kodu incelemek isterseniz bunu kullandığınız IDE yardımıyla kolaylıkla bulabilirsiniz.</p><p>Örnek olarak:</p><ul><li>Kodunuzdaki bir Column ‘a gelin ve kaynak koduna ilerleyin ( Ctrl-B IntelliJ ). Muhtemelen basic.dart dosyası açılacaktır. Column ise Flex ‘ten extend olduğundan Flex kısmına ilerleyin ( aynı dosya: basic.dart )</li><li>Şimdi createRenderObject metoduna kadar aşağı inin. Bu metodun bir RenderFlex döndürdüğünü göreceksiniz. Bu ise Column için karşılık gelen render-objesidir. RenderFlex için kaynak koduna ilerleyin ve flex.dart dosyasına gidin.</li><li>performLayout metodunu bulun. İşte Column için yerleşimi yapan metot budur.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*TdPNJQExjmNhnojgi1nXPQ.png" /></figure><h4>😎 Marcelo Glasberg’in diğer yararlı paketleri ve sosyal medya adreslerine mutlaka göz atın:</h4><p><strong>Yerleşim (lay-out) paketleri:</strong></p><ul><li><a href="https://pub.dev/packages/align_positioned"><em>align_positioned</em></a></li><li><a href="https://pub.dev/packages/assorted_layout_widgets"><em>assorted_layout_widgets</em></a></li></ul><p><strong>Diğer paketleri:</strong></p><ul><li><a href="https://pub.dev/packages/async_redux"><em>async_redux</em></a><em> </em>|Medium: <a href="https://medium.com/flutter-community/https-medium-com-marcglasberg-async-redux-33ac5e27d5f6"><strong><em>Async Redux: Flutter’s non-boilerplate version of Redux</em></strong></a></li><li><a href="https://pub.dev/packages/i18n_extension"><em>i18n_extension</em></a><em> </em>| Medium: <a href="https://medium.com/flutter-community/i18n-extension-flutter-b966f4c65df9"><strong><em>Mind-blowing Easy Translations and Internationalization for Flutter</em></strong></a></li><li><a href="https://pub.dev/packages/fast_immutable_collections"><em>fast_immutable_collections</em></a> | Medium: <a href="https://medium.com/flutter-community/announcing-fic-fast-immutable-collections-5eb091d1e31f"><strong>Announcing FIC: Fast Immutable Collections</strong></a></li><li><a href="https://pub.dev/packages/themed"><em>themed</em></a> | Medium: <a href="https://medium.com/flutter-community/the-new-way-to-create-themes-in-your-flutter-app-7fdfc4f3df5f"><strong>The New Way to create Themes in your Flutter App</strong></a></li><li><a href="https://pub.dev/packages/provider_for_redux"><em>provider_for_redux</em></a></li><li><a href="https://pub.dev/packages/image_pixels"><em>image_pixels</em></a></li><li><a href="https://pub.dev/packages/network_to_file_image"><em>network_to_file_image</em></a></li><li><a href="https://pub.dev/packages/matrix4_transform"><em>matrix4_transform</em></a></li><li><a href="https://pub.dev/packages/back_button_interceptor"><em>back_button_interceptor</em></a></li><li><a href="https://pub.dev/packages/indexed_list_view"><em>indexed_list_view</em></a></li><li><a href="https://pub.dev/packages/animated_size_and_fade"><em>animated_size_and_fade</em></a></li><li><a href="https://pub.dev/packages/weak_map"><em>weak_map</em></a></li></ul><blockquote><a href="https://github.com/marcglasberg">https://github.com/marcglasberg</a><br><a href="https://twitter.com/GlasbergMarcelo">https://twitter.com/GlasbergMarcelo</a><br><a href="https://stackoverflow.com/users/3411681/marcg">https://stackoverflow.com/users/3411681/marcg</a></blockquote><p>👍 <a href="https://github.com/slightfoot">Simon Lightfoot</a>’a bu makalenin ana imajı ve içerik önerileri için ayrıca teşekkürler !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3395762b518e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>