<?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 Merdan Durdyyev on Medium]]></title>
        <description><![CDATA[Stories by Merdan Durdyyev on Medium]]></description>
        <link>https://medium.com/@meinnps?source=rss-c93de175ef16------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uoF-W7bxyFIb3nkph0-bgg.png</url>
            <title>Stories by Merdan Durdyyev on Medium</title>
            <link>https://medium.com/@meinnps?source=rss-c93de175ef16------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 06:53:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@meinnps/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[Our Coding Agent Has Amnesia. So We Tried Giving It a Wiki.]]></title>
            <link>https://medium.com/@meinnps/our-coding-agent-has-amnesia-so-we-tried-giving-it-a-wiki-b5c9515cc0b3?source=rss-c93de175ef16------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5c9515cc0b3</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[agent-memory]]></category>
            <category><![CDATA[coding-agents]]></category>
            <category><![CDATA[coding-agent-memory]]></category>
            <dc:creator><![CDATA[Merdan Durdyyev]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 05:15:22 GMT</pubDate>
            <atom:updated>2026-07-23T05:15:22.986Z</atom:updated>
            <content:encoded><![CDATA[<h4>Andrej Karpathy’s <a href="https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f">llm-wiki.md</a> but for software development projects.</h4><p><em>An experiment in giving Claude Code and Codex a team-shared, Git-versioned memory that maintains itself for building better and faster.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVub0OgIGVUZFjc30qLPSA.png" /></figure><p>This article is not about teaching. It’s about sharing an experiment and, honestly, learning from you.</p><p>I built a small tool called <strong>LLM Wiki-Dev</strong>. We’ve been using it on our own repos. I think the idea is right, and I’m still not sure the execution is. So instead of polishing it in private for another month, I want to put it out early. Here is the problem, here is what I built, and here is exactly where I think it’s still weak. If you’ve solved this better, please tell me in the comments. That’s half the reason I’m writing.</p><h3>The problem: my agent forgets everything</h3><p>If you use a coding agent, Claude Code, Codex, whatever, you’ve felt this.</p><p>You spend an hour teaching it your codebase. Why this module exists. Which invariant must never break. That one confusing service that looks wrong but is load-bearing. The agent finally <em>gets it</em>, and then the session ends, and all of that evaporates.</p><p>Next session, it starts from zero. It re-reads the same files, re-discovers the same architecture, re-asks the same questions, and re-makes the same mistakes you already corrected yesterday.</p><p>We have a band-aid for this: <strong>CLAUDE.md,</strong> <strong>AGENTS.md</strong>, a notes/ folder. And they help a little. But be honest about what they actually become:</p><ul><li><strong>Unstructured.</strong> A growing dump where nobody can find anything.</li><li><strong>Half-true. </strong>Written once, never checked against the code again. Half of it is quietly stale.</li><li><strong>Too big.</strong> Eventually it’s so large you can’t even load it into context without eating your whole budget.</li><li><strong>Personal.</strong> It lives on <em>your</em> machine and in <em>your </em>head. Your teammate’s agent has no idea it exists.</li></ul><p>So the knowledge an agent builds up is real, but it leaks out the bottom of the bucket every single session.</p><h3>The idea I stole (from Karpathy)</h3><p>I didn’t invent the fix. Andrej Karpathy described its shape in his <a href="https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f">LLM Wiki gist</a>, and it clicked for me immediately. The idea is to stop treating “knowledge” as one blob and split it into <strong>three strict layers</strong>:</p><p>1. <strong>Evidence.</strong> The raw, immutable truth. For software, that’s your code, tests, schemas, configs, and Git history. Nobody edits truth. It just <em>is</em>.</p><p>2. <strong>Compiled wiki.</strong> Knowledge an LLM <em>synthesizes</em> from that evidence and maintains over time: what the system does, where the boundaries are, what must not break, why decisions were made. “<strong>Compiled</strong>” is the important word. It means integrated and contradiction-checked, not a copy-pasted transcript.</p><p>3. <strong>Rules.</strong> A schema and a maintenance policy that govern how the wiki is allowed to evolve: what counts as durable knowledge, what gets thrown away, how you notice when it’s stale.</p><p>The one property that makes this worth-it <strong>knowledge is integrated once, then maintained incrementally</strong>, instead of being re-derived from scratch in every session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7rupDpA8qxOdQ_31xT16g.png" /></figure><blockquote><em>The three layers, mapped onto an actual repo. Evidence is read-only. The wiki is committed. The rules keep it honest.</em></blockquote><h3>What LLM Wiki actually is</h3><p>LLM Wiki is my attempt to make those three layers concrete inside a normal Git repository:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pgxrr-_b29JSaduhq1X4qQ.png" /></figure><p>The most important design decision is that <strong>the wiki is committed and shared</strong>. When your teammate’s agent learns something durable, it writes it todocs/llm-wiki/<em>,</em> commits it, and pushes. After you<strong> </strong>git pull, <em>your</em> agent knows it too. The memory stops being a personal scratchpad and becomes a team asset. The per-machine bookkeeping (the helper binary, local notes) stays gitignored, so only real knowledge is versioned.</p><p>The wiki stores the things agents repeatedly need but can’t cheaply re-derive:</p><ul><li><strong>components/</strong>: what each service, module, and CLI is responsible for</li><li><strong>flows/</strong>: how behavior travels across components, end to end</li><li><strong>contracts/</strong>: APIs, events, schemas, config formats, and who consumes them</li><li><strong>decisions/</strong>: append-only architecture decisions, linked when one supersedes another</li><li><strong>quality/</strong>: invariants that must hold, testing strategy, known failure modes</li><li><strong>operations/</strong>: deployment, observability, recovery</li><li>plus an index, a glossary, a health page (open contradictions), and a maintenance log</li></ul><p>And it deliberately does <strong>not</strong> store code copies, dependency lists, formatting changes, or failed debugging hypotheses. Durable knowledge in, noise out. That “<em>what to leave out</em>” list turned out to be just as important as the “<em>what to keep</em>” list.</p><h3>Getting it into a repo</h3><p>This part I’m reasonably happy with. From the root of any Git repo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJcpqpuGAOnL4NgKwi7bmA.png" /><figcaption>Before we install the LLM-Wiki-dev</figcaption></figure><pre>curl -fsSL https://llm-wiki-dev.salesshortcut.ai/install.sh | bash</pre><p>It downloads a small helper, verifies its SHA-256 checksum, and initializes the repo. It needs only Git, a POSIX shell, curl, tar, and a SHA-256 tool. No Node, Python, Go, or Dart. It’s idempotent, so rerunning it is safe, and it ships for macOS, Linux, and Windows on both arm64 and amd64.</p><p>Here’s what lands:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGh1gSqTutBMhYrnd5S2Xg.png" /><figcaption>Uncomented Structure</figcaption></figure><pre>docs/llm-wiki/ # the wiki, COMMIT this, it&#39;s the team memory<br>llm-wiki.yaml # config + schema version, commit<br>AGENTS.md / CLAUDE.md # a short managed section merged in (your content untouched), commit<br>.llm-wiki/ # helper binary + template, gitignored, per-machine<br>.llm-wiki-state/ # local notes, locks, gitignored</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LxBklTfYLdTtVhyrTcKPew.png" /></figure><p>Your existing <strong>CLAUDE.md</strong> content is preserved. The tool only merges a small marked section, it doesn’t clobber your file. Teammates never pull a binary from Git. Each machine just runs that one command once.</p><p>Then you get a few boring, useful commands:</p><pre>llm-wiki status # is the wiki healthy? validation errors, contradictions, sync state<br>llm-wiki validate # structural check: metadata, unique IDs, working links, evidence paths<br>llm-wiki version</pre><h3>The part I actually think is clever: the sticky-note trick</h3><p>Here’s the question that kept me stuck for a while. A session with an agent is <em>many</em> prompts. So <em>when</em> should the wiki update?</p><p>Not on a timer. That’s arbitrary. Not on every prompt. That’s exhausting and mostly pointless, because most prompts don’t change any durable knowledge. I wanted it to update exactly when the code actually drifts from what the wiki describes, and stay completely silent otherwise.</p><p>The solution is almost embarrassingly simple, so I’ll just describe it plainly.</p><p>Every time the wiki is confirmed up to date, the helper writes a local <strong>sticky note</strong>: <em>”the wiki is good as of this code state.”</em> Then, after every single agent turn, a millisecond-fast check compares your current code against that note:</p><ul><li><strong>You only asked questions.</strong> Nothing changed. So it stays silent.</li><li><strong>You fixed a typo in a comment.</strong> Changed, but not knowledge the wiki stores. So it stays silent.</li><li><strong>You added rate limiting to an API.</strong> Real code drifted from the note. So the agent gets <strong>one</strong> quiet nudge before it finishes: update the affected contract page, re-validate, save a new sticky note. Done.</li><li><strong>You’re mid-feature and just typed “</strong><em>continue</em><strong>”.</strong> The agent decides “<em>nothing durable yet</em>,” records that, and won’t be nagged again until the code actually moves.</li><li><strong>You pulled five teammate commits overnight.</strong> The next session start notices commits it never checked and runs the same quiet pass once.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Txga4klSFgbk0rGZFafBA.png" /></figure><blockquote><em>What happens after every agent turn. The check is deterministic. Only real drift triggers a single quiet update pass.</em></blockquote><p>And here is the design choice I’m proudest of: <strong>that check needs no AI at all.</strong> It’s deterministic file comparison. The <em>judgment</em>, deciding what knowledge actually changed and rewriting the page, is done by the coding agent that is <em>already</em> working in your repo. Which means:</p><ul><li>No second model.</li><li>No API keys.</li><li>No background daemon.</li><li>No network calls during a normal session.</li></ul><p>The whole thing rides on the agent you’re already paying for. That felt right to me. The cheapest place to make the judgment is the agent that already has all the context loaded.</p><p><em>Ýazylan galar, aýdylan uçar</em>. What is written stays, what is spoken flies away.</p><blockquote>That’s the entire pitch in one Turkmen proverb.</blockquote><h3>How the two hooks behave</h3><p>llm-wiki-init<strong> </strong>wires two quiet hooks into .claude/settings.json for Claude Code and .codex/hooks.json for Codex, and commits them, so the whole team gets them on git pull. (Codex asks each developer to approve project hooks once.)</p><h4><strong>Session start</strong></h4><p>Injects a tiny orientation packet (under 1 KB): where the wiki lives, read index.md first, the status/<strong> </strong>validateshortcuts, current health. It also notices commits made outside any session, like a teammate’s merge you just pulled, and flags the material ones for a single audit pass.</p><h4><strong>Stop</strong></h4><p>Runs after every turn and lands in one of four states:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ikJ9-IqRF0ZI58VjSyPOEg.png" /></figure><p>There’s a per-worktree lease so two sessions can’t fight over the wiki, a guard that caps it at one maintenance pass per turn, and, importantly, every hook is a silent no-op in a repo that doesn’t have the helper installed. Nobody gets errors just because they haven’t run the installer.</p><p>One more thing worth knowing: a fresh install starts as an <strong>uncompiled scaffold</strong>. The very first session asks the agent to compile the wiki once from your codebase, then run llm-wiki finalize-init. Drift enforcement only switches on after that. So the tool never nags you about a wiki that doesn’t have real content yet.</p><h3>Where I think this is still weak (the honest part)</h3><h4><strong>What works today</strong></h4><p>The one-command install with checksum verification across five platforms, the full wiki template and schema, safe merging into your existing AGENTS.md / CLAUDE.md, the structural validator, status reporting, evidence fingerprinting, and both quiet hooks wired automatically. All the internal machinery for the lifecycle (change classification, sync notes, per-worktree locks) is implemented and unit-tested.</p><h4><strong>What is not shipped yet</strong></h4><p>The polished recall, sync, and audit skills, and proper plugin packaging for Claude Code and Codex. Right now the agent does the maintenance by following the instructions in the managed section. The packaged, one-click skill experience is next on my list.</p><h4><strong>The open questions I don’t have clean answers for</strong></h4><ul><li>How good is an agent, really, at deciding what counts as <em>durable</em> knowledge versus noise? That judgment is the whole game, and I’ve only tested it on my own repos.</li><li>Does the wiki stay genuinely useful on a large, fast-moving team repo, or does it slowly rot in a new and more confusing way?</li><li>Is committing the wiki to the main repo the right call, or should it live somewhere adjacent?</li></ul><blockquote>I have opinions on all three. I don’t have evidence yet. That’s exactly where I’d love your comments.</blockquote><h3>Try it (and tell me what breaks)</h3><p>If your agents keep forgetting your codebase, give them a memory that survives the session:</p><pre>curl -fsSL https://llm-wiki-dev.salesshortcut.ai/install.sh | bash</pre><p>It’s safe to run on a throwaway repo first ( -dry-run just downloads and verifies), and it won’t touch your existing instruction files beyond a small marked section.</p><p>This is an experiment, not a verdict. If you try it, please tell me where it annoyed you, where the agent made a bad call, or where a totally different design would have been better. I’ll be reading every comment.</p><h3>Links</h3><ul><li><strong>Install:</strong> curl -fsSL <a href="https://llm-wiki-dev.salesshortcut.ai/install.sh">https://llm-wiki-dev.salesshortcut.ai/install.sh</a> | bash</li><li><strong>Repo:</strong> <a href="https://github.com/merdandt/LLM-wiki-dev">https://github.com/merdandt/LLM-wiki-dev</a></li><li><strong>The concept: </strong><a href="https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f">Andrej Karpathy’s LLM Wiki gist</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5c9515cc0b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turn Google ADK into your Gmail and Calendar Assistant]]></title>
            <link>https://medium.com/@meinnps/turn-google-adk-into-your-gmail-and-calendar-assistant-8fee1b1cb05f?source=rss-c93de175ef16------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fee1b1cb05f</guid>
            <category><![CDATA[google-calendar]]></category>
            <category><![CDATA[google-a2a]]></category>
            <category><![CDATA[adkhackathon]]></category>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[google-gmail]]></category>
            <dc:creator><![CDATA[Merdan Durdyyev]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 21:31:20 GMT</pubDate>
            <atom:updated>2025-07-25T15:08:23.280Z</atom:updated>
            <content:encoded><![CDATA[<h4>Short yet Powerful Tutorial: Google ADK + Gmail + Calendar</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qqkv6arv0PNOhjoRyZ1pAg.png" /></figure><p>In this hands-on guide, you’ll learn exactly how to integrate Gmail and Google Calendar into your ADK agent. Less theory, more practice—so you can get up and running fast.</p><h3>Background</h3><p>We just won the Grand Prize of the <a href="https://googlecloudmultiagents.devpost.com/?ref_feature=challenge&amp;ref_medium=your-open-hackathons&amp;ref_content=Submissions+open&amp;_gl=1*h2zea8*_gcl_au*NTg1OTM4MzY5LjE3NDg1MzI4NTk.*_ga*MTA0MTUyMjg0OC4xNzUwNjcyNjQw*_ga_0YHJK3Y10M*czE3NTA3MDM5NjIkbzQkZzEkdDE3NTA3MDYxMTAkajU1JGwwJGgw"><strong>Agent Development Kit Hackathon</strong></a> with Google Cloud, where we, with <a href="https://medium.com/u/eb9c9f13dec4">Sergazy Nurbavliyev,</a> built a feature-rich integration using Gmail and Calendar for an autonomous SDR system that discovers leads, researches prospects, and makes phone calls—all powered by Google’s Gemini 2.0 and modern AI agents<em>.</em></p><p>During my search, I couldn’t find a simple, quick-start guide—just scattered documentation and fragmented examples. So, I took the long road, absorbed the complexity, and figured it out step by step.</p><p>Now I’m sharing everything I wish I had at the start—a clear, beginner-friendly path to building this integration.</p><p>We’ll use <strong>Google Colab</strong> to make things easy and reproducible. I’ll provide the notebook at the end so you can follow along and try it yourself.</p><p>Let’s start with getting your credentials.</p><h3>Getting the credentials from the Google Cloud Console</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tH0vghNWC1qSu2gOYvLGWg.png" /></figure><p>To obtain the required credentials, open <strong>Google Cloud Console</strong>, navigate to <strong>APIs &amp; Services → Credentials</strong>, and first configure an <strong>OAuth consent screen</strong> with the basic information Google asks for (app name, support email, etc.) so that users can authorize your app properly.</p><p>Next, click <strong>Create Credentials → OAuth client ID</strong>, pick <strong>“Web application”</strong>, give the client a meaningful name, and—crucially—add at least one <strong>Authorized redirect URI</strong> (for local testing, a common choice is <strong>http://localhost:8000/callback</strong>) so Google knows where to send the user after they grant access. After saving, Google will display the <strong>Client ID</strong> and <strong>Client Secret</strong>; copy both of these (or download a JSON), along with the redirect URI you just registered, because you will need all three values in your code or environment variables whenever your agents initiate OAuth flows. Save the JSON or variables into you Colab secrets</p><h3>Part 1: Setting Up the Foundation</h3><p>Every project starts with the right tools. The first step is to set up the Python environment and install the necessary libraries.</p><pre>!pip install google-adk -q <br>!pip install litellm -q <br>!pip install deprecated -q <br>!pip install typing-extensions -q <br>!pip install google-cloud-aiplatform -q</pre><p>With the libraries installed, the next step is to import all the necessary modules into our script.</p><pre># @title Import necessary libraris<br>import os<br>import asyncio<br>from google.adk.agents import Agent<br>from google.adk.models.lite_llm import LiteLlm<br>from google.adk.sessions import InMemorySessionService<br>from google.adk.runners import Runner<br>from google.genai import types # For creating message Content/Parts<br><br>import warnings<br># Ignore all warnings<br>warnings.filterwarnings(&quot;ignore&quot;)<br><br>import logging<br>logging.basicConfig(level=logging.ERROR)<br><br>print(&quot;Libraries imported.&quot;)</pre><h3>Part 2: Authentication—The Keys to the Kingdom</h3><p>To allow our agent to access private user data, we need to handle authentication using an API key for Gemini and OAuth 2.0 credentials for Google services. In Google Colab, we can use the userdatafeature to securely store and access these secrets.</p><pre>from google.colab import userdata<br><br># --- IMPORTANT: Replace placeholders with your real API keys ---<br><br># Make sure to add these secrets to your Colab environment<br># (Click the key icon on the left sidebar)<br>try:<br>    api_key = userdata.get(&#39;GEMINI_API_KEY&#39;)<br>    os.environ[&quot;GEMINI_API_KEY&quot;] = api_key<br>    GOOGLE_CLOUD_CLIENT_ID = userdata.get(&#39;GOOGLE_CLOUD_CLIENT_ID&#39;)<br>    GOOGLE_CLOUD_CLIENT_SECRET = userdata.get(&#39;GOOGLE_CLOUD_CLIENT_SECRET&#39;)<br>    GEMINI_API_KEY = userdata.get(&#39;GEMINI_API_KEY&#39;)<br>    MODEL = &quot;gemini-1.5-flash&quot;<br><br>    # For Google Admin Workspace project (later)<br>    CLOUD_PROJECT_ID=&quot;your-id&quot;<br>    CLOUD_PROJECT_REGION=&quot;us-central1&quot;<br>    print(&quot;Secrets loaded successfully.&quot;)<br>except Exception as e:<br>    print(&quot;Could not load secrets. Please make sure you have added GEMINI_API_KEY, GOOGLE_CLOUD_CLIENT_ID, and GOOGLE_CLOUD_CLIENT_SECRET to your Colab secrets.&quot;)<br><br></pre><p>or from the JSON we just downloaded</p><pre># prompt: import client_secret_762506172719-jkc8verldrb6lfcabkb42t65pr9l36q8 and set dredentials just for client id and secret from that json client_id = client_info.get(web).get(&#39;client_id&#39;)<br><br>import json<br><br>with open(&#39;/content/client_secret_76...9l36q8.apps.googleusercontent.com.json&#39;, &#39;r&#39;) as f:<br>  client_info = json.load(f)<br><br># Assuming your client secret file has a &#39;web&#39; key with &#39;client_id&#39; and &#39;client_secret&#39;<br>client_id = client_info.get(&#39;web&#39;).get(&#39;client_id&#39;)<br>client_secret = client_info.get(&#39;web&#39;).get(&#39;client_secret&#39;)<br><br>print(client_id)<br>print(client_secret)</pre><h3>Part 3: Defining the Agent and Tools</h3><p>Now we define the agent and give it tools. The ADK provides pre-built and makes GmailToolset and CalendarToolset integration simple.</p><pre>from google.adk.auth import AuthConfig<br>from google.adk.agents import Agent<br>from google.adk.events import Event<br>from google.adk.runners import Runner<br>from google.adk.sessions import InMemorySessionService<br>from google.adk.tools.google_api_tool import GmailToolset, CalendarToolset<br><br>from google.genai import types<br><br><br>import asyncio<br>import base64<br>from email.mime.text import MIMEText<br>from email.mime.multipart import MIMEMultipart<br>from email.mime.base import MIMEBase<br>from email import encoders<br>import os # Import os for path handling<br><br># --- Helper Functions ---<br>async def get_user_input(prompt: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Asynchronously prompts the user for input in the console.<br><br>    Uses asyncio&#39;s event loop and run_in_executor to avoid blocking the main<br>    asynchronous execution thread while waiting for synchronous `input()`.<br><br>    Args:<br>        prompt: The message to display to the user.<br><br>    Returns:<br>        The string entered by the user.<br>    &quot;&quot;&quot;<br>    loop = asyncio.get_event_loop()<br>    # Run the blocking `input()` function in a separate thread managed by the executor.<br>    return await loop.run_in_executor(None, input, prompt)<br><br><br>def is_pending_auth_event(event: Event) -&gt; bool:<br>    &quot;&quot;&quot;<br>    Checks if an ADK Event represents a request for user authentication credentials.<br><br>    The ADK framework emits a specific function call (&#39;adk_request_credential&#39;)<br>    when a tool requires authentication that hasn&#39;t been previously satisfied.<br><br>    Args:<br>        event: The ADK Event object to inspect.<br><br>    Returns:<br>        True if the event is an &#39;adk_request_credential&#39; function call, False otherwise.<br>    &quot;&quot;&quot;<br>    # Safely checks nested attributes to avoid errors if event structure is incomplete.<br>    return (<br>        event.content<br>        and event.content.parts<br>        and any(<br>            part.function_call<br>            and part.function_call.name == &#39;adk_request_credential&#39;<br>            for part in event.content.parts<br>        )<br>    )<br><br><br>def get_function_call_id(event: Event) -&gt; str:<br>    &quot;&quot;&quot;<br>    Extracts the unique ID of the function call from an ADK Event.<br><br>    This ID is crucial for correlating a function *response* back to the specific<br>    function *call* that the agent initiated to request for auth credentials.<br><br>    Args:<br>        event: The ADK Event object containing the function call.<br><br>    Returns:<br>        The unique identifier string of the function call.<br><br>    Raises:<br>        ValueError: If the function call ID cannot be found in the event structure.<br>    &quot;&quot;&quot;<br>    if (<br>        event<br>        and event.content<br>        and event.content.parts<br>    ):<br>        for part in event.content.parts:<br>            if part.function_call and part.function_call.id:<br>                return part.function_call.id<br>    # If the ID is missing, raise an error indicating an unexpected event format.<br>    raise ValueError(f&#39;Cannot get function call id from event {event}&#39;)<br><br><br>def get_function_call_auth_config(event: Event) -&gt; AuthConfig:<br>    &quot;&quot;&quot;<br>    Extracts the authentication configuration details from an &#39;adk_request_credential&#39; event.<br><br>    Client should use this AuthConfig to necessary authentication details (like OAuth codes and state)<br>    and sent it back to the ADK to continue OAuth token exchanging.<br><br>    Args:<br>        event: The ADK Event object containing the &#39;adk_request_credential&#39; call.<br><br>    Returns:<br>        An AuthConfig object populated with details from the function call arguments.<br><br>    Raises:<br>        ValueError: If the &#39;auth_config&#39; argument cannot be found in the event.<br>    &quot;&quot;&quot;<br>    if (<br>        event<br>        and event.content<br>        and event.content.parts<br>    ):<br>        for part in event.content.parts:<br>            if (<br>                part.function_call<br>                and part.function_call.name == &#39;adk_request_credential&#39;<br>                and part.function_call.args<br>                and part.function_call.args.get(&#39;authConfig&#39;)<br>            ):<br>                return AuthConfig(<br>                    **part.function_call.args.get(&#39;authConfig&#39;)<br>                )<br><br>    raise ValueError(f&#39;Cannot get auth config from event {event}&#39;)<br><br># Helper function to create RFC822 formatted message<br>def create_rfc822_message(to_email: str, subject: str, body: str, from_email: str = None, file_paths: list = None):<br>    &quot;&quot;&quot;<br>    Creates an RFC822 formatted message string with optional attachments that Gmail API can use.<br><br>    Args:<br>        to_email: Recipient email address<br>        subject: Email subject<br>        body: Email body text<br>        from_email: Sender email (optional, will use authenticated user&#39;s email if not provided)<br>        file_paths: A list of file paths to attach (e.g., [&#39;path/to/file1.pdf&#39;, &#39;path/to/image.png&#39;])<br><br>    Returns:<br>        Base64 encoded RFC822 message string<br>    &quot;&quot;&quot;<br>    if file_paths:<br>        # Create a multipart message for attachments<br>        msg = MIMEMultipart()<br>    else:<br>        # Create a simple text message if no attachments<br>        msg = MIMEText(body, &#39;plain&#39;)<br><br>    msg[&#39;To&#39;] = to_email<br>    msg[&#39;Subject&#39;] = subject<br><br>    # Add From header if provided<br>    if from_email:<br>        msg[&#39;From&#39;] = from_email<br><br>    # Attach the email body if it&#39;s a multipart message<br>    if file_paths:<br>        msg.attach(MIMEText(body, &#39;plain&#39;))<br><br>        for file_path in file_paths:<br>            try:<br>                # Guess the MIME type of the file<br>                import mimetypes<br>                content_type, encoding = mimetypes.guess_type(file_path)<br><br>                if content_type is None or encoding is not None:<br>                    content_type = &#39;application/octet-stream&#39; # Default if type can&#39;t be guessed<br><br>                main_type, sub_type = content_type.split(&#39;/&#39;, 1)<br><br>                with open(file_path, &#39;rb&#39;) as f:<br>                    file_data = f.read()<br><br>                if main_type == &#39;text&#39;:<br>                    part = MIMEText(file_data.decode(&#39;utf-8&#39;), _subtype=sub_type)<br>                else:<br>                    part = MIMEBase(main_type, sub_type)<br>                    part.set_payload(file_data)<br>                    encoders.encode_base64(part) # Encode content to base64<br><br>                # Add header with the filename<br>                filename = os.path.basename(file_path)<br>                part.add_header(&#39;Content-Disposition&#39;, &#39;attachment&#39;, filename=filename)<br>                msg.attach(part)<br><br>            except Exception as e:<br>                print(f&quot;Error attaching file {file_path}: {e}&quot;)<br>                # You might want to handle this error more gracefully, e.g., raise an exception<br>                continue # Continue to the next file if one fails<br><br>    # Convert to RFC822 format and encode<br>    rfc822_message = msg.as_string()<br><br>    # Gmail API expects the message to be base64url encoded<br>    encoded_message = base64.urlsafe_b64encode(rfc822_message.encode(&#39;utf-8&#39;)).decode(&#39;utf-8&#39;)<br><br>    return encoded_message<br><br>gmail_tool = GmailToolset(<br>    client_id = GOOGLE_CLOUD_CLIENT_ID,<br>    client_secret = GOOGLE_CLOUD_CLIENT_SECRET<br>)<br><br>gmail_tool.configure_auth(<br>    client_id=GOOGLE_CLOUD_CLIENT_ID,<br>    client_secret=GOOGLE_CLOUD_CLIENT_SECRET<br>)<br><br>calendar_tool = CalendarToolset(<br>    client_id = GOOGLE_CLOUD_CLIENT_ID,<br>    client_secret = GOOGLE_CLOUD_CLIENT_SECRET<br>)<br><br>calendar_tool.configure_auth(<br>    client_id=GOOGLE_CLOUD_CLIENT_ID,<br>    client_secret=GOOGLE_CLOUD_CLIENT_SECRET<br>)<br><br><br>gmail_agent = Agent(<br>    name=&quot;gmail_agent_v1&quot;,<br>    model=MODEL,<br>    description=&quot;Have access to the Gmail and Calendar services and can send read emails and view, create evnets on calendar&quot;,<br>    instruction=&quot;&quot;&quot;<br>    You are the Gmail assistant. You can use the &#39;gmail_tool&#39; to access, read and send emails.<br>    &quot;&quot;&quot;,<br>    tools=[gmail_tool, calendar_tool],<br>)<br><br></pre><h3>Part 4: Running the Agent and Handling Tasks</h3><p>The Runner manages the interaction loop and a SessionService keeps track of the conversation history. The call_agent_with_auth_flow function sends a user&#39;s query to the agent and manages the authentication handshake.</p><pre># --- Session Management ---<br>session_service = InMemorySessionService()<br>APP_NAME = &quot;google_toolset_hackathon_app&quot;<br>USER_ID = &quot;user_1&quot;<br>SESSION_ID = &quot;session_001&quot;<br>session = await session_service.create_session(<br>    app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID<br>)<br>print(f&quot;Session created: App=&#39;{APP_NAME}&#39;, User=&#39;{USER_ID}&#39;, Session=&#39;{SESSION_ID}&#39;&quot;)<br><br># --- Runner ---<br>runner = Runner(agent=gmail_agent, app_name=APP_NAME, session_service=session_service)<br>print(f&quot;Runner created for agent &#39;{runner.agent.name}&#39;.&quot;)<br><br><br>async def call_agent_with_auth_flow(query: str, runner, user_id, session_id):<br>    &quot;&quot;&quot;Sends a query to the agent and handles the full authentication flow.&quot;&quot;&quot;<br>    print(f&quot;\n&gt;&gt;&gt; User Query: {query}&quot;)<br>    content = types.Content(role=&#39;user&#39;, parts=[types.Part(text=query)])<br>    auth_request_function_call_id, auth_config = None, None<br>    final_response_text = &quot;Agent did not produce a final response.&quot;<br><br>    # --- First Run: Send initial query ---<br>    print(&quot;\nRunning agent...&quot;)<br>    async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=content):<br>        print(f&quot;  [Event] Author: {event.author}, Final: {event.is_final_response()}, Content: {event.content}&quot;)<br>        if is_pending_auth_event(event):<br>            print(&quot;--&gt; Authentication required by agent.&quot;)<br>            auth_request_function_call_id = get_function_call_id(event)<br>            auth_config = get_function_call_auth_config(event)<br>            break<br>        if event.is_final_response():<br>            if event.content and event.content.parts:<br>                final_response_text = event.content.parts[0].text<br>            break<br><br>    # --- Handle Authentication if required ---<br>    if auth_request_function_call_id and auth_config:<br>        # IMPORTANT: This must match a URI in your GCP OAuth Client settings<br>        redirect_uri = &#39;http://localhost:8000/callback&#39; # This won&#39;t work directly in Colab without a tunnel<br><br>        if (auth_config.exchanged_auth_credential and<br>            auth_config.exchanged_auth_credential.oauth2 and<br>            auth_config.exchanged_auth_credential.oauth2.auth_uri):<br><br>            base_auth_uri = auth_config.exchanged_auth_credential.oauth2.auth_uri<br>            auth_request_uri = base_auth_uri + f&#39;&amp;redirect_uri={redirect_uri}&#39;<br><br>            print(&quot;\n--- User Action Required ---&quot;)<br>            print(f&#39;1. Please open this URL in your browser to authorize:\n   {auth_request_uri}\n&#39;)<br>            print(&#39;2. After authorizing, copy the *entire* URL from your browser\&#39;s address bar.&#39;)<br>            print(f&#39;3. Paste the copied URL here and press Enter:\n&#39;)<br><br>            auth_response_uri = await get_user_input(&#39;&gt; &#39;)<br>            auth_config.exchanged_auth_credential.oauth2.auth_response_uri = auth_response_uri<br>            auth_config.exchanged_auth_credential.oauth2.redirect_uri = redirect_uri<br><br>            auth_content = types.Content(role=&#39;user&#39;, parts=[types.Part(<br>                function_response=types.FunctionResponse(<br>                    id=auth_request_function_call_id,<br>                    name=&#39;adk_request_credential&#39;,<br>                    response=auth_config.model_dump(),<br>                ))])<br><br>            # --- Second Run: Resume agent with auth details ---<br>            print(&quot;\nSubmitting authentication details back to the agent...&quot;)<br>            async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=auth_content):<br>                print(f&quot;  [Event] Author: {event.author}, Final: {event.is_final_response()}, Content: {event.content}&quot;)<br>                if event.is_final_response():<br>                    if event.content and event.content.parts:<br>                        final_response_text = event.content.parts[0].text<br>                    break<br>        else:<br>            final_response_text = &quot;Error: Authentication URI not found.&quot;<br><br>    print(f&quot;\n&lt;&lt;&lt; Agent Response: {final_response_text}&quot;)<br>    return final_response_text</pre><h4>Example 1: Sending an Email</h4><p>The gmail_users_messages_send tool requires the email content to be in a specific base64-encoded RFC822 format.</p><pre># --- Create the RFC822 formatted message ---<br>rfc822_message = create_rfc822_message(<br>    to_email=&quot;your_email@example.com&quot;, # CHANGE THIS<br>    subject=&quot;Sales ADK Hackathon Check-in&quot;,<br>    body=&quot;Hi, this is a test email sent from my Google ADK agent. The integration is working!&quot;,<br>)<br><br># --- Construct the query for the agent ---<br>email_query = f&quot;&quot;&quot;<br>Please send an email using the gmail_users_messages_send tool with the following parameters:<br>- userId: &#39;me&#39;<br>- message: &#39;{rfc822_message}&#39;<br><br>This message is already properly formatted in RFC822 format and base64url encoded.<br>&quot;&quot;&quot;<br><br># --- Run the agent ---<br># Note: The auth flow will require manual steps.<br># await call_agent_with_auth_flow(email_query, runner=runner, user_id=USER_ID, session_id=SESSION_ID)<br>print(&quot;Email query is ready. Uncomment the line above to run the agent.&quot;)</pre><p>The result should be like that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*I3jIXk97CCvIqx53QKM7JA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WyOCvReQH8XbObiCYdaTfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMxkuZXPkkfU8YDudPMcBQ.png" /></figure><p>Copy the URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rc1B_IkyTKOQVpnKSteD_Q.png" /></figure><p>Paste it,, and you are ready to receive the email.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*Mrw_92V4TxQfUlkmhnpEoQ.png" /></figure><blockquote>Now you have got the idea, let’s continue.</blockquote><h4>Example 2: Reading Recent Emails</h4><p>This demonstrates the agent’s ability to read emails.</p><pre># --- Query to read emails ---<br>read_email_query = &quot;Read the subject of my 2 most recent unread emails.&quot;<br><br># --- Run the agent ---<br># await call_agent_with_auth_flow(read_email_query, runner=runner, user_id=USER_ID, session_id=SESSION_ID)<br>print(&quot;Read email query is ready. Uncomment the line above to run the agent.&quot;)</pre><h4>Example 3: Creating a Calendar Event</h4><p>The agent parses a natural language request to create a calendar event.</p><pre># --- Query to create a calendar event ---<br>create_event_query = (<br>    &quot;Schedule a meeting with &#39;example.customer@email.com&#39; for tomorrow at 3 PM &quot;<br>    &quot;titled &#39;Project Follow-up&#39;. Set the duration to 45 minutes and add a &quot;<br>    &quot;description that says &#39;Discussing next steps for the project.&#39;&quot;<br>)<br><br># --- Run the agent ---<br># await call_agent_with_auth_flow(create_event_query, runner=runner, user_id=USER_ID, session_id=SESSION_ID)<br>print(&quot;Create event query is ready. Uncomment the line above to run the agent.&quot;)</pre><h3>Part 5: Alternative: Using a Service Account for Full Automation</h3><p>Ok, but I want to send the email without human interaction, right?</p><p>But before that you need to spend some time to get things done first.</p><h4>Create the Service Account in Google Cloud</h4><p>First, you need to create a service account and its key.</p><p><strong>Go to the Service Accounts page:</strong></p><ul><li>Open the Google Cloud Console and navigate to the <a href="https://console.cloud.google.com/iam-admin/serviceaccounts"><strong>Service Accounts</strong></a> page.</li><li>Select the project you are using for this integration.</li></ul><p><strong>Create the Service Account:</strong></p><ul><li>Click <strong>+ CREATE SERVICE ACCOUNT</strong>.</li><li>Give it a <strong>Service account name</strong> (e.g., “sales-automation-agent”) and an optional description. The <strong>Service account ID</strong> will be generated automatically.</li><li>Click <strong>CREATE AND CONTINUE</strong>.</li></ul><p><strong>Grant Access (Optional but Recommended):</strong></p><ul><li>You can grant the service account roles on the project, but for this use case, the primary permissions will be granted via domain-wide delegation. You can skip adding project-level roles for now.</li><li>Click <strong>CONTINUE</strong>.</li></ul><p><strong>Create a Key:</strong></p><ul><li>In the “Grant users access to this service account” step, scroll down to the <strong>Keys</strong> section and click <strong>+ CREATE KEY</strong>.</li><li>Select <strong>JSON</strong> as the key type and click <strong>CREATE</strong>.</li><li>A JSON file containing your service account’s private key will be downloaded to your computer. <strong>Treat this file like a password; it is highly sensitive.</strong> You will need to upload this file to your Colab environment (e.g., as sales-automation-service.json).</li></ul><p><strong>Find the Client ID:</strong></p><ul><li>After creating the key, you will be returned to the service accounts list. Click on the service account you just created.</li><li>Go to the <strong>Details</strong> tab.</li><li>Find and copy the <strong>Unique ID</strong> (this is a long number, e.g., 112233445566778899000). This is the <strong>Client ID</strong> you will need for the next part.</li></ul><h4>Authorize the Service Account in Google Workspace (Domain-Wide Delegation)</h4><p>Next, a Google Workspace administrator must authorize the service account to access user data.</p><p><strong>Go to your Google Workspace Admin console:</strong></p><ul><li>Open the <a href="http://admin.google.com/">Google Workspace Admin console</a>.</li><li>Navigate to <strong>Security &gt; Access and data control &gt; API controls</strong>.</li></ul><p><strong>Manage Domain-Wide Delegation:</strong></p><ul><li>In the “API controls” section, click on <strong>MANAGE DOMAIN WIDE DELEGATION</strong>.</li></ul><p><strong>Add a New API Client:</strong></p><ul><li>Click <strong>Add new</strong>.</li><li>In the <strong>Client ID</strong> field, paste the <strong>Unique ID</strong> of the service account you copied from the Google Cloud Console in the previous section.</li><li>In the <strong>OAuth scopes (comma-delimited)</strong> field, you must enter the specific API scopes your application needs. For the examples in Canvas, you would need:</li></ul><pre>https://www.googleapis.com/auth/gmail.send,https://www.googleapis.com/auth/gmail.readonly,https://www.googleapis.com/auth/gmail.modify,https://www.googleapis.com/auth/calendar,https://www.googleapis.com/auth/calendar.events</pre><p><strong>Authorize:</strong></p><ul><li>Click <strong>Authorize</strong>. The client will now appear in the list, and your service account is ready to make API calls on behalf of users in your domain.</li></ul><h4>Setting up the Environment for Service Accounts</h4><p>A service account is a non-human user that can be authorized to access Google Workspace data on behalf of users in your organization without manual interaction.</p><pre>!pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client -q<br>print(&quot;Service Account libraries installed.&quot;)</pre><blockquote>Before you begin, check the domain-wide delegation</blockquote><pre>import json<br>from google.oauth2 import service_account<br>from google.auth.transport.requests import Request<br><br>def test_delegation():<br>    SERVICE_ACCOUNT_FILE = &#39;sales-automation-service.json&#39;<br>    SALES_EMAIL = &#39;sales@zemzen.org&#39;<br>    SCOPES = [<br>        &#39;https://www.googleapis.com/auth/gmail.send&#39;,<br>        &#39;https://www.googleapis.com/auth/gmail.readonly&#39;,<br>        &#39;https://www.googleapis.com/auth/gmail.modify&#39;<br>    ]<br><br>    try:<br>        # Load service account info<br>        with open(SERVICE_ACCOUNT_FILE, &#39;r&#39;) as f:<br>            sa_info = json.load(f)<br><br>        print(&quot;📋 Service Account Information:&quot;)<br>        print(f&quot;   Client ID: {sa_info[&#39;client_id&#39;]}&quot;)<br>        print(f&quot;   Client Email: {sa_info[&#39;client_email&#39;]}&quot;)<br>        print(f&quot;   Project ID: {sa_info[&#39;project_id&#39;]}&quot;)<br>        print(f&quot;   Target User: {SALES_EMAIL}&quot;)<br><br>        print(f&quot;\n🔑 COPY THIS CLIENT ID TO GOOGLE ADMIN CONSOLE:&quot;)<br>        print(f&quot;   {sa_info[&#39;client_id&#39;]}&quot;)<br><br>        print(f&quot;\n🔗 COPY THESE SCOPES TO GOOGLE ADMIN CONSOLE:&quot;)<br>        print(f&quot;   https://www.googleapis.com/auth/gmail.send,https://www.googleapis.com/auth/gmail.readonly,https://www.googleapis.com/auth/gmail.modify&quot;)<br><br>        # Test domain-wide delegation<br>        print(f&quot;\n🧪 Testing domain-wide delegation...&quot;)<br><br>        credentials = service_account.Credentials.from_service_account_file(<br>            SERVICE_ACCOUNT_FILE, scopes=SCOPES<br>        )<br>        delegated_creds = credentials.with_subject(SALES_EMAIL)<br>        delegated_creds.refresh(Request())<br><br>        print(&quot;✅ SUCCESS! Domain-wide delegation is working!&quot;)<br>        print(&quot;🎉 You can now send emails!&quot;)<br>        return True<br><br>    except Exception as e:<br>        error_str = str(e)<br>        print(f&quot;\n❌ FAILED: {error_str}&quot;)<br><br>        if &#39;invalid_scope&#39; in error_str:<br>            print(&quot;\n🚨 DOMAIN-WIDE DELEGATION NOT CONFIGURED!&quot;)<br>            print(&quot;📝 Go to admin.google.com and configure it with the info above&quot;)<br><br>        return False<br><br># Run the test<br>test_delegation()</pre><h4>Example 1: Sending an Email with a Service Account</h4><p>This script uses a service account with delegated credentials to send an email. You will need to create a service account in your Google Cloud Project, grant it domain-wide delegation, and download the JSON key file.</p><blockquote>You will need to upload your service account JSON file and a sample PDF to your Colab environment for this to work.</blockquote><pre>import json<br>import base64<br>import os<br>import mimetypes<br>from email.mime.text import MIMEText<br>from email.mime.multipart import MIMEMultipart<br>from email.mime.base import MIMEBase<br>from email import encoders<br>from google.oauth2 import service_account<br>from googleapiclient.discovery import build<br><br>def send_email_from_sales_with_attachment():<br>    &quot;&quot;&quot;Send email from sales@zemzen.org to meinnps@gmail.com with PDF attachment&quot;&quot;&quot;<br><br>    # Configuration<br>    SERVICE_ACCOUNT_FILE = &#39;sales-automation-service.json&#39;<br>    SALES_EMAIL = &#39;sales@zemzen.org&#39;<br>    TARGET_EMAIL = &#39;meinnps@gmail.com&#39;<br>    ATTACHMENT_PATH = &#39;/content/SalesShortcut_Proposal.pdf&#39;  # Your PDF attachment<br><br>    SCOPES = [<br>        &#39;https://www.googleapis.com/auth/gmail.send&#39;,<br>        &#39;https://www.googleapis.com/auth/gmail.readonly&#39;,<br>        &#39;https://www.googleapis.com/auth/gmail.modify&#39;<br>    ]<br><br>    try:<br>        print(&quot;📧 Preparing to send email with attachment...&quot;)<br>        print(f&quot;   From: {SALES_EMAIL}&quot;)<br>        print(f&quot;   To: {TARGET_EMAIL}&quot;)<br>        print(f&quot;   Attachment: {ATTACHMENT_PATH}&quot;)<br><br>        # Check if attachment exists<br>        if not os.path.exists(ATTACHMENT_PATH):<br>            print(f&quot;⚠️  Warning: Attachment file not found at {ATTACHMENT_PATH}&quot;)<br>            print(&quot;   Sending email without attachment...&quot;)<br>            ATTACHMENT_PATH = None<br><br>        # Create credentials<br>        credentials = service_account.Credentials.from_service_account_file(<br>            SERVICE_ACCOUNT_FILE, scopes=SCOPES<br>        )<br>        delegated_creds = credentials.with_subject(SALES_EMAIL)<br><br>        # Create Gmail service<br>        service = build(&#39;gmail&#39;, &#39;v1&#39;, credentials=delegated_creds)<br><br>        # Create email message<br>        subject = &quot;Sales Proposal - SalesShortcut Solution 🚀&quot;<br>        body = &quot;&quot;&quot;<br>Hello!<br><br>We&#39;re excited to share our SalesShortcut proposal with you. Please find the detailed proposal document attached.<br><br>📎 **Attached Document:** SalesShortcut_Proposal.pdf<br><br>**Key highlights:**<br>✅ Automated email campaigns<br>✅ Advanced customer tracking<br>✅ Seamless integration capabilities<br>✅ Comprehensive analytics dashboard<br><br>This proposal outlines how SalesShortcut can streamline your sales processes and boost your team&#39;s productivity.<br><br>We&#39;d love to schedule a call to discuss this proposal in detail and answer any questions you might have.<br><br>Best regards,<br>**Sales Team**<br>Zemzen Organization<br><br>📧 sales@zemzen.org<br>📞 Contact us for a demo!<br><br>P.S. - This email was sent using our automated system, demonstrating one of the many capabilities we can implement for your business!<br>        &quot;&quot;&quot;<br><br>        # Create multipart message for attachment<br>        if ATTACHMENT_PATH and os.path.exists(ATTACHMENT_PATH):<br>            message = MIMEMultipart()<br>            message.attach(MIMEText(body, &#39;plain&#39;))<br><br>            # Add attachment<br>            print(&quot;📎 Adding PDF attachment...&quot;)<br><br>            # Determine MIME type<br>            content_type, encoding = mimetypes.guess_type(ATTACHMENT_PATH)<br>            if content_type is None or encoding is not None:<br>                content_type = &#39;application/pdf&#39;  # Default for PDF<br><br>            main_type, sub_type = content_type.split(&#39;/&#39;, 1)<br><br>            # Read the file<br>            with open(ATTACHMENT_PATH, &#39;rb&#39;) as attachment_file:<br>                file_data = attachment_file.read()<br><br>            # Create attachment part<br>            attachment_part = MIMEBase(main_type, sub_type)<br>            attachment_part.set_payload(file_data)<br>            encoders.encode_base64(attachment_part)<br><br>            # Add header with filename<br>            filename = os.path.basename(ATTACHMENT_PATH)<br>            attachment_part.add_header(<br>                &#39;Content-Disposition&#39;,<br>                f&#39;attachment; filename= {filename}&#39;<br>            )<br><br>            # Attach to message<br>            message.attach(attachment_part)<br>            print(f&quot;✅ Attachment added: {filename}&quot;)<br><br>        else:<br>            # Simple text message if no attachment<br>            message = MIMEText(body, &#39;plain&#39;)<br><br>        # Set email headers<br>        message[&#39;to&#39;] = TARGET_EMAIL<br>        message[&#39;from&#39;] = SALES_EMAIL<br>        message[&#39;subject&#39;] = subject<br><br>        # Send email<br>        print(&quot;📤 Sending email...&quot;)<br>        raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode(&#39;utf-8&#39;)<br><br>        result = service.users().messages().send(<br>            userId=&#39;me&#39;,<br>            body={&#39;raw&#39;: raw_message}<br>        ).execute()<br><br>        print(&quot;✅ EMAIL SENT SUCCESSFULLY!&quot;)<br>        print(f&quot;   Message ID: {result.get(&#39;id&#39;)}&quot;)<br>        print(f&quot;   Thread ID: {result.get(&#39;threadId&#39;)}&quot;)<br>        if ATTACHMENT_PATH and os.path.exists(ATTACHMENT_PATH):<br>            print(f&quot;   📎 Attachment: {os.path.basename(ATTACHMENT_PATH)} included&quot;)<br>        print(f&quot;   📬 Check {TARGET_EMAIL} inbox!&quot;)<br><br>        return result<br><br>    except Exception as e:<br>        print(f&quot;❌ Error sending email: {e}&quot;)<br>        return None<br><br># Send the email with attachment<br>print(&quot;🚀 Sending Sales Proposal Email with PDF Attachment&quot;)<br>print(&quot;=&quot; * 60)<br>send_email_from_sales_with_attachment()Example 2: Checking for Unread Emails with a Service Account</pre><h4>Example 2: Checking for Unread Emails with a Service Account</h4><p>This script can run in the background to check an inbox for unread messages.</p><pre>import json<br>import base64<br>from google.oauth2 import service_account<br>from googleapiclient.discovery import build<br>from datetime import datetime<br>import html<br><br>def check_unread_emails():<br>    &quot;&quot;&quot;Check unread emails and access all threads for sales@zemzen.org&quot;&quot;&quot;<br><br>    # Configuration<br>    SERVICE_ACCOUNT_FILE = &#39;sales-automation-service.json&#39;<br>    SALES_EMAIL = &#39;sales@zemzen.org&#39;<br><br>    SCOPES = [<br>        &#39;https://www.googleapis.com/auth/gmail.readonly&#39;,<br>        &#39;https://www.googleapis.com/auth/gmail.modify&#39;<br>    ]<br><br>    try:<br>        print(&quot;📬 Checking unread emails...&quot;)<br>        print(f&quot;   Account: {SALES_EMAIL}&quot;)<br>        print(&quot;=&quot; * 60)<br><br>        # Create credentials with delegation<br>        credentials = service_account.Credentials.from_service_account_file(<br>            SERVICE_ACCOUNT_FILE, scopes=SCOPES<br>        )<br>        delegated_creds = credentials.with_subject(SALES_EMAIL)<br><br>        # Create Gmail service<br>        service = build(&#39;gmail&#39;, &#39;v1&#39;, credentials=delegated_creds)<br><br>        # Get unread messages<br>        results = service.users().messages().list(<br>            userId=&#39;me&#39;,<br>            q=&#39;is:unread&#39;,<br>            maxResults=50<br>        ).execute()<br><br>        messages = results.get(&#39;messages&#39;, [])<br><br>        if not messages:<br>            print(&quot;✅ No unread emails found!&quot;)<br>            return []<br><br>        print(f&quot;📧 Found {len(messages)} unread email(s)&quot;)<br>        print(&quot;=&quot; * 60)<br><br>        unread_emails = []<br><br>        for i, message in enumerate(messages, 1):<br>            message_id = message[&#39;id&#39;]<br><br>            # Get detailed message info<br>            msg = service.users().messages().get(<br>                userId=&#39;me&#39;,<br>                id=message_id,<br>                format=&#39;full&#39;<br>            ).execute()<br><br>            # Extract headers<br>            headers = msg[&#39;payload&#39;].get(&#39;headers&#39;, [])<br>            subject = next((h[&#39;value&#39;] for h in headers if h[&#39;name&#39;] == &#39;Subject&#39;), &#39;No Subject&#39;)<br>            sender = next((h[&#39;value&#39;] for h in headers if h[&#39;name&#39;] == &#39;From&#39;), &#39;Unknown Sender&#39;)<br>            date = next((h[&#39;value&#39;] for h in headers if h[&#39;name&#39;] == &#39;Date&#39;), &#39;No Date&#39;)<br>            thread_id = msg.get(&#39;threadId&#39;)<br><br>            # Get message body<br>            body = extract_message_body(msg)<br><br>            # Get thread details<br>            thread_info = get_thread_details(service, thread_id)<br><br>            email_data = {<br>                &#39;message_id&#39;: message_id,<br>                &#39;thread_id&#39;: thread_id,<br>                &#39;subject&#39;: subject,<br>                &#39;sender&#39;: sender,<br>                &#39;date&#39;: date,<br>                &#39;body&#39;: body[:200] + &#39;...&#39; if len(body) &gt; 200 else body,<br>                &#39;full_body&#39;: body,<br>                &#39;thread_message_count&#39;: thread_info[&#39;message_count&#39;],<br>                &#39;thread_participants&#39;: thread_info[&#39;participants&#39;]<br>            }<br><br>            unread_emails.append(email_data)<br><br>            print(f&quot;📧 Email #{i}&quot;)<br>            print(f&quot;   📨 From: {sender}&quot;)<br>            print(f&quot;   📋 Subject: {subject}&quot;)<br>            print(f&quot;   📅 Date: {date}&quot;)<br>            print(f&quot;   🧵 Thread ID: {thread_id}&quot;)<br>            print(f&quot;   📊 Thread Messages: {thread_info[&#39;message_count&#39;]}&quot;)<br>            print(f&quot;   👥 Thread Participants: {&#39;, &#39;.join(thread_info[&#39;participants&#39;])}&quot;)<br>            print(f&quot;   📄 Preview: {body[:150]}{&#39;...&#39; if len(body) &gt; 150 else &#39;&#39;}&quot;)<br>            print(&quot;-&quot; * 60)<br><br>        return unread_emails<br><br>    except Exception as e:<br>        print(f&quot;❌ Error checking emails: {e}&quot;)<br>        return []<br><br>def extract_message_body(message):<br>    &quot;&quot;&quot;Extract text body from Gmail message&quot;&quot;&quot;<br>    body = &quot;&quot;<br><br>    def extract_text_from_part(part):<br>        if part.get(&#39;mimeType&#39;) == &#39;text/plain&#39;:<br>            data = part.get(&#39;body&#39;, {}).get(&#39;data&#39;)<br>            if data:<br>                return base64.urlsafe_b64decode(data).decode(&#39;utf-8&#39;)<br>        elif part.get(&#39;mimeType&#39;) == &#39;text/html&#39;:<br>            data = part.get(&#39;body&#39;, {}).get(&#39;data&#39;)<br>            if data:<br>                html_content = base64.urlsafe_b64decode(data).decode(&#39;utf-8&#39;)<br>                # Simple HTML to text conversion (remove tags)<br>                return html.unescape(html_content)<br>        return &quot;&quot;<br><br>    payload = message.get(&#39;payload&#39;, {})<br><br>    # Single part message<br>    if payload.get(&#39;body&#39;, {}).get(&#39;data&#39;):<br>        body = extract_text_from_part(payload)<br><br>    # Multi-part message<br>    elif payload.get(&#39;parts&#39;):<br>        for part in payload[&#39;parts&#39;]:<br>            if part.get(&#39;parts&#39;):  # Nested parts<br>                for nested_part in part[&#39;parts&#39;]:<br>                    text = extract_text_from_part(nested_part)<br>                    if text:<br>                        body += text + &quot;\n&quot;<br>            else:<br>                text = extract_text_from_part(part)<br>                if text:<br>                    body += text + &quot;\n&quot;<br><br>    return body.strip()<br><br>def get_thread_details(service, thread_id):<br>    &quot;&quot;&quot;Get detailed information about an email thread&quot;&quot;&quot;<br>    try:<br>        thread = service.users().threads().get(<br>            userId=&#39;me&#39;,<br>            id=thread_id<br>        ).execute()<br><br>        messages = thread.get(&#39;messages&#39;, [])<br>        participants = set()<br><br>        for msg in messages:<br>            headers = msg[&#39;payload&#39;].get(&#39;headers&#39;, [])<br>            from_header = next((h[&#39;value&#39;] for h in headers if h[&#39;name&#39;] == &#39;From&#39;), &#39;&#39;)<br>            to_header = next((h[&#39;value&#39;] for h in headers if h[&#39;name&#39;] == &#39;To&#39;), &#39;&#39;)<br><br>            # Extract email addresses<br>            if from_header:<br>                participants.add(extract_email_address(from_header))<br>            if to_header:<br>                for email in to_header.split(&#39;,&#39;):<br>                    participants.add(extract_email_address(email.strip()))<br><br>        return {<br>            &#39;message_count&#39;: len(messages),<br>            &#39;participants&#39;: list(participants)<br>        }<br><br>    except Exception as e:<br>        print(f&quot;⚠️  Error getting thread details: {e}&quot;)<br>        return {&#39;message_count&#39;: 1, &#39;participants&#39;: [&#39;Unknown&#39;]}<br><br>def extract_email_address(email_string):<br>    &quot;&quot;&quot;Extract email address from &#39;Name &lt;email@domain.com&gt;&#39; format&quot;&quot;&quot;<br>    if &#39;&lt;&#39; in email_string and &#39;&gt;&#39; in email_string:<br>        return email_string.split(&#39;&lt;&#39;)[1].split(&#39;&gt;&#39;)[0]<br>    return email_string.strip()<br><br>def mark_as_read(message_ids):<br>    &quot;&quot;&quot;Mark specific messages as read&quot;&quot;&quot;<br>    SERVICE_ACCOUNT_FILE = &#39;sales-automation-service.json&#39;<br>    SALES_EMAIL = &#39;sales@zemzen.org&#39;<br><br>    SCOPES = [<br>        &#39;https://www.googleapis.com/auth/gmail.modify&#39;<br>    ]<br><br>    try:<br>        credentials = service_account.Credentials.from_service_account_file(<br>            SERVICE_ACCOUNT_FILE, scopes=SCOPES<br>        )<br>        delegated_creds = credentials.with_subject(SALES_EMAIL)<br>        service = build(&#39;gmail&#39;, &#39;v1&#39;, credentials=delegated_creds)<br><br>        for message_id in message_ids:<br>            service.users().messages().modify(<br>                userId=&#39;me&#39;,<br>                id=message_id,<br>                body={&#39;removeLabelIds&#39;: [&#39;UNREAD&#39;]}<br>            ).execute()<br><br>        print(f&quot;✅ Marked {len(message_ids)} message(s) as read&quot;)<br><br>    except Exception as e:<br>        print(f&quot;❌ Error marking messages as read: {e}&quot;)<br><br>def get_thread_conversation(thread_id):<br>    &quot;&quot;&quot;Get full conversation history for a specific thread&quot;&quot;&quot;<br>    SERVICE_ACCOUNT_FILE = &#39;sales-automation-service.json&#39;<br>    SALES_EMAIL = &#39;sales@zemzen.org&#39;<br><br>    SCOPES = [&#39;https://www.googleapis.com/auth/gmail.readonly&#39;]<br><br>    try:<br>        credentials = service_account.Credentials.from_service_account_file(<br>            SERVICE_ACCOUNT_FILE, scopes=SCOPES<br>        )<br>        delegated_creds = credentials.with_subject(SALES_EMAIL)<br>        service = build(&#39;gmail&#39;, &#39;v1&#39;, credentials=delegated_creds)<br><br>        thread = service.users().threads().get(<br>            userId=&#39;me&#39;,<br>            id=thread_id<br>        ).execute()<br><br>        messages = thread.get(&#39;messages&#39;, [])<br>        conversation = []<br><br>        print(f&quot;🧵 Thread Conversation ({len(messages)} messages)&quot;)<br>        print(&quot;=&quot; * 60)<br><br>        for i, msg in enumerate(messages, 1):<br>            headers = msg[&#39;payload&#39;].get(&#39;headers&#39;, [])<br>            subject = next((h[&#39;value&#39;] for h in headers if h[&#39;name&#39;] == &#39;Subject&#39;), &#39;No Subject&#39;)<br>            sender = next((h[&#39;value&#39;] for h in headers if h[&#39;name&#39;] == &#39;From&#39;), &#39;Unknown&#39;)<br>            date = next((h[&#39;value&#39;] for h in headers if h[&#39;name&#39;] == &#39;Date&#39;), &#39;No Date&#39;)<br><br>            body = extract_message_body(msg)<br><br>            message_data = {<br>                &#39;sequence&#39;: i,<br>                &#39;message_id&#39;: msg[&#39;id&#39;],<br>                &#39;subject&#39;: subject,<br>                &#39;sender&#39;: sender,<br>                &#39;date&#39;: date,<br>                &#39;body&#39;: body<br>            }<br><br>            conversation.append(message_data)<br><br>            print(f&quot;📧 Message #{i}&quot;)<br>            print(f&quot;   From: {sender}&quot;)<br>            print(f&quot;   Date: {date}&quot;)<br>            print(f&quot;   Subject: {subject}&quot;)<br>            print(f&quot;   Body: {body[:200]}{&#39;...&#39; if len(body) &gt; 200 else &#39;&#39;}&quot;)<br>            print(&quot;-&quot; * 60)<br><br>        return conversation<br><br>    except Exception as e:<br>        print(f&quot;❌ Error getting thread conversation: {e}&quot;)<br>        return []<br><br># Main execution<br>if __name__ == &quot;__main__&quot;:<br>    print(&quot;🚀 Gmail Inbox Manager&quot;)<br>    print(&quot;=&quot; * 60)<br><br>    # Check unread emails<br>    unread_emails = check_unread_emails()<br><br>    if unread_emails:<br>        print(f&quot;\n📊 Summary: Found {len(unread_emails)} unread emails&quot;)<br><br>        # Example: Get full conversation for first thread<br>        if unread_emails:<br>            first_thread_id = unread_emails[0][&#39;thread_id&#39;]<br>            print(f&quot;\n🔍 Getting full conversation for thread: {first_thread_id}&quot;)<br>            get_thread_conversation(first_thread_id)Example 3: Managing the Calendar with a Service Account</pre><h4>Example 3: Managing the Calendar with a Service Account</h4><p>This script automates calendar management, such as checking availability and creating events.</p><pre>import json<br>import uuid  # Added for Google Meet request IDs<br>from datetime import datetime, timedelta<br>from google.oauth2 import service_account<br>from googleapiclient.discovery import build<br>import pytz<br><br>def check_calendar_availability():<br>    &quot;&quot;&quot;Check available dates and times for sales@zemzen.org calendar&quot;&quot;&quot;<br><br>    # Configuration<br>    SERVICE_ACCOUNT_FILE = &#39;sales-automation-service.json&#39;<br>    SALES_EMAIL = &#39;sales@zemzen.org&#39;<br><br>    SCOPES = [<br>        &#39;https://www.googleapis.com/auth/calendar&#39;,<br>        &#39;https://www.googleapis.com/auth/calendar.events&#39;,<br>        &#39;https://www.googleapis.com/auth/calendar.readonly&#39;<br>    ]<br><br>    try:<br>        print(&quot;📅 Checking calendar availability...&quot;)<br>        print(f&quot;   Account: {SALES_EMAIL}&quot;)<br>        print(&quot;=&quot; * 60)<br><br>        # Create credentials with delegation<br>        credentials = service_account.Credentials.from_service_account_file(<br>            SERVICE_ACCOUNT_FILE, scopes=SCOPES<br>        )<br>        delegated_creds = credentials.with_subject(SALES_EMAIL)<br><br>        # Create Calendar service<br>        service = build(&#39;calendar&#39;, &#39;v3&#39;, credentials=delegated_creds)<br><br>        # Get timezone<br>        calendar_info = service.calendars().get(calendarId=&#39;primary&#39;).execute()<br>        timezone = calendar_info.get(&#39;timeZone&#39;, &#39;UTC&#39;)<br>        tz = pytz.timezone(timezone)<br><br>        print(f&quot;🌍 Calendar timezone: {timezone}&quot;)<br><br>        # Check availability for next 7 days<br>        now = datetime.now(tz)<br>        week_later = now + timedelta(days=7)<br><br>        print(f&quot;📊 Checking availability from {now.date()} to {week_later.date()}&quot;)<br>        print(&quot;-&quot; * 60)<br><br>        # Get events for the next week<br>        events_result = service.events().list(<br>            calendarId=&#39;primary&#39;,<br>            timeMin=now.isoformat(),<br>            timeMax=week_later.isoformat(),<br>            singleEvents=True,<br>            orderBy=&#39;startTime&#39;<br>        ).execute()<br><br>        events = events_result.get(&#39;items&#39;, [])<br><br>        if not events:<br>            print(&quot;✅ No events found - completely available!&quot;)<br>            available_slots = generate_available_slots(now, week_later, [])<br>            return {<br>                &#39;existing_events&#39;: [],<br>                &#39;busy_slots&#39;: [],<br>                &#39;available_slots&#39;: available_slots,<br>                &#39;timezone&#39;: timezone<br>            }<br><br>        print(f&quot;📅 Found {len(events)} existing events:&quot;)<br><br>        busy_slots = []<br>        for event in events:<br>            start = event[&#39;start&#39;].get(&#39;dateTime&#39;, event[&#39;start&#39;].get(&#39;date&#39;))<br>            end = event[&#39;end&#39;].get(&#39;dateTime&#39;, event[&#39;end&#39;].get(&#39;date&#39;))<br>            summary = event.get(&#39;summary&#39;, &#39;No Title&#39;)<br><br>            # Parse datetime<br>            if &#39;T&#39; in start:  # Has time<br>                start_dt = datetime.fromisoformat(start.replace(&#39;Z&#39;, &#39;+00:00&#39;))<br>                end_dt = datetime.fromisoformat(end.replace(&#39;Z&#39;, &#39;+00:00&#39;))<br>            else:  # All-day event<br>                start_dt = datetime.strptime(start, &#39;%Y-%m-%d&#39;)<br>                end_dt = datetime.strptime(end, &#39;%Y-%m-%d&#39;)<br><br>            busy_slots.append({<br>                &#39;start&#39;: start_dt,<br>                &#39;end&#39;: end_dt,<br>                &#39;summary&#39;: summary<br>            })<br><br>            print(f&quot;   🗓️  {summary}&quot;)<br>            print(f&quot;      📅 {start_dt.strftime(&#39;%Y-%m-%d %H:%M&#39;)} - {end_dt.strftime(&#39;%Y-%m-%d %H:%M&#39;)}&quot;)<br><br>        print(&quot;\n🟢 Available time slots:&quot;)<br>        available_slots = generate_available_slots(now, week_later, busy_slots)<br><br>        return {<br>            &#39;existing_events&#39;: events,<br>            &#39;busy_slots&#39;: busy_slots,<br>            &#39;available_slots&#39;: available_slots,<br>            &#39;timezone&#39;: timezone<br>        }<br><br>    except Exception as e:<br>        print(f&quot;❌ Error checking calendar: {e}&quot;)<br>        return None<br><br>def generate_available_slots(start_date, end_date, busy_slots, slot_duration=60):<br>    &quot;&quot;&quot;Generate available time slots between busy periods&quot;&quot;&quot;<br><br>    # Business hours: 9 AM to 6 PM<br>    business_start = 9<br>    business_end = 18<br><br>    available_slots = []<br>    current_date = start_date.date()<br>    end_date_only = end_date.date()<br><br>    while current_date &lt;= end_date_only:<br>        # Skip weekends<br>        if current_date.weekday() &gt;= 5:  # Saturday = 5, Sunday = 6<br>            current_date += timedelta(days=1)<br>            continue<br><br>        # Create datetime objects for business hours<br>        day_start = datetime.combine(current_date, datetime.min.time().replace(hour=business_start))<br>        day_end = datetime.combine(current_date, datetime.min.time().replace(hour=business_end))<br><br>        # Add timezone info<br>        if hasattr(start_date, &#39;tzinfo&#39;) and start_date.tzinfo:<br>            day_start = day_start.replace(tzinfo=start_date.tzinfo)<br>            day_end = day_end.replace(tzinfo=start_date.tzinfo)<br><br>        # Find busy slots for this day<br>        day_busy_slots = []<br>        for slot in busy_slots:<br>            slot_start = slot[&#39;start&#39;]<br>            slot_end = slot[&#39;end&#39;]<br><br>            # Convert to same timezone if needed<br>            if hasattr(day_start, &#39;tzinfo&#39;) and day_start.tzinfo:<br>                if not hasattr(slot_start, &#39;tzinfo&#39;) or slot_start.tzinfo is None:<br>                    slot_start = slot_start.replace(tzinfo=day_start.tzinfo)<br>                if not hasattr(slot_end, &#39;tzinfo&#39;) or slot_end.tzinfo is None:<br>                    slot_end = slot_end.replace(tzinfo=day_start.tzinfo)<br><br>            # Check if busy slot overlaps with this day<br>            if (slot_start.date() == current_date or<br>                slot_end.date() == current_date or<br>                (slot_start.date() &lt; current_date &lt; slot_end.date())):<br><br>                # Adjust to business hours<br>                overlap_start = max(day_start, slot_start)<br>                overlap_end = min(day_end, slot_end)<br><br>                if overlap_start &lt; overlap_end:<br>                    day_busy_slots.append({<br>                        &#39;start&#39;: overlap_start,<br>                        &#39;end&#39;: overlap_end,<br>                        &#39;summary&#39;: slot[&#39;summary&#39;]<br>                    })<br><br>        # Sort busy slots by start time<br>        day_busy_slots.sort(key=lambda x: x[&#39;start&#39;])<br><br>        # Find available slots<br>        current_time = day_start<br><br>        for busy_slot in day_busy_slots:<br>            # Check if there&#39;s time before this busy slot<br>            if current_time + timedelta(minutes=slot_duration) &lt;= busy_slot[&#39;start&#39;]:<br>                slot_end = busy_slot[&#39;start&#39;]<br><br>                # Create available slots<br>                while current_time + timedelta(minutes=slot_duration) &lt;= slot_end:<br>                    available_slots.append({<br>                        &#39;start&#39;: current_time,<br>                        &#39;end&#39;: current_time + timedelta(minutes=slot_duration),<br>                        &#39;date&#39;: current_date.strftime(&#39;%Y-%m-%d&#39;),<br>                        &#39;time&#39;: current_time.strftime(&#39;%H:%M&#39;),<br>                        &#39;duration_minutes&#39;: slot_duration<br>                    })<br>                    current_time += timedelta(minutes=slot_duration)<br><br>            # Move past this busy slot<br>            current_time = max(current_time, busy_slot[&#39;end&#39;])<br><br>        # Check for available time after last busy slot<br>        while current_time + timedelta(minutes=slot_duration) &lt;= day_end:<br>            available_slots.append({<br>                &#39;start&#39;: current_time,<br>                &#39;end&#39;: current_time + timedelta(minutes=slot_duration),<br>                &#39;date&#39;: current_date.strftime(&#39;%Y-%m-%d&#39;),<br>                &#39;time&#39;: current_time.strftime(&#39;%H:%M&#39;),<br>                &#39;duration_minutes&#39;: slot_duration<br>            })<br>            current_time += timedelta(minutes=slot_duration)<br><br>        # Move to next day<br>        current_date += timedelta(days=1)<br><br>    # Display available slots<br>    if available_slots:<br>        print(&quot;=&quot; * 60)<br>        current_display_date = None<br>        for slot in available_slots[:20]:  # Show first 20 slots<br>            if slot[&#39;date&#39;] != current_display_date:<br>                current_display_date = slot[&#39;date&#39;]<br>                print(f&quot;\n📅 {current_display_date}:&quot;)<br>            print(f&quot;   ⏰ {slot[&#39;time&#39;]} - {slot[&#39;end&#39;].strftime(&#39;%H:%M&#39;)} ({slot[&#39;duration_minutes&#39;]} min)&quot;)<br><br>        if len(available_slots) &gt; 20:<br>            print(f&quot;\n... and {len(available_slots) - 20} more available slots&quot;)<br>    else:<br>        print(&quot;❌ No available slots found in the specified period&quot;)<br><br>    return available_slots<br><br>def create_calendar_event(title, description, start_datetime, end_datetime, attendees=None):<br>    &quot;&quot;&quot;Create a new calendar event with Google Meet&quot;&quot;&quot;<br><br>    SERVICE_ACCOUNT_FILE = &#39;sales-automation-service.json&#39;<br>    SALES_EMAIL = &#39;sales@zemzen.org&#39;<br><br>    SCOPES = [<br>        &#39;https://www.googleapis.com/auth/calendar&#39;,<br>        &#39;https://www.googleapis.com/auth/calendar.events&#39;<br>    ]<br><br>    try:<br>        print(&quot;📅 Creating calendar event...&quot;)<br>        print(f&quot;   Title: {title}&quot;)<br>        print(f&quot;   Start: {start_datetime}&quot;)<br>        print(f&quot;   End: {end_datetime}&quot;)<br><br>        # Create credentials with delegation<br>        credentials = service_account.Credentials.from_service_account_file(<br>            SERVICE_ACCOUNT_FILE, scopes=SCOPES<br>        )<br>        delegated_creds = credentials.with_subject(SALES_EMAIL)<br><br>        # Create Calendar service<br>        service = build(&#39;calendar&#39;, &#39;v3&#39;, credentials=delegated_creds)<br><br>        # Prepare event data<br>        event_data = {<br>            &#39;summary&#39;: title,<br>            &#39;description&#39;: description,<br>            &#39;start&#39;: {<br>                &#39;dateTime&#39;: start_datetime.isoformat(),<br>                &#39;timeZone&#39;: &#39;America/New_York&#39;,  # Adjust as needed<br>            },<br>            &#39;end&#39;: {<br>                &#39;dateTime&#39;: end_datetime.isoformat(),<br>                &#39;timeZone&#39;: &#39;America/New_York&#39;,  # Adjust as needed<br>            },<br>            &#39;conferenceData&#39;: {<br>                &#39;createRequest&#39;: {<br>                    &#39;requestId&#39;: f&quot;{uuid.uuid4().hex}&quot;,<br>                    &#39;conferenceSolutionKey&#39;: {<br>                        &#39;type&#39;: &#39;hangoutsMeet&#39;<br>                    }<br>                }<br>            },<br>            &#39;reminders&#39;: {<br>                &#39;useDefault&#39;: False,<br>                &#39;overrides&#39;: [<br>                    {&#39;method&#39;: &#39;email&#39;, &#39;minutes&#39;: 24 * 60},<br>                    {&#39;method&#39;: &#39;popup&#39;, &#39;minutes&#39;: 30},<br>                ],<br>            },<br>        }<br><br>        if attendees:<br>            event_data[&#39;attendees&#39;] = [{&#39;email&#39;: email} for email in attendees]<br>            print(f&quot;   Attendees: {&#39;, &#39;.join(attendees)}&quot;)<br><br>        # --- KEY CHANGE IS HERE ---<br>        # Add conferenceDataVersion=1 to the insert() call<br>        event = service.events().insert(<br>            calendarId=&#39;primary&#39;,<br>            body=event_data,<br>            sendUpdates=&#39;all&#39; if attendees else &#39;none&#39;,<br>            conferenceDataVersion=1  # &lt;--- THIS LINE IS REQUIRED<br>        ).execute()<br><br>        print(&quot;✅ EVENT CREATED SUCCESSFULLY!&quot;)<br>        print(f&quot;   Event ID: {event.get(&#39;id&#39;)}&quot;)<br>        print(f&quot;   Event Link: {event.get(&#39;htmlLink&#39;)}&quot;)<br><br>        # --- ADD THIS TO PRINT THE MEET LINK ---<br>        if &#39;conferenceData&#39; in event:<br>            meet_link = event[&#39;conferenceData&#39;][&#39;entryPoints&#39;][0][&#39;uri&#39;]<br>            print(f&quot;   🎥 Meet Link: {meet_link}&quot;)<br>        # ------------------------------------<br><br>        print(f&quot;   📧 {&#39;Invitations sent to attendees&#39; if attendees else &#39;No invitations sent&#39;}&quot;)<br><br>        return event<br><br>    except Exception as e:<br>        print(f&quot;❌ Error creating event: {e}&quot;)<br>        return None<br><br><br>def create_meeting_from_available_slot(slot_index, title, description, attendees=None):<br>    &quot;&quot;&quot;Create a meeting using an available slot with Google Meet&quot;&quot;&quot;<br><br>    # First check availability<br>    availability = check_calendar_availability()<br>    if not availability or not availability[&#39;available_slots&#39;]:<br>        print(&quot;❌ No available slots found&quot;)<br>        return None<br><br>    available_slots = availability[&#39;available_slots&#39;]<br><br>    if slot_index &gt;= len(available_slots):<br>        print(f&quot;❌ Invalid slot index. Available slots: 0-{len(available_slots)-1}&quot;)<br>        return None<br><br>    slot = available_slots[slot_index]<br><br>    print(f&quot;\n🎯 Creating meeting in slot #{slot_index}&quot;)<br>    print(f&quot;   📅 {slot[&#39;date&#39;]} at {slot[&#39;time&#39;]}&quot;)<br><br>    return create_calendar_event(<br>        title=title,<br>        description=description,<br>        start_datetime=slot[&#39;start&#39;],<br>        end_datetime=slot[&#39;end&#39;],<br>        attendees=attendees<br>    )<br><br>def get_upcoming_events(days_ahead=7):<br>    &quot;&quot;&quot;Get upcoming events for the next N days&quot;&quot;&quot;<br><br>    SERVICE_ACCOUNT_FILE = &#39;sales-automation-service.json&#39;<br>    SALES_EMAIL = &#39;sales@zemzen.org&#39;<br><br>    SCOPES = [&#39;https://www.googleapis.com/auth/calendar.readonly&#39;]<br><br>    try:<br>        print(f&quot;📅 Getting upcoming events (next {days_ahead} days)...&quot;)<br><br>        credentials = service_account.Credentials.from_service_account_file(<br>            SERVICE_ACCOUNT_FILE, scopes=SCOPES<br>        )<br>        delegated_creds = credentials.with_subject(SALES_EMAIL)<br>        service = build(&#39;calendar&#39;, &#39;v3&#39;, credentials=delegated_creds)<br><br>        # Time range<br>        now = datetime.utcnow()<br>        future = now + timedelta(days=days_ahead)<br><br>        events_result = service.events().list(<br>            calendarId=&#39;primary&#39;,<br>            timeMin=now.isoformat() + &#39;Z&#39;,<br>            timeMax=future.isoformat() + &#39;Z&#39;,<br>            singleEvents=True,<br>            orderBy=&#39;startTime&#39;<br>        ).execute()<br><br>        events = events_result.get(&#39;items&#39;, [])<br><br>        if not events:<br>            print(&quot;✅ No upcoming events found&quot;)<br>            return []<br><br>        print(f&quot;📊 Found {len(events)} upcoming events:&quot;)<br>        print(&quot;=&quot; * 60)<br><br>        for i, event in enumerate(events, 1):<br>            start = event[&#39;start&#39;].get(&#39;dateTime&#39;, event[&#39;start&#39;].get(&#39;date&#39;))<br>            summary = event.get(&#39;summary&#39;, &#39;No Title&#39;)<br><br>            if &#39;T&#39; in start:<br>                start_dt = datetime.fromisoformat(start.replace(&#39;Z&#39;, &#39;+00:00&#39;))<br>                print(f&quot;📅 {i}. {summary}&quot;)<br>                print(f&quot;    📅 {start_dt.strftime(&#39;%Y-%m-%d %H:%M&#39;)}&quot;)<br>            else:<br>                print(f&quot;📅 {i}. {summary} (All Day)&quot;)<br>                print(f&quot;    📅 {start}&quot;)<br><br>            if event.get(&#39;description&#39;):<br>                desc = event[&#39;description&#39;][:100] + &#39;...&#39; if len(event[&#39;description&#39;]) &gt; 100 else event[&#39;description&#39;]<br>                print(f&quot;    📝 {desc}&quot;)<br><br>            print(&quot;-&quot; * 40)<br><br>        return events<br><br>    except Exception as e:<br>        print(f&quot;❌ Error getting upcoming events: {e}&quot;)<br>        return []<br><br>def create_quick_meeting(title, date_str, time_str, duration_minutes=60, attendees=None):<br>    &quot;&quot;&quot;Create a meeting for a specific date and time with Google Meet (easier to use)&quot;&quot;&quot;<br><br>    try:<br>        from datetime import datetime<br>        import pytz<br><br>        # Parse the date and time<br>        meeting_datetime = datetime.strptime(f&quot;{date_str} {time_str}&quot;, &quot;%Y-%m-%d %H:%M&quot;)<br><br>        # Add timezone (match your calendar timezone)<br>        tz = pytz.timezone(&#39;America/Denver&#39;)  # Match your calendar timezone<br>        meeting_start = tz.localize(meeting_datetime)<br>        meeting_end = meeting_start + timedelta(minutes=duration_minutes)<br><br>        print(f&quot;🎯 Creating quick meeting:&quot;)<br>        print(f&quot;   📅 {date_str} at {time_str}&quot;)<br>        print(f&quot;   ⏱️  Duration: {duration_minutes} minutes&quot;)<br>        print(f&quot;   🎥 Google Meet: {&#39;Included&#39;}&quot;)<br><br>        # Enhanced description for sales meetings<br>        description = f&quot;&quot;&quot;Meeting scheduled for {duration_minutes} minutes.<br><br>📋 Agenda:<br>• Introduction and overview<br>• Product demonstration<br>• Q&amp;A session<br>• Next steps discussion<br><br>🏢 Organized by: Zemzen Sales Team<br>📧 Contact: sales@zemzen.org<br><br>We look forward to speaking with you!&quot;&quot;&quot;<br><br>        return create_calendar_event(<br>            title=title,<br>            description=description,<br>            start_datetime=meeting_start,<br>            end_datetime=meeting_end,<br>            attendees=attendees,<br>        )<br><br>    except ValueError as e:<br>        print(f&quot;❌ Invalid date/time format. Use YYYY-MM-DD for date and HH:MM for time&quot;)<br>        print(f&quot;   Example: create_quick_meeting(&#39;Demo Call&#39;, &#39;2025-06-20&#39;, &#39;14:00&#39;)&quot;)<br>        return None<br>    except Exception as e:<br>        print(f&quot;❌ Error creating quick meeting: {e}&quot;)<br>        return None<br>if __name__ == &quot;__main__&quot;:<br>    print(&quot;🚀 Google Calendar Manager&quot;)<br>    print(&quot;=&quot; * 60)<br><br>    # Check availability<br>    availability = check_calendar_availability()<br><br>    if availability and availability[&#39;available_slots&#39;]:<br>        print(f&quot;\n📊 Found {len(availability[&#39;available_slots&#39;])} available slots&quot;)<br><br>        # Test Google Meet functionality with a simple event<br>        print(&quot;\n🧪 Testing Google Meet Integration:&quot;)<br>        print(&quot;-&quot; * 40)<br><br>        from datetime import datetime, timedelta<br>        import pytz<br><br>        # Create a test meeting for 1 hour from now<br>        tz = pytz.timezone(&#39;America/Denver&#39;)  # Match your calendar timezone<br>        now = datetime.now(tz)<br>        start_time = now + timedelta(minutes=5)<br>        end_time = start_time + timedelta(minutes=35)<br><br>        print(f&quot;🕐 Scheduling test meeting for: {start_time.strftime(&#39;%Y-%m-%d %H:%M %Z&#39;)}&quot;)<br><br>        # Create a simple test event<br>        result = create_calendar_event(<br>            title=&quot;🧪 Test Google Meet Call&quot;,<br>            description=&quot;This is a test meeting to verify Google Meet integration works correctly.\n\n✅ Testing automated calendar and video call creation.&quot;,<br>            start_datetime=start_time,<br>            end_datetime=end_time,<br>            attendees=[&quot;meinnps@gmail.com&quot;]<br>        )<br><br>        if result:<br>            print(&quot;\n✅ Test completed successfully!&quot;)<br>            print(&quot;   Check your calendar for the test meeting with Google Meet link&quot;)<br>        else:<br>            print(&quot;\n❌ Test failed - please check the error messages above&quot;)<br><br>    # Get upcoming events<br>    print(&quot;\n&quot; + &quot;=&quot; * 60)<br>    get_upcoming_events()</pre><h4>Links for the project and the original Hackathon submission</h4><ul><li><a href="https://colab.research.google.com/drive/1WtxAu-tZM13ay0P6kqbesMP8ViNECUu0?usp=sharing">Colab notebook</a></li><li><a href="https://www.youtube.com/watch?v=UxP3iDqRKZ0">Video demo</a> of our project</li><li><a href="https://github.com/merdandt/SalesShortcut">GitHub repo </a>of our project</li><li><a href="https://github.com/merdandt/SalesShortcut">Submission</a> on Devpost</li></ul><p>#<em>adkhackathon, #GoogleADK, #A2A, #CloudRun</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fee1b1cb05f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning NLLB-200 with LoRA on a 650-Sentence Turkmen–English Corpus]]></title>
            <link>https://medium.com/@meinnps/fine-tuning-nllb-200-with-lora-on-a-650-sentence-turkmen-english-corpus-082f68bdec71?source=rss-c93de175ef16------2</link>
            <guid isPermaLink="false">https://medium.com/p/082f68bdec71</guid>
            <category><![CDATA[fine-tuning-llm]]></category>
            <category><![CDATA[turkmen-translation]]></category>
            <category><![CDATA[lora]]></category>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[turkmen-ai]]></category>
            <dc:creator><![CDATA[Merdan Durdyyev]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 14:47:55 GMT</pubDate>
            <atom:updated>2025-04-29T20:12:41.027Z</atom:updated>
            <content:encoded><![CDATA[<h4>Machine translation model for the Turkmen language</h4><p><em>This article is not about teaching but sharing my path and maybe learning from you. And this is not the final model — it is just a beginning.</em></p><blockquote><em>I embed some Turkmen words in this article, so if you want to see the full meaning, try this model 😉</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ziK9hyo4Vp6sncNsMQqwFw.png" /><figcaption>Image created with ChatGPT</figcaption></figure><h3>Motivation and intent</h3><h4>Why?</h4><p>The work is a final project for my <a href="https://www.coursicle.com/usu/courses/DATA/5610/">DATA 5610 — Advanced Machine Learning for Analytics</a> by <a href="https://www.coursicle.com/usu/professors/Sharad+Jones/">Sharad Jones</a>. Usually, this final project aims to solve business and analytical problems, but I convinced my professor to choose this project because I want to contribute to the Turkmen AI community as well.</p><h4>Problem?</h4><p>We have close to zero AI production in our community, and because of data scarcity and less interest, there is little development regarding the Turkmen language from big LLM providers. Although SOTA models can do a better-than-ok job, any open-source translation or LLMs lag behind good translation and communication. So why not try to do something?</p><blockquote><em>Çözeliň bu meseläni.</em></blockquote><h3>What will you find in this article?</h3><p>This article might be interesting to any Turkmen AI enthusiast and Machine Learning practitioner. I will walk you through the path I took to prepare and create the unique dataset, upload it to Hugging Face, and tune the NLLB-200 model on a small dataset using <a href="https://github.com/microsoft/lora">LoRA</a>. You will be provided links to the:</p><ul><li>GitHub repository with all the materials and code.</li><li>Links to the Hugging Face Demo Space, where you can try the model.</li><li>Link to the unique (but small) dataset of Turkmen-English sentences.</li><li>Links to the final (merged) model and its adapters.</li></ul><h3>Data is everything</h3><p>I believe that nowadays a usual LLM experiment consists of three components (Data — 75 %, Computation resources — 20 %, and Codebase — 5 %). Why is the codebase so small? Most of the code you are going to write is already written, and you can vibe-code small tuning code or repeat the code from open-source papers with the help of generative LLMs, as long as you have good, clean data and powerful computational power.</p><blockquote><em>Puluň bolsa olaryň hemmesi çözüler agam.</em></blockquote><p>Computation is more or less affordable with <a href="https://colab.research.google.com/">Google Colab</a>, and I think it would be enough for my experiment. What about the data? I searched the whole internet and found some resources for <a href="https://www.ilc.cnr.it/EAGLES96/corpustyp/node20.html#:~:text=A%20parallel%20corpus%20is%20a,however%2C%20exist%20in%20several%20languages.">parallel corpora</a> in Turkmen. The most common repository is <a href="https://opus.nlpl.eu/">OPUS</a>. Additionally, more data and neat validation/test datasets can be found on the WMT competitions website (like <a href="https://www.statmt.org/wmt22/translation-task.html">WMT21</a>, <a href="https://www.statmt.org/wmt21/translation-task.html">WMT22</a>, <a href="https://machinetranslate.org/wmt23">WMT23</a>, and <a href="https://machinetranslate.org/wmt24">WMT24</a>).</p><p>But I thought if I could easily find them, they would already be hidden inside the weights of any model. And if you take a <a href="https://opus.nlpl.eu/results/en&amp;tk/corpus-result-table">closer look</a> at that Turkmen translation, it is not good. So I bravely decided to create my own.</p><blockquote><em>Tas puşman etdirdi.</em></blockquote><h3>Creating a dataset</h3><p>This started as fun but turned out to be an annoying process. Because I wanted to have <strong><em>real</em></strong> Turkmen translations done by humans, I had no choice other than manually collecting from publicly available sources:</p><ol><li>Translated books authored by Gurbanguly Berdimuhamedov, obtained from the official Turkmenistan government portal &lt;https://maslahat.gov.tm/books&gt;.</li><li>Supplementary translated materials sourced from various public journals at &lt;https://metbugat.gov.tm&gt;.</li></ol><blockquote>Full information about this dataset can be read in the <strong>turkmen_english_s500</strong> <a href="https://huggingface.co/datasets/XSkills/turkmen_english_s500/edit/main/README.md">dataset card</a>.</blockquote><p>Long story short, for the journals, I asked my friend, and for the books, I tried to build automation scripting myself for the PDF part <em>(you can find the cleaning notebook in the repo)</em>.</p><blockquote><em>I spent two days automating a two-day task 🤦‍♂️.</em></blockquote><p>At the end of the day, we came up with this:</p><pre>DatasetDict({<br>    train: Dataset({<br>        features: [&#39;translation&#39;],<br>        num_rows: 495<br>    }),<br>    validation: Dataset({<br>        features: [&#39;translation&#39;],<br>        num_rows: 62<br>    }),<br>    test: Dataset({<br>        features: [&#39;translation&#39;],<br>        num_rows: 62<br>    })<br>})</pre><p>Which is small, but hopefully correct and precise.</p><blockquote><em>See the dataset README for details.</em></blockquote><h3>Base model selection</h3><p>After searching through HuggingFace, I came up with two options, which I tested myself:</p><ul><li><a href="https://huggingface.co/facebook/nllb-200-distilled-600M">NLLB-200</a> from Facebook.</li><li><a href="https://huggingface.co/google/madlad400-10b-mt">madlad400–10b-mt</a> from Google.</li></ul><p>Both are good in translation and capturing the Turkmen intonation; <strong>madlad400-10b–mt</strong> felt slightly better for me, but after comparing the performance and parameters <em>(10 B &gt; 600 M)</em> and considering my microscopic dataset, I decided to proceed with the <strong><em>NLLB-200</em></strong>.</p><blockquote><em>Ýatyryp aýlaýyn diýdim.</em></blockquote><h3>Selecting the tuning method</h3><p>Knowing my tiny dataset and empty pocket, I knew that I should look at <a href="https://www.ibm.com/think/topics/parameter-efficient-fine-tuning">parameter-efficient fine-tuning</a> techniques. I ended up choosing <strong><em>LoRA</em></strong>. Why? My idea is to preserve multilingual knowledge by keeping original weights intact while adding small, targeted updates and the ability to control which attention modules to tune. On top of that, we can create no inference latency as updates can be merged with the original weights after training.</p><blockquote><em>Garyp oglanlar AI bilen meşgullamaýar.</em></blockquote><h3>Let’s start tuning blindly</h3><p><em>I want to show you two parts of the tuning — “bad” and “good” hyperparameters, and the contradiction with the metrics. So when I refer to Bad, it means the first training, and Good means the last (but not least)</em></p><blockquote>It’s not really about good and bad, but about randomness and consciousness.</blockquote><h4>Put the defaults and give it a shot</h4><p>I think that the main components of my fine-tuning journey are around these three parts: <strong>LoRA config</strong>, <strong>Training arguments</strong>, and <strong>Evaluation</strong>.</p><p>For evaluation, I decided to pick the standard for translation: <a href="https://www.youtube.com/watch?v=M05L1DhFqcw">BLEU</a>, <a href="https://machinetranslate.org/chrF">chrF</a>, and <a href="https://machinetranslate.org/ter">TER</a>. There is nothing to talk about the metrics since you define them and write code — they do not change over time or with your hyperparameter changes. But what we can play with are our <a href="https://www.ibm.com/think/topics/hyperparameter-tuning">hyperparameters</a> of LoRA config and Training arguments. It is all about trying and testing, so the first couple of iterations of default configurations gave me what I later understood was a bad model with good metrics.</p><blockquote><em>Ýatyp galanyňdan atyp gal.</em></blockquote><p>I just applied these:</p><p><strong><em>LoRA Config</em>:</strong></p><pre>lora_config = LoraConfig(<br>    r=16,                           <br>    lora_alpha=32,                 <br>    target_modules=[&quot;q_proj&quot;, &quot;v_proj&quot;, &quot;k_proj&quot;, &quot;o_proj&quot;],<br>    lora_dropout=0.05,<br>    bias=&quot;none&quot;,<br>    task_type=TaskType.SEQ_2_SEQ_LM,<br>)</pre><p>and <strong><em>Training arguments</em></strong>:</p><pre>training_args = Seq2SeqTrainingArguments(<br>    output_dir=TUNNED_MODEL_DIR,<br>    per_device_train_batch_size=8,<br>    per_device_eval_batch_size=8,<br>    weight_decay=0.01,<br>    save_total_limit=3,<br>    learning_rate=5e-4,<br>    num_train_epochs=15,<br>    lr_scheduler_type=&quot;linear&quot;,<br>    predict_with_generate=True,<br>    fp16=True if torch.cuda.is_available() else False,<br>    logging_dir=&quot;./logs&quot;,<br>    logging_steps=50,<br>    eval_steps=100,               <br>    save_steps=100,               <br>    eval_accumulation_steps=2, <br>    report_to=&quot;tensorboard&quot;,<br>    warmup_ratio=0.1<br>)</pre><h4>Writing code for LoRA</h4><p>And remember I said about <em>(5 % for code)</em>? Thanks to AI influencers and hype, all those machine-learning and AI codes are more or less accessible. You can see how different LLM providers suggested code with an identical prompt and use it:</p><ul><li><a href="https://claude.ai/share/902510fe-9e89-47b0-b7db-0c42881d91dc">Anthropic Claude 3.7 Sonnet</a></li><li><a href="https://chatgpt.com/share/67f3ef9a-de4c-8004-900e-ed178905c640">ChatGPT 4.5</a></li><li><a href="https://gist.github.com/merdandt/35bf0217f3b62d770da692125aadbb66">DeepSeek R1</a></li><li><a href="https://gemini.google.com/share/bfd75a1ec37c">Gemini 2.5 Pro (experimental)</a></li><li><a href="https://docs.google.com/document/d/12sw-kxcQq6Af_yjJKaKFWRjebqtBurbkF4AkU5V46_s/edit?usp=sharing">Grok 3</a></li></ul><p>So did I. I took good ideas from each of them and ended up with my Google Colab notebook. Nothing fancy, right? I got the A100 GPU from Colab and wrote code that works (<em>see all the code in the GitHub repository</em>). But what this code does we will explore below.</p><blockquote><em>The number of trainable params in this set: </em><strong><em>3,538,944 || all params: 618,612,736 || trainable%: 0.5721.</em></strong><em>)</em></blockquote><h4>Result of the “Bad”- good metrics</h4><p>After <strong>~3 minutes</strong> of training and <strong>~7 minutes</strong> of evaluating, I got my initial model evaluation results. As you can see in the image below, the numbers look great. Better than the original.</p><p>English to Turkmen translation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*fs8TSVGFv12DkkPRcqXcDA.png" /></figure><pre>| Metric                    | Fine-tuned | Original | Difference |<br>|---------------------------|-----------:|---------:|-----------:|<br>| **BLEU**                  |       7.38 |     8.12 |      -0.74 |<br>| **chrF**                  |      40.49 |    39.46 |      +1.03 |<br>| **TER (lower is better)** |      88.45 |    87.30 |      +1.15 |</pre><p>Turkmen to English translation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*jidopTHO_CJ2ychRiokpmA.png" /></figure><pre>| Metric                    | Fine-tuned | Original | Difference  |<br>|---------------------------|-----------:|---------:|------------:|<br>| **BLEU**                  |      39.25 |    26.48 |      +12.77 |<br>| **chrF**                  |      61.72 |    52.91 |      +8.81  |<br>| **TER (lower is better)** |      51.31 |    69.70 |      -18.39 |</pre><p>As you can see, the numbers are not bad at all. One might say perfect. But if you ever took a statistics class, you know that perfect model metrics are a mirage. So I decided to check the human-evaluation table.</p><h4>Human evaluation of the “<em>Bad”</em>-good metrics</h4><p>I uploaded the test examples to Google Sheets so you can also see and apply conditional formatting to see the differences (<em>if the fine-tuned cell is green, it is different from the original</em>) between the translations. Since I know the Turkmen language, I was able to evaluate the translation.</p><p>English to Turkmen translation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Gl9nhmTvddaKtSgA4i1MA.png" /><figcaption>See it yourself <a href="https://docs.google.com/spreadsheets/d/1LI1ipu4rPjG-NKuXAaHz5wmUzIRgsaixpBIE-7Kb0Hk/edit?usp=sharing">here</a></figcaption></figure><p>Turkmen to English translation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XFj_rk9Z5JzPDKlNzugIzQ.png" /><figcaption>See it yourself <a href="https://docs.google.com/spreadsheets/d/1TaHgaWZHtCuS97wipRkx_21IK8qIVg1SOivIJdzfBks/edit?usp=sharing">here</a></figcaption></figure><p>As you can see, all the fine-tuned translations are different from the original. OK, but they are not good. Even worse, the original translations are now more accurate. Sometimes it feels like my model pulls Turkish or another language. This is when I realized that I overfitted on a small dataset and faced <a href="https://en.wikipedia.org/wiki/Catastrophic_forgetting">catastrophic forgetting</a>. I decided to stop here and try to find a better solution.</p><h3>Let’s start tuning wisely</h3><blockquote><em>Ýedi ölçäp bir train et.</em></blockquote><h4>Put some thought and give it a shot</h4><p>After some thinking and research, I decided to change the <em>LoRA config</em> and <em>Training arguments</em> a bit.</p><blockquote><em>I am not going to teach you what all those parameters mean; you can read about them in the </em><a href="https://arxiv.org/abs/2106.09685"><em>LoRA paper</em></a><em> or </em><a href="https://huggingface.co/docs/peft/index"><em>HuggingFace</em></a><em> documentation. I will just show you what I changed and why.</em></blockquote><h4>Jumping ahead to the “<em>Good”</em>-bad results</h4><p>Although I did not achieve as <strong><em>good</em></strong> metrics as in the <strong><em>bad</em></strong> training, I saw a difference in the human-evaluation test samples.</p><p><strong><em>Metrics comparison</em>:</strong></p><p>English to Turkmen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*5Zs2p9VSyR_rRyuVgqccow.png" /></figure><pre>| Metric                    | Fine-tuned | Original | Difference |<br>|---------------------------|-----------:|---------:|-----------:|<br>| **BLEU**                  |       8.24 |     8.12 |      +0.12 |<br>| **chrF**                  |      39.55 |    39.46 |      +0.09 |<br>| **TER (lower is better)** |      87.20 |    87.30 |      -0.10 |</pre><p>Turkmen to English.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*YZSDhzcHL2cmmfYV89IGWQ.png" /></figure><pre>| Metric                    | Fine-tuned | Original | Difference |<br>|---------------------------|-----------:|---------:|-----------:|<br>| **BLEU**                  |      25.88 |    26.48 |      -0.60 |<br>| **chrF**                  |      52.71 |    52.91 |      -0.20 |<br>| **TER (lower is better)** |      67.70 |    69.70 |      -2.00 |</pre><p><strong><em>Google Sheets:</em></strong></p><p>English to Turkmen translation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WDyczAKMvK9-EMACdpy9Ug.png" /><figcaption>See it yourself <a href="https://docs.google.com/spreadsheets/d/1qKgyr0S02fyRgCxUzDpmmnPtiw8VLjPPFfsZtlN1IsI/edit?gid=2014241094#gid=2014241094">here</a></figcaption></figure><p>Turkmen to English translation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_zh8XrwqIkhDy9ytTQfoBA.png" /><figcaption>See it yourself <a href="https://docs.google.com/spreadsheets/d/1CydK-dDm_EeMMD-iYHOdet3LqIRJzuco9SmqhJNN5jo/edit?usp=sharing">here</a></figcaption></figure><p>Again, pay attention to the translation rows that are different from the original model <em>(filled in green)</em>. First of all, not all the translations are different (<em>most of them are similar)</em>, which is a good sign that our model did not forget its original translation ability. Second, the translations are not perfect, but they are not bad either. I would say they are a little more accurate than the original ones. Yes, we did it! I saw a slight improvement in quality by tuning the custom dataset with no overfitting and catastrophic forgetting. And let’s see what I did to achieve this.</p><blockquote><em>Meseläň mesele dälä.</em></blockquote><h4>LoRA Config</h4><p><strong>r:</strong></p><p>My choice of <strong>r=16</strong> is reasonable (but could be smaller). And with <strong>lora_alpha=32</strong> it gives the scaling factor of <strong>2.0,</strong> which is recommended in the paper.</p><p><strong>Target Modules</strong> (Most critical):</p><ul><li>Bad: <strong>[“q_proj”, “v_proj”, “k_proj”, “o_proj”]</strong> (All attention modules)</li><li>Good: <strong>[“q_proj”, “v_proj”]</strong> (Only query and value projections)</li></ul><p>Impact: This is the most significant difference, where training all attention modules (q, k, v, o) with LoRA can be too aggressive for fine-tuning. Fewer target modules = fewer trainable parameters = less risk of overfitting, and as a result, we get fewer trainable parameters: <strong>2359296 | All params: 617433088 | Trainable%: 0.38%</strong></p><h4>Training arguments</h4><p><strong>Learning rate </strong>(Most critical):</p><ul><li>Bad: 5e-4 (0.0005)</li><li>Good: 1e-5 (0.00001)</li></ul><p>Impact: My initial learning rate was 50 times higher! This is the primary cause of my problems: Too high LR causes the model to take huge steps, destroying the pretrained knowledge. Leads to catastrophic forgetting as the model “unlearns” its multilingual capabilities. Causes overfitting by aggressively fitting to your specific dataset</p><p><strong>Batch size:</strong></p><ul><li>Bad: <strong>per_device_train_batch_size=8</strong></li><li>Good: <strong>per_device_train_batch_size=4</strong></li></ul><p>Impact: A Larger batch size with a high learning rate amplifies the problems: Larger batches mean more stable gradients, which, with high LR, leads to more dramatic parameter updates. Smaller batches in the good config create noisier gradients, which act as regularization</p><p><strong>Epochs:</strong></p><ul><li>Bad: <strong>num_train_epochs=15</strong></li><li>Good: <strong>num_train_epochs=5</strong></li></ul><p>Impact: Training for <strong>3x</strong> longer with a high learning rate: Gives more opportunity for overfitting. Allows more time for catastrophic forgetting. Pretrained models typically need fewer epochs for fine-tuning (especially with small datasets)</p><p><strong>Weight decay:</strong></p><ul><li>Bad: <strong>weight_decay=0.01</strong></li><li>Good: <strong>weight_decay=0.005</strong></li></ul><p>Impact: Higher weight decay wasn’t enough to counter the high learning rate: While 0.01 is stronger regularization, it couldn’t compensate for the aggressive learning rate. The lower weight decay in the good config is sufficient with the conservative learning rate.</p><p><strong>Learning rate scheduler:</strong></p><ul><li>Bad: <strong>lr_scheduler_type=”linear”</strong></li><li>Good: <strong>lr_scheduler_type=”cosine”</strong></li></ul><p>Impact: Linear decay with high initial LR: Linear decay maintains a relatively high learning rate for longer. Cosine provides a more gradual, smooth decay that’s better for fine-tuning. This helps in achieving better convergence and prevents overshooting during training.</p><h3>Conclusion</h3><p>This is not the final model. I just stopped at the beginning to share this with you and wrap it up to the HuggingFace models, dataset, and demo space. And of course, these parameters are not ideal, and I want to learn from your comments what I missed and what I can improve. I am just happy enough to see that the Turkmen language can be tuned if we have more data and computation.</p><blockquote><em>Çözdümi?</em></blockquote><h3>Future work</h3><ul><li>I need to collect more more more clean data.</li><li>I want to try the <strong>madlad400–10b–mt</strong> model and see if it can outperform the NLLB-200.</li><li>I want to try the <strong>LoRA</strong> with <strong>QLoRA</strong> and see if it can outperform the NLLB-200.</li><li>I want to use the <a href="https://github.com/mjpost/sacrebleu">sacreBLEU</a> metric instead.</li><li>I want to explore the impact of different learning rates and other hyperparameters on model performance.</li></ul><blockquote><em>Ýagty gelejege tarap…</em></blockquote><h3>Links</h3><ul><li><a href="https://github.com/merdandt/nllb-tk-en-lora">GitHub repository</a></li><li><a href="https://huggingface.co/spaces/XSkills/nllb-turkmen-english">Space demo</a></li><li>Merged model for inference <a href="https://huggingface.co/XSkills/nllb-200-turkmen-english-lora">nllb-200-turkmen-english-lora</a></li><li>Model adapters <a href="https://huggingface.co/XSkills/nllb-200-turkmen-english-lora-adapter/tree/main">nllb-200-turkmen-english-lora-adapter</a></li><li>Dataset <a href="https://huggingface.co/datasets/XSkills/turkmen_english_s500">turkmen_english_s500</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=082f68bdec71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart dilinde concurrency we isolates düşünjeler]]></title>
            <link>https://medium.com/@meinnps/dart-dilinde-concurrency-we-isolates-d%C3%BC%C5%9F%C3%BCnjeler-b45382bfb8d4?source=rss-c93de175ef16------2</link>
            <guid isPermaLink="false">https://medium.com/p/b45382bfb8d4</guid>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[türkmençe]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[türkmenistan]]></category>
            <dc:creator><![CDATA[Merdan Durdyyev]]></dc:creator>
            <pubDate>Sat, 18 May 2024 05:14:51 GMT</pubDate>
            <atom:updated>2024-05-18T05:14:51.153Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bölüm #6</h4><p>Bu makalada, Dart dilinde <a href="https://en.wikipedia.org/wiki/Asynchrony_(computer_programming)">asinhron</a> programmirlemäniň esaslaryny we onuň üç esasy guraly: Isolates, Future, we Stream barada gürrüň açarys. Bu gurallar, Dart programmalaryň reaktiw we ygtybarly bolmagyny üpjün edýär.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qKQp_z05iVqX8233xmGOuA.jpeg" /></figure><blockquote>Ähli bölümleri görmek üçin <a href="https://medium.com/@meinnps/flutter-a-giri%C5%9F-kursy-3d4b28de3f32">şu ýere </a>salgylanyp bilersiňiz.</blockquote><p>Programma üpjünçiligini işläp taýýarlamak üçin aşakdaky wezipeleri ýerine ýetirmeli bolarsyňyz:</p><ul><li>Maglumat bazasy bilen işlemek</li><li>Serwer bilen habarlaşmak</li><li>Maglumatlary fonda (arkada) ýüklemek</li><li>Faýl ulgamyny dolandyrmak</li><li>Enjamyň fiziki serişdeleri (meselem, batareýa, GPS) bilen işlemek</li><li>Ekranlaryň we programmalaryň ýagdaýyny (state) dolandyrmak</li></ul><p>Ýokardaky ähli wezipeler, imperative <a href="https://en.wikipedia.org/wiki/Synchronous_programming_language">sinhron</a> kod ýazylmagy bilen netijeli çözülip bilinmez. Mysal üçin, uly möçberli JSON parse etmek ýaly agyr operasiýa programmaňyzy doňmaga getirer.</p><p>Bu bölümde, Dart-da şeýle wezipeleri netijeli çözmäge kömek edýän gurallary ara alyp maslahatlaşarys.</p><p>Emma ilki bilen esasy tezisler (adalgalar) bilen tanyş bolaly:</p><ul><li>Dart-da Isolates (izolýatorlar) bar, olar Threads (iş potok, akym) bilen deňeşdirilýär emma olardan tapawutly.</li><li>Dart-da ähli kod adatça bir izolýatda ýerine ýetirilýär.</li><li>Dart-da giňden kabul edilen manyda <a href="https://en.wikipedia.org/wiki/Parallel_computing">parallellik</a> ýok.</li><li>Her bir izolýatda koduň bloklanmazdan ýerine ýetirilmegini üpjün edýän <a href="https://dart.dev/language/concurrency">Event Loop</a> (Waka/event Dolanyşygy) bar.</li><li>Dart-da hakyky asinhronlyk bardyr.</li><li>Dart-da reaktiw kod ýazmagyň usuly bolan <a href="https://api.dart.dev/stable/3.3.4/dart-async/Stream-class.html">Stream API</a> bar.</li></ul><p>Siz eýýäm asinhronlyk, parallellik we bäsdeşlik (<a href="https://en.wikipedia.org/wiki/Concurrency_(computer_science)">concurrency</a>) ýaly düşünjeler bilen tanyş diýip çaklaýarys. Şol sebäpli bu düşünjeleri düşündirmekde durup geçmeris, emma olaryň Dart-da nädip amala aşyrylýandygyny jikme-jik ara alyp maslahatlaşarys.</p><h3>Event Loop</h3><p>Bu wakalary (Event-lary, sobytiýalary) dolandyryş mehanizmi bolup, bloklanmaýan (doňmaýan) kod ýazmaga mümkinçilik berýär. Bu bölümde köp teoriýa bar, ýöne ony düşünmek möhüm, çünki makalada ara alnyp maslahatlaşylýan ähli gurallar Event Loop-yň işleýiş ýörelgelerine esaslanýar.</p><p>Onuň işleýiş düzgünini aşakdaky shemada düşündirip bolar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stUYwAnUVXBYmEl8CguNIA.jpeg" /></figure><p>Dart-da microtask bu event loop-yň edil şu wagtdaky iterasiýasyndan soň, emma indiki event loop-yň iterasiýasyndan öň, dessine işläp çykmak üçin nobata goýulan kiçiräk iş bölegi.</p><p>Geliň bu shemany kod görnüşinde göz öňümize getireliň.</p><pre>import &#39;dart:collection&#39;;<br><br>bool programRuns = true;<br>Queue&lt;String&gt; microtaskQueue = Queue();<br>Queue&lt;String&gt; eventQueue = Queue();<br><br>void main() {<br>  // Starting the event loop<br>  scheduleMicrotask(() =&gt; microtaskQueue.add(&#39;Initial microtask&#39;));<br>  eventQueue.add(&#39;Initial event&#39;);<br>  runEventLoop();<br>}<br><br>void runEventLoop() {<br>  while (programRuns) {<br>    eventLoopIteration();<br>  }<br>  disposeProgram();<br>}</pre><p>Her bir iterasiýada kod takmyndan şu işi amala aşyrýar.</p><pre>void eventLoopIteration() {<br>  if (microtaskQueue.isNotEmpty) {<br>    var task = microtaskQueue.removeFirst();<br>    print(&#39;Executing microtask: $task&#39;);<br>  } else if (eventQueue.isNotEmpty) {<br>    var event = eventQueue.removeFirst();<br>    print(&#39;Handling event: $event&#39;);<br>  } else {<br>    stopEventLoop();<br>  }<br>}<br><br>void scheduleMicrotask(Function task) {<br>  microtaskQueue.add(task.toString());<br>}<br><br>void stopEventLoop() {<br>  programRuns = false;<br>}<br><br>void disposeProgram() {<br>  print(&#39;Cleaning up and exiting...&#39;);<br>}</pre><ol><li>Programma işe başlaýar.</li><li>EventLoop mikrotasklaryň bütin nobatyny (Microtask Queue) <a href="https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics)#:~:text=In%20computing%20and%20in%20systems,the%20queue%2C%20is%20processed%20first.">FIFO tertibinde</a> düzýär.</li><li>Soňra waka nobatyna (Event Queue) geçip, nobatdaky wakany işleýär.</li><li>Soňra sikl (iterasiýa) başyna gaýdýar — 2-nji punkta.</li><li>Waka nobaty boşalanda, programma işini tamamlaýar.</li></ol><p>Biz ýokarda iki täze düşünje bilen tanyşdyk: Microtask we Event. Kod ýazanymyzda, biz bu düşünjeler bilen göni aragatnaşykda bolmaýarys, şonuň üçin haýsy hereketlerimiziň Event we Microtask döredýändigini düşünşeliň.</p><h3>Microtask</h3><p>Bu juda kiçi we çykdajysy az operasiýalar, olar asinhron ýagdaýda we mümkin boldugyça tiz ýerine ýetirilmeli.</p><p>Microtasky scheduleMicrotask() funksiýasy arkaly döredip bolar, we ol möhüm koduň başlangyjynda ulanylmaly.</p><pre>class MyVeryImportantManager{<br>   void init(){<br>      scheduleMicrotask((){<br>         // wajyp kod<br>      });<br>   }<br>}</pre><p>Bu ýerde, bizde operasiýalarymyzyň ileri tutulýanlygyny (prioritetyny) üýtgetmek mümkinçiligine eýe bolýandygymyz baradaky täsir döreýär. Bu aslynda dogry, Dart-yň köpçülikleýin (publik, açyk) API-si bize bu mümkinçiligi berýär, ýöne munuň bilen seresap bolmaly. Koduňyzda Future (ona aşakda ýene-de serederis) we Microtask garyşdyrylan bolsa, ol kod howpsuzdyr (stabilny däl) bolup biler:</p><ul><li>Future we Microtask siziň garaşýan tertibiňizde işlejegine kepil ýok.</li><li>Kadry çyzýan koduň ählisi — bu EventQueue-daky Events -dyr. Uzyn Microtask nobaty EventQueue-iň işlenişini bloklaýar, we ulanyjy, iň gowy ýagdaýynda, kadrlaryň arasynda boşluklary görer (junk), iň erbet ýagdaýynda, doňan UI görer.</li></ul><p>Mysal üçin, Flutter-yň çeşme (sourcecode) <a href="https://github.com/search?q=repo%3Aflutter%2Fflutter+scheduleMicrotask&amp;type=code">kodlarynda</a> scheduleMicrotask() köp ulanylmandyr, ýöne olar örän kiçi operasiýalar üçin, UI-yň akymlylygyny üpjün etmek üçin möhüm ýerlerde işjeň ulanylýar.</p><h3>Event</h3><p>Bu, Event Queue-na düşýän (nobata düşýän) we Event Loop tarapyndan işlenilmäge degişli bolan daşarky wakadyr (daşyndan gelýän waka, meselem ulanyjy ekrana basmak, UI renderi tazelemek).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQpWIGbLXCMXHLtAsjFJ0g.png" /></figure><p>Mysal üçin:</p><ul><li>Giriş/çykyş operasiýalary</li><li>Jestler (ekrana basmak, saklamak, swipe etmek, press etmek we ş.m.)</li><li>Çyzmak (Render etmek)</li><li>Taýmerler</li><li>…</li></ul><p>Edil Event Queue nobatyna göniden göni özümiz täze wakalary goşup bilmeris. Munuň ýekeje kadadan çykma ýagdayy — Future API. Olar barada aşakda has giňişleýin gürrüň ederis.</p><h3>Future</h3><p>Future — bu gelejegiň bir wagtynda tamamlanjak (netijesini berjek) we häzirlikje gyra süýşirilen (emma eýýäm başlanan) operasiýadyr.</p><p>Bu, köp ýagdaýlarda peýdaly bolup biler: mysal üçin, biz serwere sorag ibermeli, we onuň ýerine ýetirilişi dowam edýärkä, soragyň ýerine ýetiriliş wagtyny görkezmeli. Bu wezipäni diliň bloklanmaýan asinhron kodlary bolmazdan çözüp bilmeris.</p><pre>void serverRequest(){<br> print(&#39;Start loading&#39;);<br> var seconds = 0;<br> Timer? timer;<br>  Future(getServerData).then((result){<br>  timer?.cancel();<br>  print(result);<br> });<br> // Aşakdaky kod server request-dan son ýerine ýetirilip başlar<br> timer = Timer.periodic(Duration(seconds:1), (_) {<br>  print(&#39;Seconds elapsed: ${seconds++}&#39;);<br> });<br>}<br> <br>Future&lt;String&gt; getServerData() =&gt; //server request</pre><p>Future adaty klass bolup, onda hem öz konstruktorlar bar.</p><p>Meselem:</p><pre>Future((){<br> // Some async job<br>});</pre><p>Bu ýerde biz konstruktora funksiýa iberýäris — bu <strong>funksiýa</strong>, Event Loop tarapyndan ýerine ýetiriljek we netijesini ýa-da ýalňyşlygy şu Future-yň işleýşine (obraborçigyna/handler) gaýtaryljak <strong>wakadyr (event)</strong>.</p><p>Birnäçe bellemeli zatlar bardyr:</p><ul><li>Future API mikrotasklary hem döredip biler, ol Future.microtask() fabrik-konstruktory arkaly amala aşyrylýar — onuň ýerine ýetirilişini beýleki islendik Future ýaly işläp bileris.</li><li>Future.delayed() konstruktor ulanyp, koduň ýerine ýetirilişini kesgitli möhlete çenli yza süýşürip bileris. Mysal üçin, eger biz operasiýalaryň trotlingini — ýagny, bir operasiýany X millisekund aralykda birden köp ýerine ýetirmezlik — amala aşyrmak isleýän bolsak.</li></ul><h4>Future-yň Ýagdaýlary</h4><p>Ýokarda belläp geçişimiz ýaly, “<em>Future — bu häzirlikçe gyra süýşirilen operasiýa</em>” diýip aldyk. Diýmek, onuň iki sany ýagdaýy bölüp biler:</p><ul><li>Uncompleted — Future-içindäki kod heniz başlanmadyk ýa-da ýerine ýetirilýär.</li><li>Completed — Future-iň işi bir <strong>netije</strong> (rezultat) bilen ýa-da <strong>ýalňyşlyk </strong>(error)<strong> </strong>bilen tamamlandy.</li></ul><h4>Future Netijesini Işlemek</h4><p>Munuň üçin then kolbekini hasaba almak (registrasiýa etmek) zerurdyr. Ol, Future-içindäki funksiýa tamamlanandan dessine çagyrylar.</p><pre>void main() {<br>  Future(() {<br>    print(&#39;Future print&#39;);<br>  }).then((_) =&gt; print(&#39;Print after future&#39;));<br>}</pre><blockquote>Başgada hem .then() kolbagine derek biz await açar sşzüni ulanyp funksiýamyzy çagyryp bileris.</blockquote><h4>Future ýalňyşyny Işlemek</h4><p>Future işleýän wagty ýalňyşlyk ýüze çyksa, Event Loop ony catchError kolbegine iberer:</p><pre>void main() {<br>  Future(() =&gt; print(&#39;Future print&#39;))<br>      .then((_) =&gt; print(&#39;Print after future&#39;))<br>      .catchError((error, stacktrace) =&gt; print(error));<br>}</pre><p>then funksiýasynda şeýle-de meýletin onError kolbegi bar, onuň prioriteti catchError-den &quot;ýokarydyr&quot;:</p><pre>void main() {<br>  Future(() =&gt; throw Exception())<br>      .then(<br>        (_) =&gt; print(&#39;Print after future&#39;),<br>        onError: (error, stacktrace) =&gt; print(&#39;Then: $error&#39;),<br>      )<br>      .catchError((error, stacktrace) =&gt; print(&#39;catchError: $error&#39;));<br>}</pre><p>onError() metod hem bardyr, öz içinde catchError() çagyrýar.</p><p>Ol şu aýratynlyklary bilen tapawutlanýar:</p><ul><li>Ýalňyşlygyň gurluşyny (strukturasyny) üýtgedip biler.</li><li>Netijede şol ýalňyşlygyň tipi, başdaky ýalňyşlygynyň tipi bilen birmeňzeş bolmagyny kepillendirýär.</li></ul><p>Mysal üçin, bu serwerden gelýän ýalňyşlyk kodlaryny dolandyrmakda peýdaly bolup biler.</p><p>Diýeliň, serwer soraga jogap hökmünde standart HTTP kodlaryndan başga-da dürli ýalňyşlyk kodlaryny ýollan ýagdaýynda:</p><pre>void main() {<br>  Future(() =&gt; performNetworkRequest())<br>      .onError((error, stackTrace){<br>        if(error.body.code == 1){<br>          // Ýenede bir Future konstruktor. Event Loop-dan ugradylan ýalňyşlygu dessine atar<br>          return Future.error(CodeOneError());<br>        }<br>                              <br>        return error;<br>      });<br>}</pre><h3>Asinhron işlemek</h3><p>Biz ýokarda Event Loop-yň, waka nobatynyň we Future-iň işleýiş düzgünlerini ara alyp maslahatlaşdyk. Emma bu, “Eger Event Loop adaty sinhron sikl bolsa, waka nobaty gurluşy — FIFO bolsa, we Future — bu waka nobatyna waka döretmek üçin interfeýs bolsa, onda şularyň içinde<strong> näme zat asinhron</strong>?” diýen soraga jogap berip bilenok.</p><p><strong>Jogap</strong> — hiçzat.</p><p>EventLoop-yň işleýşini täzeden pikirlensek, agyr wakanyň EventLoop-yň işini bökdäp, programmaň doňmagyna getirip biljekdigini aýdyp bileris. Ýokarda agzalan zatlaryň hiç haýsysy koduňyzy asinhron etmez.</p><p>Emma bu zatlaryň ählisi, asinhron funksiýalaryň nämedigini we olaryň maksatlaryny düşünmäge kömek edýär.</p><p>Indi öňümizde kyn teoriýa bar, şonuň üçin dili döreden deweloperleriň öz <a href="https://dart.dev/codelabs/async-await">terminologiýasy</a> bilen kesgitläliň.</p><p>Esasy düşünjeler:</p><ul><li><strong>Sinhron operasiýa</strong>: Häzirki işlenýän kody doly işläp gutarýança indiki kody bloklap biljek (oňa başlap bilmeýän) islendik sinhron iş.</li><li><strong>Sinhron funksiýa</strong>: Diňe sinhron operasiýalary ýerine ýetirip bilýän funksiýa.</li><li><strong>Asinhron operasiýa</strong>: Başlandan soň, we tamamlanýança başga operasiýalaryň ýerine ýetirilmegine mümkinçilik berýän (olary bloklamaýan) iş.</li><li><strong>Asinhron funksiýa</strong>: Azyndan bir asinhron operasiýany ýerine ýetirýän we çäksiz mukdarda sinhron operasiýalary ýerine ýetirip bilýän funksiýa.</li></ul><p>Ilkinji iki düşünje anyk bolsa-da (sinhron operasiýa — adaty tanyşlyk kod, sinhron funksiýa — islendik asinhron däl funksiýa), galanlary biraz düşnüksiz bolmagy ahmal.</p><p>Geliň has giňişleýin düşündireliň.</p><h4>Asinhron operasiýa</h4><p>Future baradaky bölümde koduň bloklanmagynyň öňüni alýan mysallary eýýäm getirdik.</p><p>Bu has dogrusy däl:</p><p>Future-iň içindäki koduň nädip işleýändigi, onuň içine iberilen (giriş parametr hökmünde bellenilen) funksiýanyň sinhronmy ýa-da asinhronlygyna baglydyr.</p><p>Sinhron operasiýalar nobatdaky koduň ýerine ýetirilişini bloklap biler sebäbi, Event Loop täze sikle geçmezden öň şular ýaly (sinhron) operasiýalary işlemäge borçludyr.</p><p>Netijede, Future asyl ýalan (hakyky däl) asinhron operasiýalary döretmäge mümkinçilik berýär, olaryň hem ýerine ýetiriliş tertibi hakykatda oňa geçirilen (iberilen) funksiýa baglydyr.</p><p>Soňky düşünje üçin aşakdaky kody gözden geçireliň:</p><pre>print(&#39;Before Future&#39;);<br>Future(()=&gt; print(&#39;Future&#39;)).then((_)=&gt; print(&#39;Future then&#39;));<br>print(&#39;After Future&#39;);</pre><p>Çykyş (print) tertibi şeýle bolar: Before Future → After Future → Future → Future then</p><p>Bu dogry, ýöne hakykatda print şeýle bolar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RdxPPH3nDVdwd8P7hZGrUw.png" /></figure><p>Şeýle tertip hemişe dogry bolar, şoňa görä:</p><ul><li>Future hakyky asinhron operasiýa däldir. Hem Future, hem-de onuň içindäki kod asyl sinhron operasiýalarydyr.</li><li>Future ýeňil parallellik çözgüdi däldir. Eger bu dogry bolsady, biz After Future çykyşynyň Future-dan öň boljagyny kepillendirip bilmezdik (100% garantiýa bermezdik).</li></ul><h3>Asinhron funksiýa</h3><p>Kesgitlemäni gaýtalaly:</p><ul><li><strong>Asinhron operasiýa</strong>: Başlandan soň, we tamamlanýança başga operasiýalaryň ýerine ýetirilmegine mümkinçilik berýän (olary bloklamaýan) iş.</li><li><strong>Asinhron funksiýa</strong>: Azyndan bir asinhron operasiýany ýerine ýetirýän we çäksiz mukdarda sinhron operasiýalary ýerine ýetirip bilýän funksiýa.</li></ul><p>Sinhron funksiýany asinhrona öwürmek üçin, funksiýanyň göwresiniň (body) öňünde async açar sözüni goşmak ýeterlikdir:</p><pre>void myAsyncFunction() async {<br> print(&#39;Some job&#39;);<br>}</pre><p>Gutlaýaryn, indi myAsyncFunction() çagyryşy — asinhron operasiýa.</p><p>Barlap göreli:</p><pre>    <br>void main() {<br>  print(&#39;Before operation&#39;);<br>  foo();<br>  print(&#39;After operation&#39;);<br>}<br><br>void foo() async {<br>  print(&#39;async&#39;);<br>}</pre><blockquote>Print: Before operation &gt; async &gt; After operation</blockquote><p>Bir zada ýalňyş boldy gerek? foo() funksiýasy asinhron bolsa-da, ol print(&#39;After operation&#39;) çagyryşyny bloklamaly däldi.</p><p>Hakykatda, async bilen bellenilen funksiýalar sinhron ýagdaýda işleýärler, emma olar await açar sözüne ilkinji gegezek duşanda asinhron işe başlaýar.</p><pre>void main() {<br>  print(&#39;Before operation&#39;);<br>  foo();<br>  print(&#39;After operation&#39;);<br>}<br><br>void foo() async {<br>  await Future.delayed(Duration.zero, () =&gt; print(&#39;async&#39;));<br>}</pre><p>Doly düşünmek üçin, asinhron funksiýanyň düşünjesini giňeldeliň:</p><p>Bu, işleýşini wagtlaýynça duruzyp, dolandyryşy yzyna çagyryş ýerine geçirip bilýän (nireden çagyrylan bolsa şona yzyna berip bilýän) funksiýadyr. Blok edýän kodyň bölegi (operasiýa) tamamlanansoň, funksiýanyň işleýşi duran (duruzylan) ýerinden dowam eder.</p><p>await — koduň ýerine ýetirilmegini wagtlaýynça togtatmaga mümkinçilik berýär açar sözüdir.</p><p>Birnäçe möhüm bellikler:</p><ul><li>await diňe async bilen bellikli funksiýanyň içinde ulanylyp bilner.</li><li>Diňe Future-iň tamamlanyşyny garaşyp bileris.</li><li>Asinhron funksiýa diňe Future görnüşli netijeleri (rezultady) gaýtaryp biler.</li><li>Asinhron funksiýanyň gaýtaryşy (return resultaty) void bolup biler, ýöne şol ýagdaýda onuň tamamlanyşyny garaşyp bilmersiňiz.</li></ul><p>Indi ýaňky mysaly üýtgedip göreliň. Kody başlatmazdan öň, netijäni özüňiz çaklamaga synanyşyň:</p><pre>void main() {<br>  print(&#39;Before operation&#39;);<br>  getAsyncJobValue().then((value) =&gt; print(&quot;Go async value: $value&quot;));<br>  print(&#39;After operation&#39;);<br>}<br><br>Future&lt;int&gt; getAsyncJobValue() async {<br>  print(&#39;Sync inside async&#39;);<br>  await Future(()=&gt; print(&#39;Awaited async job&#39;));<br>  return Future.value(5);<br>}</pre><p>Indi hemme zat dogry ýola düşdi:</p><ul><li>Asinhron getAsyncJobValue() funksiýasy çagyryldy;</li><li>Kod sinhron ýagdaýda başlandy;</li><li>9-njy setirde await getAsyncJobValue()-iň işleýişini wagtlaýynça duruzdy, emma esasy main() funksiýasynyň işleýişini bloklamady;</li><li>9-njy setirde Future işini tamamlanansoň, kod dowam etdi.</li></ul><p>Dowam etmäkäk ozal öwrenenlerimizi gysgaça ýatladyp geçeliň: ⚠️</p><ul><li>Asinhron funksiýany async açar sözi bilen döretmek bolýar, ýöne kod diňe await sözinden soň asinhron ýerine ýetirilip başlaýar.</li><li>Future özi bir operasiýa däl-de, onuň içindäki funksiýa sinhron ýa-da asinhron bolup biler.</li><li>Event Loop — bu wakalary yzygiderli dolandyrmak üçin ulanylýan, çäksiz aýlanýan sikldir, ol psewdo-parallelligi (parallelligi imitasiýa etmäge) gazanmaga mümkinçilik berýär.</li></ul><h4>Ýalňyşlyklary işlemek</h4><p>Bu, try/catch gurluşy arkaly amala aşyrylýar. Ýöne bir bellemeli zat bar:</p><ul><li>Eger asinhron funksiýanyň netijesi garaşylmaýan bolsa, ýalňyşlyk ýüze çykan ýagdaýynda, try/catch blok ony tutup bilmez.</li></ul><p>Bu näme üçin şeýle bolýandygy barada has giňişleýin maglumat <strong>Advanced</strong> bölüminde belläris, emma häzirki wagt üçin bir mysal bereliň.</p><pre>   <br>void main() {<br>  badAsyncJob();<br>  goodAsyncJob();<br>}<br><br>badAsyncJob() async {<br>  try {<br>    print(&#39;Start badAsyncJob&#39;);<br>    throwAsyncJob();<br>  } catch (e, stacktrace) {<br>    print(&#39;Caught badAsyncJob: $e&#39;);<br>  }<br>}<br><br>goodAsyncJob() async {<br>  try {<br>    print(&#39;Start goodAsyncJob&#39;);<br><br>    await throwAsyncJob();<br>  } catch (e, stacktrace) {<br>    print(&#39;Caught goodAsyncJob: $e&#39;);<br>  }<br>}<br><br>throwAsyncJob() async {<br>  print(&#39;Start throwAsyncJob&#39;);<br>  throw Exception(&#39;Hello, i am async error&#39;);<br>}</pre><blockquote>Start badAsyncJob<br>Start throwAsyncJob<br>Start goodAsyncJob<br>Start throwAsyncJob<br>Caught goodAsyncJob: Exception: Hello, i am async error</blockquote><p>Görşüňiz ýaly, badAsyncJob() funksiýasynyň catch bloky Exception-ny işläp bilmedi.</p><blockquote>Asinhron operasiýalarda ýalňyşlyklary tutmakçy bolsak, onda olaryň garaşylýan netijesine (return bahasyna) seretmek (şoňa garaşmak) zerurdyr.</blockquote><h4>Taýmerler</h4><p>Dart-da taýmer — bu, Event Loop — daky wakalaryň kömegi hem-de wagtyň üsti bilen (wagtyň geçmegi bilen) ýerine ýetirilýän käbir operasiýalary amala aşyrmaga mümkinçilik berýän klasdyr.</p><p>Iň ýönekeý taýmerleriň mysaly:</p><pre>// Bir sekuntdan &#39;on Tick&#39; print eder<br>Timer(Duration(seconds: 1), (){<br> print(&#39;on Tick&#39;);<br>});<br> <br>// Her sekund &#39;on Tick&#39; print eder<br>Timer.periodic(Duration(seconds: 1), (timer){<br> print(&#39;on Tick&#39;);<br>}); </pre><p>Future barada gürrüň edilende, biz Future.delayed() metodyny agzap geçdik, ol hem taýmer bilen deňeşdirilende şol bir işi ýerine ýetirýär. Emma olaryň arasynda birnäçe tapawut bar:</p><ul><li>Timer klass Timer obýekti gaýtaryp berýär.</li><li>Future.delayed metody Future gaýtaryp berýär we muny await bilen ulanmaga mümkinçilik berýär.</li><li>Timer koduň içindäki iş tamamlanmazdan öň ýapylyp bolýar, emma Future bilen olar ýaly zatlar mümkin däl.</li></ul><pre>final timer = Timer(Duration(seconds: 1), (){<br>  print(&#39;on Tick&#39;);<br>});<br>timer.cancel();// Hiç zat print edilmez</pre><ul><li>Future.delayed içinde Timer-dan peýdalanýar, <a href="https://api.flutter.dev/flutter/dart-async/Future/Future.delayed.html">dokumentasiýa</a> serediň.</li></ul><h3>Isolate</h3><p>Öňde agzap geçişimiz ýaly:</p><p>Dart-da<em> </em><em>Isolates (izolýatorlar) </em>bar, olar<em> </em><em>Threads (iş potok, akym) </em>bilen<em> </em>deňeşdirilýär emma olardan tapawutly.</p><p>Indi bu nämäni aňladýandygyny düşündirmegiň wagty geldi.</p><p><strong>Isolate</strong>:</p><ul><li>Bu, Dart-da psewdo-parallelligiň amala aşyrylyş usulydyr.</li><li>Her bir izolýat özüniň Event Loop-y we Ýat bölegi (meýdany, ýeri) bar.</li><li>Islendik mukdarda izolýat döredip bilersiňiz.</li></ul><p>Näme üçin psewdo-parallellik we näme üçin Isolate doly iş Thread meňzeş däl, ony <strong>Advanced</strong> bapda ara alyp maslahatlaşarys.</p><p>Häzirlikçe bolsa olaryň peýdaly taraplaryna seredeliň:</p><p>Öňde EventLoop barada gürrüň edenimizde, agyr operasiýalar Dart kodunyň işini doly bloklap biler diýdik. Isolate ulanmagy bilen, käbir çylşyrymly (agyr) operasiýalary “<em>asinkron</em>” ýagdaýda ýerine ýetirip, soňra bolsa netijäni esasy izolýatda gaýtaryp işläp bileris.</p><p>Isolýat döretmegiň iki ýönekeý usuly bar:</p><ul><li><a href="https://api.dart.dev/stable/2.19.4/dart-isolate/Isolate/run.html">Isolate.run</a> ulanmak bilen</li></ul><pre>int slowFib(int n) =&gt;<br>    n &lt;= 1 ? 1 : slowFib(n - 1) + slowFib(n - 2);<br>Isolate.run(() =&gt; slowFib(40));</pre><p>Isolate.run siziň üçin izolýat döreder, içindäki kolbekde kody ýerine ýetirer, netijäni gaýtarar we izolýaty ahyrynda özi arassalar. Möhüm nokat: izolýatyň giriş nokady diňe ýokary derejeli funksiýalar, statiki funksiýalar ýa-da ýapyk funksiýalar (<a href="https://dart.dev/language/functions#:~:text=A%20closure%20is%20a%20function,outside%20of%20its%20original%20scope.">closures</a>) bolup biler . Ýapyk funksiýalar bilen seresaply bolmaly: olar diňe şol izaolýata elýeterli bolan obýektleri ulanmalydyr.</p><ul><li>compute funksiýasy arkaly</li></ul><pre>Future&lt;bool&gt; isPrime(int value) {<br>  return compute(_calculate, value);<br>}<br>bool _calculate(int value) {<br>  if (value == 1) {<br>    return false;<br>  }<br>  for (int i = 2; i &lt; value; ++i) {<br>    if (value % i == 0) {<br>      return false;<br>    }<br>  }<br>  return true;<br>}</pre><p><a href="https://api.flutter.dev/flutter/foundation/compute.html">compute</a> finksiýa siz üçin izolýat döreder, içindäki kolbekde kody ýerine ýetirer, netijäni gaýtarar we izolýaty ahyrynda arassalar.</p><h3>Stream we Reaktiw Programmirleme</h3><p>Reaktiw ýa-da deklaratiw programmirlemäniň konsepsiýasy asinhron wakalaryň yzygiderliginden esaslanýar.</p><p>Bu konsepsiýanyň mazmuny şu shemada beýan edilip bolar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*us6ytgv94qdYE2xd4HFmAA.png" /></figure><p>Umuman belli bir asinhron waka <strong>generatory</strong> bar we şol wakalary diňleýän <strong>diňleýjiler</strong> bar.</p><p>Dart-da, şeýle zat Stream diýlip atlandyrylýar. Stream-i birnäçe usul bilen döredip bolýar:</p><ol><li>Konstruktor ulanmak bilen.</li></ol><pre>final stream = Stream.fromIterable([1, 2, 3, 4, 5]);</pre><p>Beýleki konstruktorlar barada <a href="https://api.dart.dev/stable/2.19.4/dart-async/Stream-class.html">dokumentasiýada</a> has giňişleýin maglumat alyp bilersiňiz.</p><p>2. Asinhron generatory ulanmak bilen. Onuň işleýiş düzgüni adaty generatoryňky ýalydyr, ýöne ol Iterable däl-de, Stream gaýtaryp berýär.</p><pre>Stream&lt;int&gt; generateStream() async* {<br>  int count = 1;<br>  while(count &lt;= 5){<br>    yield count++;<br>  }<br>}</pre><p>3. StreamController ulanmak bilen. Bu barada aşakda has giňeşleýin durarys, emma häzirlikçe iň ýönekeý Stream-iň mysalyny, StreamController arkaly döredileni görkezeliň:</p><pre>class StreamProvider {<br>  final _controller = StreamController&lt;int&gt;();<br>  Stream get stream =&gt; _controller.stream;<br>  void startPushingEvents() {<br>    for (int i = 0; i &lt; 20; i++) {<br>      _controller.sink.add(i);<br>    }<br>  }<br>  void stopPushingEvents() {<br>    _controller.close();<br>  }<br>}</pre><p>Aslynda StreamProvider 1-den 19-a çenli sanlaryň yzydigerligini jemleýän ýönekeýje Stream — y bize döredip berýär. Stream -dan daşary sink ýüze çykýär we controller -y ýapmagy talap edilýär. Bularyn näme üçin gerekdigini biz aşakda düşündireris.</p><h4>StreamController</h4><p>Asinhron wakalary döredilmeginiň kämil usuly hökmünde göz oňümizde geterip bileris. Onuň interfeýsiniň jemgyýetçilik (public) agzalarynyň arasynda:</p><ul><li>sink — wakalary kabul edýän obýekt.</li><li>stream — Stream obýektiň özi.</li></ul><p>Umuman aýdanyňda, StreamController-iň işini şeýle beýan etmek bolar:</p><ol><li>Koduň bir ýerlerinde stream obýektine diňleýji agza bolýar (eventlara ýazylýar).</li><li>Koduň başga bir ýerine sink arkaly wakalary goşýar — ýalňyşlyklar, wakalar ýa-da başga bir Stream.</li><li>StreamController derrew wakalary stream-iň abonentlerine ugradýar (habar berýär).</li></ol><p>StreamController Stream API bilen işlemegiň iň amatly usuly bolup görünýär, ýöne onuň hereketleri ulanylýan StreamController görnüşine baglydyr.</p><p>Indiki shemany göz öňünde tutup, has giňişleýin maslahatlaşalyň:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mde5k7rXy4gZN8CqfwnFnQ.png" /></figure><p>StreamController iki esasy görnüşe bölünýär:</p><h4>Single-subscription StreamController</h4><p>Standart konstruktor StreamController -y döredýär, ol Single-subscription Stream berýär. Bu nämäni aňladýar:</p><ol><li>Stream-e diňe bir abonent (diňleýji) bolup biler.</li><li>Ähli wakalar buferde ýygnalýar, şonuň üçin abonent giç (bir näçe wagt geçenden soň) abuna bolsa-da (ýazylsada), wakalaryň bütin sanawyny (ähli yzygiderligini) kabul edýändigine kepil berýär.</li><li>Eger hiç kim ony diňlemeýän bolsa, StreamController ýapylmalydyr, bu resurslaryň syzmagynyň (harçlanmasyny) öňüni alar.</li><li>Stream -a hiç kim ýazylmasa, waka döretmeli däldir.</li></ol><h4>Broadcast StreamController</h4><p>factory konstruktor StreamController.broadcast() bir Broadcast Stream berýän StreamController döreder. Bu nämäni aňladýar:</p><ol><li>Stream-de birnäçe abonent (diňleýji) bolup biler.</li><li>Ähli wakalar Sink obýektindäki add, addAll ýa-da addError metodlary çagyrylanda işjeň diňleýjiler tarapyndan Stream-a iberilýär.</li><li>Bu görnüşdäki StreamController-de bufer ýok, şonuň üçin käbir wakalary gözden galyp (diňleýja ýa-da soň ýazylan diňleýja görünmän galyp) biler.</li><li>Eger hiç kim ony diňlemeýän bolsa, StreamController ýapylmalydyr, bu resurslaryň syzmagynyň (harçlanmasyny) öňüni alar.</li><li>Stream -a hiç kim ýazylmasa, waka döretmeli däldir.</li></ol><h4>Kolbekleriň detallary</h4><ol><li>onListen — ilkinji gezek biri Stream-e diňleýji bolup ýazylanda işleýär.</li><li>onCancel — Stream ýapylanda we ony hiç kim diňlemeýän wagty işleýär.</li><li>onResume — Stream pauzadan çykanda işleýär.</li><li>onPause — Stream pauza geçende işleýär, wakalar buferde goşulýar, ýöne diňleýjiler ony alýan däldir.</li></ol><blockquote>Diňe Single-subscription bu iki soňky kolbegi bar, sebäbi diňe onda wakalar buferi bar.</blockquote><p>Ähli konstruktorlar standart ýagdaýda asinhron StreamController döredýär. Bu, her bir wakanyň EventLoop arkaly mikrotask hökmünde geçmegine sebäp bolup, bu hem öz gezeginde braz gijikmä sebäp bolýar.</p><p>Her bir konstruktoryň sync parametri bar, eger ol true bolsa, biz sinhron StreamController -y emele getireris. Emma ony seresaply ulanmalydyr.</p><p><strong>Sinhron</strong> we <strong>Asinhron</strong> StreamController döretmekliginiň mysaly</p><pre>// Asinhron kontrollerlar<br>final asyncController = StreamController();<br>final asyncBroadcastController = StreamController.broadcast();<br> <br>// Sinhron kontrollerlar<br>final syncController = StreamController(sync: true);<br>final syncBroadcastController = StreamController.broadcast(sync: true);</pre><p>Gelin sinhron kontroler barada jikme-jik göz aýlalyň.</p><h4>SynchronousStreamController</h4><p>Biz SynchronousStreamController-i seresaply ulanmalydygymyzy aýtdyk. Bu ýerde onuň berýän artykmaçlyklaryny we Stream bilen işleşmek şertnamasyny nädip bozup biljekdigini düşüneris.</p><p>Wakany mikrotask arkaly ibermegiň ýerine, waka dessine ähli işjeň diňleýjilere iberilýär. Şeýlelikde, eger siz asinhron StreamController-iň haýal işleýändigini aňsaňyz, sinhron tarapyna seredip bilersiňiz.</p><p>Indi kemçilikler barada:</p><ol><li>Asinhron Stream diňleýjileriň wakany diňe taýýar bolanlarynda aljakdygyny (kabul etjekdigine) kepillendirýär. Sinhron ýagdaýda, beýle bir kepillik ýok we diňleýji wakany işläp bilmäge ýagdaýy bolmasada kabul etmeli bolýar. Mysal üçin biz harydyň sanyny görkezýän ikonka ýasaýarys. Täze 5 harydyň sebede goşulandygyny aýdýan waka sinhron Stream-e goşulanda, ýöne sebet ikonkasy heniz inisializasiýa (render) edip ýetişenok we täze wakalary diňlemäge taýýar däl bolsa, sinhron ýagdaýda biz wakany ýitireris we harydyň sanawyny görkezmeris. Asinchron ýagdaýda Dart wakanyň ýetiriljekdigini kepillendirýär.</li><li>Stream wakalaryň diňleýjilere bir tertipde gelýändigini we häzirki add metody tarapyndan iberilen waka-diňleýji tarapyndan tamamlanmasa, indiki waka iberilmeýändigini kepillendirýär. Sinhron StreamController bolsa özi bu ýagdaýy gözegçilik etmeýär, şonuň üçin Stream şertnamasyny bozma howpy bar.</li></ol><p>Gündelik (ähli) wezipeler asinhron StreamController arkaly çözülip bilner, şonuň üçin sinhron döretmegiň zerurlygy ýok. Sinhron StreamController-iň çuňňur düşündirişini almak üçin, <a href="https://api.flutter.dev/flutter/dart-async/StreamController-class.html">dokumentasiýa</a> ýüz tutmagy maslahat berýärin.</p><h4>StreamController-e wakalary ugratmak</h4><p>Ýokarda biz bir diňleýjili (single-subscription) we köpçülikleýin (broadcast) iki görnüşli Stream döretmegiň ähli usullaryny gözden geçirdik.</p><p>Stream -y konstruktor we generator arkaly döretmegiň usullary belli bolsa (wakalar diňleýjiler ýazylan pursady derrew ýetýär), onda StreamController üçin aýratyn Sink diýen mehanizm bar.</p><p>Sink-iň maksady — maglumatlary akyma girizmek üçin giriş nokady bolmak.</p><p>Dart-da Sink-iň köp sanly amala aşyrylyşy (implementasiýalary) bar, ýöne biz StreamSink-de duraly — bu klas, ol Stream üçin maglumatlary sinhron we asinhron (StreamController-iň amala aşyrylyşyna bagly) kabul edip bilýär.</p><p>Indi Sink metodlaryny gözden geçireliň, gowy düşünmek üçin bu klasyň <a href="https://api.flutter.dev/flutter/dart-async/StreamSink-class.html">dokumentasiýadaky</a> signaturasyny we amala aşyrylyşyny açyp görüň.</p><p>Diňe birnäçe metod elýeter:</p><p>EventSink&lt;S&gt;-den miras alnan:</p><ul><li>addEvent(S event) — Stream-e täze waka goşýar, soňra StreamController ony ähli işjeň diňleýjilere geçirýär.</li><li>addError(Object error) — Stream-e ýalňyşlygy goşýar. Ony abuna ýazylan ýerde handleError() arkaly tutup bolar.</li></ul><p>StreamConsumer&lt;S&gt;-den miras almak:</p><ul><li>addStream(Stream&lt;S&gt; stream) — stream-den ähli wakalary alyp, olary StreamController-e geçirýär. Future gaýtaryp berýär.</li></ul><p>Sink-den miras almak:</p><ul><li>close — Sink-e bu instans üçin täze wakalar bolmajakdygyny habar berýär. Eger ýapyk Sink-e zat goşmaga synanyşsaňyz, ýalňyşlyk alarsyňyz.</li></ul><p>Hem-de birje häsiýet (property) bar:</p><ul><li>done — Bu, StreamSink ýapylanda ýa-da EventSink-iň bir usuly ýalňyşlyk döredende ýerine ýetiriljek Future obýektydyr.</li></ul><blockquote>addStream() -yň Future prosesy işjeň wagtynda, EventSink-iň usullaryndan peýdalanyp bolmaýar. Ýogsam, ýalňyşlyk alarsyňyz.</blockquote><h4>Stream wakalaryny işlemek</h4><p>Wakalary işläp başlamak üçin iki usul bar:</p><ol><li>listen() metody</li><li>Asinhron for sikli (await for)</li></ol><p>Indi await for-y gözden geçireliň.</p><p>Adaty for in sikli bilen deňeşdirilende, onuň üç tapawudy bar:</p><ol><li>for-dan öň await goşmaly</li><li>Ol diňe Stream wakalary boýunça iterirlenip bilner</li><li>Ony diňe asinhron funksiýada ulanyp bolýar</li></ol><p>Has gowy düşünmek üçin bir mesele çözeliň:</p><p>Bize faýlyň tutuş mazmunyny okap, ony bir setirde jemlemek gerek.</p><p>Munuň üçin biz iki funksiýa ýazalyň, olar iterirlenýän massiwyň (Iterable) we Stream-iň setirlerini bir doly setirde jemläliň.</p><pre>String concatStrings(Iterable&lt;String&gt; collection) {<br>  final stringBuffer = StringBuffer();<br>  for (final string in collection) {<br>    stringBuffer.write(string);<br>  }<br>  return stringBuffer.toString();<br>}<br> <br>Future&lt;String&gt; conctatStreams(Stream&lt;String&gt; stream) async* {<br>  final stringBuffer = StringBuffer();<br>  await for (final string in stream) {<br>    stringBuffer.write(string);<br>  }<br>  return stringBuffer.toString();<br>}</pre><p>Şeýlelikde, biz bir zadanyň iki çözgüdini aldyk, emma conctatStreams() arkaly faýlyň mazmunyny asinhron işläp bilýäris we başga kodyň ýerine ýetirilişini bloklamaýarys.</p><blockquote>Belläp geçsek, await for ýalňyşlyk wakalaryny işläp bilmeýär. Eger ýalňyşlyk ýüze çyksa, sikl işläp bilmän durýar.</blockquote><p>Indi listen() metodyny gözden geçireliň.</p><p>Bu metod kodyň islendik ýerinde Stream-e abunaçy (diňleýji) döretmäge mümkinçilik berýär.</p><blockquote>Ýatladýarys, single-subscription Stream üçin birden köp abunaçy döretmäge bolmaýar. Kompilýator muny gözegçilik etmeýär, şonuň üçin programma işleýän wagtynda (run time) ýalňyşlyk alarsyňyz.</blockquote><p>Indi listen() metodyny çagyrmak bilen kodyň mysalyna seredeliň.</p><pre>StreamSubscription&lt;T&gt; createStreamSubcription&lt;T&gt;(Stream&lt;T&gt; stream) {<br>  final streamSubscription = stream.listen(<br>    _handleStreamEvent,<br>    onError: _handleOnError,<br>    onDone: _handleOnDone,<br>    cancelOnError: true,<br>  );<br>  return streamSubscription;<br>}<br> <br>void _handleStreamEvent&lt;T&gt;(T event) {<br>  print(&#39;Got new event $event&#39;);<br>}<br> <br>void _handleOnError(Object? error, StackTrace? stackTrace) {<br>  print(&#39;Got stream error&#39;);<br>}<br> <br>void _handleOnDone() {<br>  print(&#39;Stream subscription closed&#39;);<br>}</pre><p>Ilki bilen, göze ilýän zat — listen() metody StreamSubscription obýekti gaýtarýar. Bu hem abuna (ýazylma, podpiska, subscription). Abunany durzup bileris (pause()), gaýtadan işledip bileris (resume()) we ýapyp bileris (cancel()).</p><p>Eger cancelOnError == true diýen flag bar bolsa, onda ilkinji ýalňyşlyk wakasyndan soňra abuna ýapylar.</p><blockquote>cancel() bilen ünsli boluň — ýapyk abunany dikeltmek mümkin däl, we Stream özi sizin üçin ony ýapmaz. Muny ýatdan çykarsaňyz wakalar siziň garaşmaýan ýagdaýlaryňyzda syzyp biler.</blockquote><p>Abuna (ýazylma) wagtynda birnäçe yza çagyryş (callback) kesgitläp bilersiňiz:</p><ul><li>onData — her gezek StreamSubscription Stream-däki wakany işleýän wagty çagyrylar.</li><li>onError — Stream-da ýalňyşlyk peýda bolanda çagyrylar. Eger kesgitlenmese, ähli ýalňyşlyklar işlenmedik hökmünde kabul edilip, häzirki zonanyň işleýjisine iberiler.</li></ul><blockquote>zonalar barada gelejekdäki bölümlerde gürrüň ederis.</blockquote><ul><li>onDone — Stream ýapylsa we bu barada waka iberse çagyrylar. Ýagny, ýalňyşlyksyz tamamlansa. Eger kesgitlenmese, hiç zat bolmaz.</li></ul><blockquote>Diňe esasy waka işleme usullaryny gözden geçirdik, <a href="https://api.dart.dev/stable/3.0.7/dart-async/dart-async-library.html">dart:async</a> kitaphanasynda has köp <a href="https://dart.dev/tutorials/language/streams#modify-stream-methods">metod-modifikatorlar</a> bar, olar ýokarda aýdylanlardan gelip çykýar. Çylşyrymly ýagdaýlarda bolsa <a href="https://pub.dev/packages/rxdart">rxdart</a> paketini ulanyň.</blockquote><h4>Stream-da ýalňyşlyk işlemek</h4><blockquote>Bu makalada men Exception we Error düşünjileri umumaşdyryp Ýalňyşlyk diýip aldym. Aslynda olaryň hersi aýraty many berýär we olar barada giňeşleýin gürrüň bermäge çalyşaryn.</blockquote><p>Ýokarda biz Dart-da Stream işiniň prinsipini gözden geçirdik, siz eýýäm olaryň beýleki asinhron funksiýalary we Isolate-dan düýpli tapawutlydygyny göz ýetirensiňiz. Şeýle-de ýalňyşlyklar bilen, adaty try/catch ähli ýalňyşlyklary tutp bilmez.</p><blockquote>Stream-däki islendik ýalňyşlyk şeýle ýagdaýa getirer, ýagny abunaçy wakany almaz we ony onData-da işlemez. Ähli işlenmedik (unhandled) ýalňyşlyklar unhandled hasaplanýar we zonanyň obrabotçigyna (handler) geçirilýär.</blockquote><p>Ýalňyşlyk bize bir näçe ýerden garaşýar:</p><ol><li>Metod-modifikatorlaryň haýsam bolsa biri yalňyşlyk berýär. Şu ýagdaýda şundan peýdalanyp bilersiňiz:</li></ol><ul><li>Funkisiýaň içinde try/catch;</li><li>Stream -yň astynda handleError();</li><li>StreamController we StreamSubscription-däki onError yza çagyryş kolbagi.</li></ul><p>Ýalňyşlyk ýokarda beýan edilen tertipde gelýär, ýagny eger handleError() bir ýerde ýalňyşlygy tutsa, onda StreamSubscription ony almaz.</p><p>2. Stream-da ýalňyşlyk wakasy peýda boldy. Kimdir biri ony addError() arkaly bilkastlaýyn goşdy. Bu ýagdaýda:</p><ul><li>Stream -yň astynda handleError();</li></ul><pre>Stream.periodic(const Duration(seconds: 1), (count) {<br>  if (count == 2) {<br>    throw Exception(&#39;Exceptional event&#39;);<br>  }<br>  return count;<br>}).take(4).handleError(print).forEach(print);</pre><ul><li>onError kolbagi StreamController-de we StreamSubscription-da.</li></ul><p>Ýalňyşlyk ýokarda beýan edilen tertipde gelýär, ýagny eger handleError() bir ýerde ýalňyşlygy tutsa, onda StreamSubscription ony almaz.</p><ul><li>StreamSubscription-yň kolbakleriň biri ýalňyşlyk zyňýar. Şu ýagdaýda diňe try/catch ulanylýar, onError-a ýalňyşlyk düşmez.</li></ul><h3>Netije</h3><p>Bu paragrafda biz Dart-yň durnukly deklaratiw kod ýazmak üçin elýeterli gurallaryny öwrendik:</p><ul><li>EventLoop-yň näme üçin gerekdigi we onuň nädip gurnalandygyny bilýäris.</li><li>Event bilen Microtask-y tapawutlandyryp bilýäris.</li><li>Future API bilen tanyşdyk — konkurent kod ýazmak üçin gural.</li><li>Isolate-yň nämedigini we ony nädip ulanmalydygyny bilýäris.</li><li>Stream API bilen tanyşdyk — reaktiw kod ýazmagyň usuly.</li></ul><p>Indiki bölümlerde biz Flutter programmasyň daşky görnüşini döredýän komponentler bolan widget-lary öwrenmäge başlarys.</p><p>Şu aşakdaky kodyň haysy yzygiderligi boýunça print boljagyny komentariýada ýazyň göreli.</p><pre>void main() {<br>  print(&#39;1&#39;);<br>  Future(() =&gt; print(&#39;2&#39;)); <br>  Future.microtask(() =&gt; print(&#39;3&#39;));<br>  Future(() =&gt; print(&#39;4&#39;));<br>  Future.delayed(Duration(seconds:1)).then((_)=&gt; print(&#39;5&#39;));<br>  Future.delayed(Duration.zero).then((_){<br>      Future.microtask(() =&gt; print(&#39;6&#39;));<br>  });<br>  print(&#39;7&#39;);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b45382bfb8d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart: OOP Esaslary]]></title>
            <link>https://medium.com/@meinnps/dart-oop-esaslary-8f99cd24940b?source=rss-c93de175ef16------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f99cd24940b</guid>
            <category><![CDATA[türkmençe]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Merdan Durdyyev]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 02:03:34 GMT</pubDate>
            <atom:updated>2024-04-20T04:06:49.884Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bölüm #5</h4><p><em>Dart — obýekt-gönükdirilen dil, şonuň üçin bu paradigma beýleki diller bilen meňzeşdir. Bu bölümde, başda düşnüksiz bolup biljek, emma ünsli seredilende, lakoniki we gowy gurnalan kod döretmäge kömek edýän diliň aýratynlyklara serederis.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lBm4tbpBUtaZcU1gl-fYpA.png" /></figure><blockquote>Ähli bölümleri gömek üçin <a href="https://medium.com/@meinnps/flutter-a-giri%C5%9F-kursy-3d4b28de3f32">şu ýere </a>salgylanyp bilersiňiz.</blockquote><h3>Const Gurluşyjy (Konstruktor)</h3><p>Öňki bölümde, biz sada konstantalary döretmegi öwrendik, ýöne Dart const gurluşyjy arkaly konstanta obýektlerini hem döretmäge mümkinçilik berýär.</p><p>Geliň barlap göreliň:</p><pre>void main() {<br>  const printer = Printer(&#39;Hello, World!&#39;);<br>}<br><br>class Printer {<br>  final String _valueToPrint;<br><br>  Printer(this._valueToPrint);<br><br>  void printValue() {<br>    print(&#39;Printing: $_valueToPrint&#39;);<br>  }<br>}</pre><p>Run edýäs we kompilýasiýa tapgyrynda şeýle ýalňyşlygy görýäris: Cannot invoke a non-&#39;const&#39; constructor where a const expression is expected.</p><p>Bu nämäni aňladýar? Aslynda, biz bu ýalňyşlykdan iki möhüm netije alyp bileris:</p><ul><li>const üýtgeýjä (ululuga) diňe &quot;konstanta&quot; eýe bolan beýany ýazyp bolar, ýagny biz ona funksiýanyň ýerine ýetirilişiniň netijesini belläp bilmeris;</li><li>const üýtgeýjä diňe const gurluşyjy arkaly döredilen klas instansyny (nusgasyny) ýazyp bolar.</li></ul><p>Geliň, tertip boýunça seredeliň.</p><p>Ilki bilen, birinji punkty düşündirýän mysala seredeliň. Bu ýerde, biz konstant üýtgeýjä programa işläp başlandan soň belli boljak funksiýanyň netijesini bellemäge (ýazmaga) synanyşýarys, hatda netijäniň islendik wagt birmeňzeş boljak ýaly bolsada:</p><pre>   <br>void main() {<br>  const printer = getInteger();<br>}<br><br>int getInteger() =&gt; 1;</pre><p>Const variables must be initialized with a constant value. ýalňyşlyk alýarys.</p><p>Bu ýalňyşlyk, programma ýerine ýetirilmäge başlanmanka bilinmeýän gymmatlyklaryň konstanta üýtgeýjä ýazylmagyna rugsat berilmeýändigi sebäpli peýda bolýar.</p><p>Ikinji beýanda, obýekti döretmekde const açar sözüni ulanmagyň zerurdygyny aýdýar.</p><p>Barlap göreliň:</p><pre>void main() {<br>  const printer = const Printer(&#39;some String value&#39;);<br>}<br><br>class Printer {<br>  String valueToPrint;<br><br>  Printer(this.valueToPrint);<br><br>  void printValue() {<br>    print(&#39;Printing: $valueToPrint&#39;);<br>  }<br>}</pre><p>Ýalňyşlyk hiç ýere gitmedi, sebäbi Printer klasynyň const gurluşyjysy ýok.</p><p>Ony goşmaga synanşalyň. Bu görnüşli gurluşyň sintaksisy diňe başynda const bolmagy bilen adatydan tapawutlanýar.</p><pre>void main() {<br>  const printer = const Printer(&#39;some String value&#39;);<br>}<br><br><br><br>class Printer{<br>  String valueToPrint;<br>  <br>  const Printer(this.valueToPrint);<br>  <br>  void printValue(){<br>    print(&#39;Printing: $valueToPrint&#39;);<br>  }<br>}</pre><p>Ähli şertler ýerine ýetirildi: const gurluşyjy bar we konstant instans (nusga) döredilýär. Emma täze ýalňyşlyk peýda bolýar: Constructor is marked &#39;const&#39; so all fields must be final.</p><blockquote>Konstanta üýtgeýjä programma işläp başlamanka ýa-da programma ýerine ýetirilende üýtgedilip bilinjek gymmatlygy ýazyp bolmaýandygyny düşünmek möhümdir!</blockquote><p>Soňky problemany çözmek üçin, kody üýtgetmeli we täzeden barlamaly.</p><pre>void main() {<br>  const printer = const Printer(&#39;some String value&#39;);<br>  printer.printValue();<br>}<br><br>class Printer {<br>  final String _valueToPrint;<br><br>  const Printer(this._valueToPrint);<br><br>  void printValue() {<br>    print(&#39;Printing: $_valueToPrint&#39;);<br>  }<br>}</pre><p>Ahyrynda, gerek netijäni aldyk.</p><h3>Factory Gurluşyjylar</h3><p>Dart-nyň ýene bir aýratynlygy, funksiýalaryň, metodlaryň (usullaryň) we gurluşyjylaryň (konstruktorlaryň) üstünden ýazylmaýandygydyr (ýagny override edip bolmaýa).</p><p>Aşakdaky kod asla kompilirlenmez:</p><pre><br>int foo() {<br> return 5;<br>}<br> <br>int foo(int value) {<br> return value * 2;<br>}</pre><p>Bu düzgün dewelopera aşakdy ýaly uly möçberde okalmaýan, aşa üst-üstüne ýüklenen usullary bolan klasslary döretmäge rugsat bermeýär:</p><pre><br>class Mathematic {<br>  int compute() {<br>    return 5;<br>  }<br> <br>  int compute(int value) {<br>    return value * value;<br>  }<br> <br>  int compute(int left, int right) {<br>    return left * right;<br>  }<br> <br>  String compute(int left, int right, String operator) {<br>    return &#39;$left$operator$right&#39;;<br>  }<br>}</pre><p>Gurluşyjylar özi hem metod bolany üçin, onuň üçin hem şol düzgün degişli. Muňa boýun bolmak üçin, Dart dilinde factory gurluşyjylar bar.</p><p>Aşakda, bu guralyň haçan peýdaly bolup biljekdigine seredeliň.</p><ul><li>Instanslary (nusgalary) döretmek üçin aýratyn interfeýs kesgitläp bileris:</li></ul><pre><br>class Logger {<br>  String? _tag;<br>  <br>  Logger(this._tag);<br>  <br>  factory Logger.withBeautifulTag(String tag) =&gt; Logger(&#39;[$tag]&#39;);<br>  <br>  <br>  factory Logger.withDoubleTag(String tag) =&gt; Logger(&#39;$tag$tag&#39;);<br>  <br>  void log(Object? message) {<br>    print(&quot;$_tag:$message&quot;); <br>  }<br>}</pre><ul><li>Subtipleriň instanslaryny döretmekligi factory gurluşyjylaryň üstine ýükläp bolar. Bul hem öz gezeginde Union-tipini bir derejede durmuşa geçirmäge mümkinçilik berýär.</li></ul><blockquote>Union-tip — birnäçe görnüşli tiplary bir bitewi tipe birleşdirýär. Dart-da Union-tipleri doly goldaýan gural ýok, emma bar bolan serişdeler bilen şeýle konsepsiýany durmuşa geçirmek mümkindir. Ýa-da daşarky paketleri ulanyp bilersiňiz — mysal üçin, <a href="https://pub.dev/packages/freezed#union-types-and-sealed-classes">Freezed</a>.</blockquote><p>factory gurluşyjylarynda Union-tipiniň doretmegiň mysaly:</p><pre><br>// A tipy — bu Union Type  <br>class A {<br> // A - yň ekzemplaryny (nusgasyny) döretmek bolmaz<br>  A._();<br> <br>  // Ýöne biz muňa derek A klasynyň gurluşyjylary arkaly<br>  // B we C klaslarynyň nusgalaryny dörederis<br>  factory A.withB(int bValue) = B;<br>  factory A.withC(String cValue) = C;<br>}<br> <br>class B extends A {<br>  final int bValue;<br> <br>  B(this.bValue) : super._();<br>}<br> <br>class C extends A {<br>  final String cValue;<br>  C._(this.cValue) : super._();<br> <br>  factory C(String value) =&gt; C._(value);<br>}</pre><ul><li>Bu gurluşyjylar üçin const açar sözüni ulanyp bileris.</li></ul><pre><br>class A {<br>  const A();<br>// &quot;const factory&quot; gurluşyjy A.asConstFactory() &quot;const B()&quot; gurluşyjysyny çagyrýar<br> const factory A.asConstFactory() = B;<br>}<br> <br>class B extends A {<br>  const B() : super();<br>}</pre><h3>Interfeýsler</h3><p>Köp dillerden tapawutlylykda, Dart-da interface açar sözi ýok.</p><p>Dogrysyny aýdylanda, başda ol bardy, ýöne 2012-nji ýylda deweloperlar ony <a href="https://news.dartlang.org/2012/06/proposal-to-eliminate-interface.html">aýyrdylar</a> we onuň deregine Dart-nyň her bir klasynyň <a href="https://dart.dev/guides/language/language-tour#implicit-interfaces">implicit interface</a> bar.</p><blockquote>Dart-da diňe klaslar we olaryň görnüşleri: mixin we abstract class bar. Mundan beýläk düşündirişde biz şuňa salgylanarys.</blockquote><p>Printer mysalymyzy kämilleşdirip synanşalyň:</p><pre><br>void main() {<br>  Printer printer = Printer();<br>  Printer taggedPrinter = TaggedPrinter(&#39;MyTag&#39;);<br>  printer.printValue(&#39;some value&#39;);<br>  taggedPrinter.printValue(&#39;some value&#39;);<br>}<br><br>class Printer {<br>  void printValue(String value) {<br>    print(&#39;Printed: $value&#39;);<br>  }<br>}<br><br>class TaggedPrinter implements Printer {<br>  final String _tag;<br>  const TaggedPrinter(this._tag);<br><br>  @override<br>  void printValue(String value) {<br>    print(&#39;$_tag: $value&#39;);<br>  }<br>}</pre><p>Indi TaggedPrinter , implements açar sözi arkaly Printer interfeýsini durmuşa geçirýär. Bu, başga bir <strong>klas</strong> interfeýsini onuň amala aşyrylyşyny miras almazdan (inherit etman) durmuşa geçirmäge mümkinçilik berýär. Implements şeýle-de, superclass-yň (ata, parent klassyň) interfeýsiniň her bir elementini durmuşa geçirmegi talap edýär.</p><p>Dart bir klasda köp sanly interfeýsi durmuşa geçirmäge mümkinçilik berýär. Indi başga bir interfeýs FooInterface goşup we ony Printer-da durmuşa geçirmegi synanyşalyň:</p><pre>    <br>void main() {<br>  PrinterInterface printer = Printer(&#39;Hello, world!&#39;);<br>  <br>  printer.printValue();<br>  <br>  // Ýalňyşlyk peýda bolýar, sebäbi PrinterInterface &quot;foo()&quot; metody barada &quot;bilmeýär&quot;<br>  printer.foo();<br>  <br>  Printer correctPrinter = Printer(&#39;Hello, correct!&#39;);<br>  correctPrinter.printValue();<br>  correctPrinter.foo();<br>}<br><br><br>abstract class PrinterInterface{<br>  void printValue();<br>}<br><br>abstract class FooInterface{<br>  void foo();<br>}<br><br>class Printer implements PrinterInterface, FooInterface{<br> final String _valueToPrint;<br> <br>  const Printer(this._valueToPrint);<br><br>  @override<br>  void printValue() {<br>    print(&#39;Printing: $_valueToPrint&#39;);<br>  }<br><br><br>  void foo() {<br>    print(&#39;Fooing&#39;);<br>  }<br>}</pre><p>Häzir 6-njy setirde ýalňyşlygy görýäris. Bu ýalňyşlyk, öňki mysalda biz PrinterInterface görnüşli printer ululugy döretdenimiz sebäpli ýüze çykýar. PrinterInterface interfeýsinde foo() metody ýok, şoňuň üçin kompilýator hakykatdanam printer-iň foo() çagyryp biljekdigini bilmeýär.</p><p>Dogry ýol, Printer ululygynyň hasaplamasyny ulanmak ýa-da ululygynyň görnüşini anyk görkezmekdir. Onuň interfeýsinde hem printValue(), hem-de foo() bar.</p><h3>Miras Almak</h3><p>Klasslary giňeltmek (mümkünçilikleri köpeltmek, parameterlary ulaltmak) hakynda gürrüň etmezden ozal, Dart-da miras almagyň üstünde durmak möhümdir. Dokumentasiýada <a href="https://dart.dev/language/classes">mixin-based</a> miras almagyň durmuşa geçirilendigi aýdylýar. Bu, her klasyň diňe bir super (ata) klassa eýe bolup biljekdigini aňladýar. Bu möhüm çäklendirme, ýöne dil bize klasyň hereketini giňeltmegiň usullaryny hödürleýär, olar barada aşakda gürrüň ediler.</p><h3>Extends</h3><p>Extends açar sözi, klasyň hereketini miras alýan kiçi klas arkaly giňeltmäge mümkinçilik berýär.</p><p>Şunda miras alýan klass, atanyň interfeýsiniň böleklerini üýtgedip biler we her bir amala aşyrylmadyk bölegi üçin öz amala aşyryşyny hökman kesgitlemeli.</p><p>Abstrakt klasdan miras almak bilen mysala seredeliň:</p><pre>void main() {<br>  final myObject = MyClass(&#39;String value&#39;);<br><br>  myObject.foo();<br>  myObject.bar();<br>  myObject.baz();<br>  myObject.myPrint();<br>}<br><br>abstract class MyAbstractClass {<br>  final String someValue;<br><br>  MyAbstractClass(this.someValue);<br>  <br>  void foo() {<br>    print(&#39;MyAbstractClass foo: $someValue&#39;);<br>  }<br><br>  void bar();<br><br>  void baz() {<br>    print(&#39;MyAbstractClass baz: $someValue&#39;);<br>  }<br>}<br><br>class MyClass extends MyAbstractClass {<br>  MyClass(super.someValue);<br><br>  @override<br>  void bar() {<br>    print(&#39;MyClass bar: $someValue&#39;);<br>  }<br><br>  @override<br>  void baz() {<br>    print(&#39;MyClass baz: $someValue&#39;);<br>  }<br><br>  void myPrint() {<br>    print(&#39;My class print: $someValue&#39;);<br>  }<br>}</pre><p>Bu mysal adaty klaslary giňeltmek üçin hem işleýär, ýöne interfeýsiň abstrakt bölekleriniň hökmany amala aşyrylyşyndan başga — siz amala aşyrylmadyk usullary bolan adaty klas döredip bilmeýärsiňiz.</p><p>Bu mysaldan näme netije çykaryp bileris:</p><ul><li>Kiçi (subсlass, çaga, mirasdüşer) klas, ataklasyň hereketini miras alýar;</li><li>Kiçi klas, ataklasyň hereketini üýtgedip biler;</li><li>Egerde ata klasyň gurluşyjysy (konstruktory) bar bolsa, kiçi klas ata gurluşyjysyny çagyrýan öz gurluşyjysyny saklamaly;</li><li>Üýtgeýjiniň interfeýsi onuň görnüşini kesgitleýär, emma amala aşyrylyşy döredýän klas tarapyndan kesgitlenilýär.</li></ul><p>Üýtgeýjiniň görnüşini üýtgetmäge synanyşalyň:</p><pre><br>void main() {<br>  // Indi myObject-iň görnüşi - MyAbstractClass<br>  final MyAbstractClass myObject = MyClass(&#39;String value&#39;);<br> <br>  myObject.foo();<br>  myObject.bar();<br>  myObject.baz();<br>  // IDE we kompilýator bu ýerde ýalňyşlygy görkezer, sebäbi MyAbstractClass-da myPrint() metody ýok<br>  myObject.myPrint();<br>}</pre><h3>Extension</h3><p>Giňeldiş usullary — diliň örän peýdaly guralydyr. Olar klaslaryň hereketini subklaslary we Utils-klaslary döretmezden giňeltmäge mümkinçilik berýär.</p><p>Giňeldiş usullary klas üçin ýazylan jemgyýetçilik interfeýsine doly girişe eýedir.</p><p>Aşakda Extension ulanyşynyň mysaly görkezilýär:</p><pre><br>void main() {<br>  print(&#39;23&#39;.hasOneSymbol()); //false<br>}<br> <br>extension StringExt on String { <br>  bool hasOneSymbol() =&gt; length == 1;<br>}<br> <br>// Şol bir zady Utils klasyny ulanyp ýazyp bileris<br>class StringUtils {<br> static bool hasOneSymbol(String value) =&gt; value.length == 1;<br>}</pre><p>Şeýlelikde, String klasynyň hereketini giňeltmek üçin statiki usullary bolan Utils klaslaryny ýazmaly bolmarys.</p><p><strong>Extensions</strong>-ň doly mümkinçiliklerini <a href="https://dart.dev/language/extension-methods">resminamada</a> görmek bolýar.</p><h4>With we Mixin</h4><p>Ýokarda aýdyşymyz ýaly, klasyň birden köp ata-enesi ýa-da superklasy bolup bilmeýär. Ýöne with açar sözi klasyň funksionallygyny birden köp klas bilen giňeltmäge mümkinçilik berýär.</p><p>Dart topary deweloperlary ýalňyşlyklardan has köp derejede goramaga çalyşýar — şeýle düzgün köp sanly mirasdüşerlikdäki problemalary çözmäge kömek edýär. Mysal üçin, <a href="https://ru.wikipedia.org/wiki/%D0%A0%D0%BE%D0%BC%D0%B1%D0%BE%D0%B2%D0%B8%D0%B4%D0%BD%D0%BE%D0%B5_%D0%BD%D0%B0%D1%81%D0%BB%D0%B5%D0%B4%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5">romb şekilli</a> mirasdüşerlikden.</p><p>Mixin — konstruktory bolmadyk we beýleki klaslardan miras almadyk islendik klas.</p><p>Ene bu — Mixin:</p><pre>class MyMixin {<br>  void foo() {<br>    print(&#39;Mixed foo&#39;);<br>  }<br>}</pre><p>We bu Mixin:</p><pre><br>abstract class MyAbstractMixin {<br>  void bar();<br>}</pre><p>Olary täze klasa with ulanyşy bilen goşup bolar:</p><pre><br>class MyMixin {<br>  void foo() {<br>    print(&#39;Mixed foo&#39;);<br>  }<br>}<br> <br>abstract class MyAbstractMixin {<br>  void bar();<br>}<br> <br>class A with MyMixin, MyAbstractMixin {<br>  @override<br>    /// &quot;bar&quot; hökman durmuşa geçirilmeli, sebäbi bu abstrakt metod<br>  void bar() {<br>    // TODO: implement bar<br>  }<br>  <br>}</pre><p>Indi MyMixin eýýam Mixin däl, eýsem adaty klas:</p><pre><br>class B {}<br> <br>class MyMixin extends B {<br>  void foo() {<br>    print(&#39;Mixed foo&#39;);<br>  }<br>}</pre><p>MyMixin-i indi goşup bolmaýar, şonuň üçin romb şekilli mirasdüşerlik meselesi hem aradan gidýär:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*pD2h5Cxwphvcc_WVLs4D2A.png" /></figure><p>Goşundyň (garyndyny, garyşygyň) hereketi giňeldilip bilinmez, ýöne Mixin beýleki interfeýsleri amala aşyryp biler:</p><pre><br>class MyMixin implements MyAbstractMixin {<br>  void foo() {<br>    print(&#39;Mixed foo&#39;);<br>  }<br> <br>  @override<br>  // Biz abstrakt &quot;bar&quot;-y durmuşa geçiräýmeli, sebäbi MyMixin adaty klas<br>  void bar() {<br>    // TODO: implement bar<br>  }<br>}<br> <br>// A klasynyň interfeýsine iki metod goşuldy - &quot;foo()&quot;, &quot;bar()&quot;<br>// Olaryň amala aşyrylyşyny MyMixin garyşmasyndan miras aldy (inherit)<br>class A with MyMixin {<br> <br>}</pre><p>Ýokardaky mysallarda MyMixin-i adaty klas hökmünde ulanyp bilersiňiz. Şeýlelikde, onuň nusgalaryny döredip we giňeldip bileris.</p><p>Ýöne Mixin-iň wezipesi täze klaslar <strong>döretmezden</strong> hereketi giňeltmekdir. Bu ýerde mixin açar sözi kömek edýär:</p><pre><br>mixin MyMixin implements MyAbstractMixin {<br>  void foo() {<br>    print(&#39;Mixed foo&#39;);<br>  }<br>  // Abstrakt &quot;bar&quot;-y durmuşa geçirmek indi hökmany däl, sebäbi mixin nusgasyny döredilip bilinmez.<br>  // Netijede, interfeýsiň ähli agzalarynyň durmuşa geçirilişini kepillendirmek hem hökmany däl.<br>}<br> <br>// A klasynyň interfeýsinde &quot;foo()&quot;, &quot;bar&quot; diýen iki metod goşuldy<br>// Olaryň amala aşyrylyşyny MyMixin garyndysyndan miras aldy<br>class A with MyMixin {<br>@override<br>  void bar() {<br>    // TODO: implement bar<br>  }<br>}</pre><p>We şeýle hem, Mixin-i haýsy klaslara goşup bolýandygyny çäklendirmek üçin on açar sözüni hem ulanyp bileris.</p><p>Ol Mixin arkaly superklasyň mirasdüşerlerini giňeltmäge rugsat berýär.</p><p>Munuň nähili işleýändigini has gowy düşünmek üçin, şu şemany gözden geçireliň:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*UZnmZBt_YJDfJRI5R6cRfw.png" /></figure><pre><br>class Super {<br>  final int a;<br>  <br>  Super(this.a);<br>  <br>  void foo() {<br>    print(&#39;Super foo&#39;);<br>  }<br>}<br> <br>mixin MyMixin on Super {<br>  void baz() {<br>    print(&#39;Mixed baz&#39;);<br>  }<br>}<br> <br>// Klas A - Super-iň mirasdüşeri we Mixin-i goşýar. MyMixin hem Super-iň mirasdüşeridir.<br>class A extends Super with MyMixin {<br>  A(super.a);<br>}<br> <br>// Emma indi klas B-ä MyMixin-i goşup bolmaýar.<br>class B with MyMixin {<br>  <br>}</pre><p>Ýokardaky mysalda MyMixin içinde foo() täzeden kesgitläp bileris, şonda dilde haýsy amalyň saýlanjakdygy belli däl.</p><p>Miras almakdaky indiki shemada has hem düşnüksiz bolýar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*rbxyAGT_tqHvZ32eqYNbUA.png" /></figure><p>Eger giňeldilýän klaslarda şol bir usulyň dürli amallary duş gelse, Dart soňky yglan edilen amaly dogry hasaplaýar, bu klasda bolan täzeden kesgitlenme ýa-da iň soňky goşulan Mixin bolsada tapawudy ýok.</p><p>Indi, Dart-da OOP gurallary bilen tanyş bolanyňyzdan soň, birnäçe meseleleri çözmäge synanyşyň.</p><p>Aşakdaky kodyň näme çagyrjakdygyny aýdyň:</p><pre>class P {<br>  String getMessage() =&gt; &#39;P&#39;;<br>}<br><br>mixin A {<br>  String getMessage() =&gt; &#39;A&#39;;<br>}<br><br>mixin B {<br>  String getMessage() =&gt; &#39;B&#39;;<br>}<br><br>class AB extends P with A, B {}<br><br>class BA extends P with B, A {}<br><br>void main() {<br>  String message = &#39;&#39;;<br>  <br>  AB ab = AB();<br>  <br>  message += ab.getMessage();<br>  <br>  BA ba = BA();<br>  <br>  message += ba.getMessage();<br>  <br>  print(message);<br>}</pre><blockquote>Jogap: BA</blockquote><p>Klaslaryň miras alnanda işleýşi ýaly, görnüşler (tipler) hem şonuň ýaly işleýär.</p><p>Aşakdaky kodyň näme görkezjekdigini düşünmäge synanyşyň:</p><pre>class P {<br>  String getMessage() =&gt; &#39;P&#39;;<br>}<br><br>mixin A {<br>  String getMessage() =&gt; &#39;A&#39;;<br>}<br><br>mixin B {<br>  String getMessage() =&gt; &#39;B&#39;;<br>}<br><br>class AB extends P with A, B {}<br><br>class BA extends P with B, A {}<br><br>void main() {<br>  AB ab = AB();<br>  print(ab is P);<br>  print(ab is A);<br>  print(ab is B);<br><br>  BA ba = BA();<br>  print(ba is P);<br>  print(ba is A);<br>  print(ba is B);<br>}</pre><blockquote>Jogap: 6 true</blockquote><h4>Bularyň jogabyny komentariýada ýazaýyň</h4><p><strong>A)</strong> Bu ýerde haýsy jübütler bir ýatkeşlik (pamat) öýjügine salgylanýar?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*PKaYLjVkynCHwHMw" /></figure><ol><li>A, D</li><li>B, C</li><li>A, C, D</li><li>B, C, D</li><li>A, B, C</li></ol><p><strong>B)</strong> Klas “A” üçin klas “B” interfeýs bolanda, klas “A” klas “B”-niň interfeýsini durmuşa geçirmeli. Bu ýagdaýda Dart dilinde näme açar sözüni ulanmaly?</p><ol><li>implemnets. class A with B</li><li>with. class A with B</li><li>extends. class A extends B</li></ol><p><strong>C)</strong> “A” klasy “B” klasy üçin interfeýs hökmünde ulanylyp bilinýärmi, eger “A” abstrakt däl klasyň bolsa?</p><ol><li>Bolup biler</li><li>Bolup bilmez</li></ol><p><strong>D)</strong> “A” klasy “B” klasynyň mirasdüşeri bolup bilermi, eger “B” abstrakt däl klasyň bolsa?</p><ol><li>Bolup biler</li><li>Bolup bilmez</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f99cd24940b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter-a Giriş Kursy]]></title>
            <link>https://medium.com/@meinnps/flutter-a-giri%C5%9F-kursy-3d4b28de3f32?source=rss-c93de175ef16------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d4b28de3f32</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutterashgabat]]></category>
            <category><![CDATA[community]]></category>
            <category><![CDATA[türkmençe]]></category>
            <dc:creator><![CDATA[Merdan Durdyyev]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 18:28:04 GMT</pubDate>
            <atom:updated>2024-04-20T06:45:19.479Z</atom:updated>
            <content:encoded><![CDATA[<h4>Giriş bölümi</h4><p><em>Flutter-de programmirlemäge başlajak bolýanlara hem-de eýýäm tejribesi bar deweloperlere gyzykly boljak türkmen dilinde taýýarlanan doly giriş kursy.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4ZWXFtFbhPl5qzF033bKA.png" /></figure><h3>Motiwasiýa</h3><p>Türkmenistanda Flutter-a bagyşlanan ilkinji “IT” jemgyýetini — <a href="https://www.meetup.com/flutter-ashgabat/?success=groupSetup"><strong>FlutterAshgabat</strong></a> jemgyýetini döretmek, mana Türkmenistandaky dil päsgelçilikleri we maglumatyň azlygy sebäpli kynçylyk çekýän ildeşlerimize goldaw bermek pikiri ylham berdi. Men Türkmenistanyň zehinli ýaşlaryny güýçlendirmek we öňe itmek üçin, seminarlar, tehniki söhbetdeşlikler we <a href="https://t.me/flutterashgabat"><strong>Telegram toparyny</strong></a> döretmäge başladym. Edil şul kursyň döremegi hem şol ylhamdan ugur alýar.</p><p>Bu tagallalar, tehnologiýa dünýäsinde Türkmenistanyň ýaşlarynyň biliminiň ösmegine, ýaş öwrenjilerimize goldaw bolar diýip umyt edýärin.</p><h3>Kurs Barada</h3><p>Bu kursy men özimden oýlap tapamok. Men bu kursy <a href="https://education.yandex.ru/handbook/flutter">Yandex Eeducation</a> portalyndan elýeterli maglumatlardan türkmen diline terjime edip, we öz tejribämden goşup taýýarladym.</p><p>Bu kurs wagtly-wagtynda täzelenip durlar diýip umyt edýärin. Bu bolsa siziň goldawyňyza we feedback-yňyza bagly.</p><h3>Duýduryş</h3><p>Türkmen dilinde tehniki inçe many berýän sözler az bolany sebäpli, bu kursy taýýarlan wagtymda köp sanly sözler iňlis we rus dilinden “türkmenleşdirilen” görnüşinde alyp goýdym. Ondan başga-da türkmen edebi dili tarapyndan ýalňyşlyklar bolmagy ahmal. Bu kurs döredilen wagtynda men ähli ünsümi Size many ýetirmekde jemledim. Şol sebäpli türkmen edebi dili söýüjileri meni bagyşlaň.</p><h3>Kursuň Mazmuny</h3><p>Bölümler boýunça Kurs şu aşakdaky yzygiderlilik boýunça gurnalan. (Egerde link ýok bolsa onda bu bölüm entäk doly taýýar däl we geljekde täzelener).</p><ol><li><a href="https://medium.com/@meinnps/flutter-pro%C3%BDekty%C5%88-gurlu%C5%9Fy-30e0fa7fdef1">Flutter: proýektiň gurluşy</a></li><li><a href="https://medium.com/@meinnps/flutter-pro%C3%BDekty%C5%88-baglylyklary-e88abec85b03">Flutter: proýektiň baglylyklary</a></li><li><a href="https://medium.com/@meinnps/prilo%C5%BEeni%C3%BDany%C5%88-resurslary-c65a02b4cee7">Priloženiýanyň resurslary</a></li><li><a href="https://medium.com/@meinnps/dart-bu-n%C3%A4me-a0bf1a032afa">Dart — Bu näme?</a></li><li><a href="https://medium.com/@meinnps/dart-oop-esaslary-8f99cd24940b">Dart: OOP</a></li><li>Dart: concurrency, isolates</li><li>Widgets: basics, Stateless, Stateful, Inherited</li><li>Widgets: Standard widgets</li><li>Widgets: Keys (Açarlar)</li><li>Widgets: Layout</li><li>Widgets: Formalar we Düwmeler</li><li>Networking: Tor bilen işlemek (HTTP, socket)</li><li>Project: Log-lar, Ýalňyşlyklary sazlamak (handling)</li><li>Project: Tema</li><li>Project: Navigation</li><li>Project: Dil bilen işlemek</li><li>Flutter: Freýmworkyň arhitekturasy. Sborkanyň görnüşleri</li></ol><p>Kursy halan bolsanyz (ýa-da teklipleriňiz we bellikleriňiz bar bolsa) täzelikleri göz astyna almak üçin <a href="http://www.linkedin.com/in/merdandt">LinkedIn</a>, <a href="https://www.meetup.com/flutter-ashgabat/?success=groupSetup">MeetUp</a>, <a href="https://t.me/flutterashgabat">Telegram</a> we Mediumyň özine yzarlap bilersiňiz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d4b28de3f32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart — Bu näme?]]></title>
            <link>https://medium.com/@meinnps/dart-bu-n%C3%A4me-a0bf1a032afa?source=rss-c93de175ef16------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0bf1a032afa</guid>
            <category><![CDATA[türkmençe]]></category>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Merdan Durdyyev]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 15:17:26 GMT</pubDate>
            <atom:updated>2024-04-20T04:07:24.525Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bölüm #4</h4><h3>Dart — Bu näme?</h3><p><em>Bu uly bölümde, Dart programmirleme diliniň taryhy, esasy aýratynlyklary we onuň JavaScript bilen deňeşdirilende nähili tapawutlanýandygy barada giňişleýin maglumat berilýär.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0tOPvBhDSQHXGt8ZikiFg.png" /></figure><p>Dart 2011-nji ýylda JavaScript-iň ornuny tutmak üçin döredi. Web programmirlemäge öwrenişenler Dart-da, JavaScript-e meňzeş mümkinçilikleri taparlar. Häzirki wagtda bu dil uzak ýol geçdi, null-safety, statiki tipizasiýa we Dart-VM goldawyny aldy.</p><p>Esasan, Dart Flutter framework bilen birlikde kross-platforma programmalar döretmekde ulanylýar. Mundan başga-da, serwer tarapyny ýazmakda Dart-dan peýdalanmak barada geljekki meýilnamalar (we eýýämden tayyarlanan bibliotekalar) bar.</p><p>Geliň onda bu makalada, Dart-yň, başga programirleme dillerden tapawudy, gyzykly mümkinçilikleri barada gürrüň açalyň.</p><blockquote>Ähli bölümleri gömek üçin <a href="https://medium.com/@meinnps/flutter-a-giri%C5%9F-kursy-3d4b28de3f32">şu ýere </a>salgylanyp bilersiňiz.</blockquote><h3>Ululuklar (Variables)</h3><p>Dart dili- köp sanly tiplere (iňlis <em>type</em>) eýedir. Bu tipleriň hemmesiniň sanawyny bär-de düşündirip oturmarys, olar hakynda diliň <a href="https://dart.dev/language/built-in-types">dokumentasiýasynda</a> giňişleýin okap bilersiňiz.</p><p>Ululuk döretmek beýleki dillerde näçe aňsat bolsa, şonça-da Dart dilinde- de aňsat. Mysal üçin:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd42272fb4f4d6c95823d7ddd73983a6/href">https://medium.com/media/fd42272fb4f4d6c95823d7ddd73983a6/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=bce487e47ee504101f4e724f6804f24f">bu ýerde</a> run edip bilersiňiz</blockquote><p>Ýokardaky kod setiri <em>String</em> görnüşli ululugy döredýär, oňa Hello, world! diýen bahany berýär we netijäni konsola çykaryar.</p><h4>var</h4><p>Dart diliniň tipleri çykarýan (type-inference) goldawy bar, şonuň üçin ululugyň görnüşini dessine görkezmek hökman däl. Munuň üçin var açar sözi ulanylýar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/231f01ef910dca05cd2504b0e3104e2c/href">https://medium.com/media/231f01ef910dca05cd2504b0e3104e2c/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=a331191ab005c6e8501253b09592c919">bu ýerde</a> run edip bilersiňiz</blockquote><h4>dynamic</h4><p>Dart diliniň dynamic diýen açar sözi bar, bu tipiň görnüşini barlamagy öçürýär. Eger ululugyň tipi diňe programma işläp başlanda belli bolýan bolsa we ony görkezip bolmaýan bolsa, dynamic ulanmak gerek. Indi öňki mysalymyzdaky var-y dynamic-e çalşalyň we kody biraz üýtgedeliň:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4a96bfd84257f20d16dc5f4887f26e2/href">https://medium.com/media/b4a96bfd84257f20d16dc5f4887f26e2/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=fcb0ccc30f8f1760567c7bb0387f2411">bu ýerde</a> run edip bilersiňiz</blockquote><blockquote>Bu ulanyşa seresaply çemeleşmeli, sebäbi bu ululugy ulananyňyzda bolýan islendik ýalňyşlyklary diňe programma işleýän wagtynda görüp bilersiňiz (kä wagt bu programmanyň bozulmagyna getirip bilýär).</blockquote><p>Belläp geçsek, var ulanylanda ululugyň tipi hemişe kompilýasiýa döwründe kesgitlenýär. Şeýlelikde, eger var bilen bellik edilen ululuk yglan edilende (döredilende) inisializasiýa edilmese ( inglis <em>initialize</em> başlangyç baha berilmese), onda beýle ululugyň “näbelli görnüşli” (ýagny null) bolýar, bu hem islendik görnüşdäki bahany (tipi) bermäge mümkinçilik berýär.</p><p>Aşakdaky mysalda bu herekete seredeliň:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01ada3a80e34652b8cfb5e1c78e894e1/href">https://medium.com/media/01ada3a80e34652b8cfb5e1c78e894e1/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=b9511bb508f481e9451c4cea6f794e41">bu ýerde</a> run edip bilersiňiz</blockquote><h4>final we const</h4><p>Ýokardaky mysallarda ululuklar yglan edilenden soň üýtgedilip we täzeden kesgitlenip bilner. Ýöne köplenç programmirlemede ululugy yglan edilenden soň üýtgetmezlik zerurlygy döreýär (üýtgetmäge gadagan). Mysal üçin, modeliň häsiýetlerini (propertilaryny) we şol sanda modeliň özüni üýtgetmezlik gowy tejribe hasaplanýar. Hem-de konstant obýektler bolsa öndürijilik (performance) meselede gowy täsir edýärler.</p><h4>final</h4><p>final açar sözi ululugy initialize edilenden soň gaýtadan kesgitlenmegi gadagan edýär.</p><blockquote><strong>Möhüm!</strong>. final bilen bellik edilen ululuk — bu konstanda (const) däl, ony diňe onuň bahasy initialize edilenden soň üýtgedilip bolanok.</blockquote><p>Indi geliň final ululugy döredeliň we onuň bahasyny üýtgetmäge synanyşalyň.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8d768d6b4570483ebb83e762c738531/href">https://medium.com/media/c8d768d6b4570483ebb83e762c738531/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=b5972aa3b26fa25514dca8494e2900ff">bu ýerde</a> run edip bilersiňiz</blockquote><p>Hakykatdan hem, a ululuk 5 bahasyny alar, we onuň bahasyny gaýtadan kesgitläp synanyşanyňyzda kompilýasiýa döwründe çykýan, kadadan çykma ýalňyşlygy (exception) bilen ýüzbe-ýüz bolarsyňyz.</p><p>Şeýle-de bolsa, final bilen kesgitlenen ululugyň berlen bahasynyň içki ýagdaýyny üýtgedip bolýar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/687780b6f46bbd6a12eb84a6ded366a4/href">https://medium.com/media/687780b6f46bbd6a12eb84a6ded366a4/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=c4ff4807f574c3a5dec9bccb387d6fc3">bu ýerde</a> run edip bilersiňiz</blockquote><h4>late</h4><p>late açar sözi ululugy yglan etmäge we onuň bahasyny derrew initialize etmezden (soňrak baha bermäge) mümkinçilik berýär.</p><p>Bu, non-nullable (null-howpsuzlygy barada aşakda gürrüň ederis) ululuklary yglan etmek islänimizde we onuň bahasyny soňrak kesgitläp bilmek üçin peýdalydyr.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d9b11c14185e27e7a83daf610a6d1c6/href">https://medium.com/media/2d9b11c14185e27e7a83daf610a6d1c6/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=441c0579bf4756e5566bb0388dc443ea">bu ýerde</a> run edip bilersiňiz</blockquote><h4>const</h4><p>const açar sözi konstantalary belläp geçýär. Olaryň bahalary kompilýasiýa döwründe eýýäm belli bolýar we olar işleýän wagtynda üýtgedilip ýa-da gaýtadan kesgitlenip bilinmezler. Üýtgetmäge gadaganlyk barada aşakda, konstant klas konstruktorlary bilen bilelikde gürrüň ederis.</p><p>Indi ýokardaky mysaly final-dan const-a öwreliň.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1eedecb2fe3612335b0e0f0b3fb53b4c/href">https://medium.com/media/1eedecb2fe3612335b0e0f0b3fb53b4c/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=ee69f854181868fdc412e90e3065b18c">bu ýerde</a> run edip bilersiňiz</blockquote><p>Netijede, kompilýasiýadan öň birnäçe ýalňyşlyk alarys:</p><ul><li>const ululugy initialize edilmän goýulyp bilinmez;</li><li>const ululugy gaýtadan kesgitlenip bilinmez;</li><li>const ululugynyň görnüşini üýtgetmek bolmaýar, bu diliň tip (type) <a href="https://dart.dev/guides/language/type-system">ulgamyndan</a> we öňki punktdan aýan bolýar.</li></ul><p>Indi bir mesele çözeliň.</p><h4>Mesele 1</h4><p>Iki sanaw (list) döredeliň, biri const we beýlekisi final, we olara täze elementler goşup synanyşalyň. Programma run etmän näme çykaryp berjegini aýdyň?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5ab05a19d07d4f8c56a3d22ffd3cfe6/href">https://medium.com/media/e5ab05a19d07d4f8c56a3d22ffd3cfe6/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=15ee985975150d9a7cffbe381b125dac">Bu ýerde</a> run edip bilersiňiz</blockquote><blockquote>Jogap</blockquote><blockquote>[3] Ýalňyşlyk — Unsupported operation</blockquote><h3>Kolleksiýalar</h3><p>Bu bölümde kolleksiýalar bilen işleşmägi öwreneris.</p><h4>Kolleksiýalary Yglan Etmek</h4><p>Zerur bolanda Dart, elementleriň tiplerini kolleksiýalarda görkezmäge mümkinçilik berýär.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c60bbf6fc4fbffe9feba20068d493ff0/href">https://medium.com/media/c60bbf6fc4fbffe9feba20068d493ff0/href</a></iframe><blockquote>Üns beriň: Tipleriň görnüşini görkezmek hökman däl bolsa-da, kompilýatoryň özi kolleksiýanyň elementlerine esaslanyp kesgitleýär.</blockquote><blockquote>Ol, sanaw list -iň içinde dynamic tipli ululuklaryň ýatandygyny kabul eder. Netijede, bu kod <a href="https://dart.dev/language/type-system">Type-Safety</a> (Görnüş Howpsuzlygy) kepillik geçmeýär.</blockquote><h4>Kolleksiýalary Açmak</h4><p>… operatory arkaly birnäçe kolleksiýalary bir kolleksiýa çenli açyp bilýäris.</p><p>If-else kolleksiýalaryň içinde kolleksiýalary yglan edenimizde, elementleriň goşulmagy üçin şertleri girizip bilýäris.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97264b22105b4d30de19d46322de6727/href">https://medium.com/media/97264b22105b4d30de19d46322de6727/href</a></iframe><h4>If-else Kolleksiýalaryň Içinde</h4><p>Kolleksiýalary yglan edenimizde, elementleriň goşulmagy üçin şertleri girizip bilýäris.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59ff20a7b02598b702795f02ec7eaeaa/href">https://medium.com/media/59ff20a7b02598b702795f02ec7eaeaa/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=205bb6da491ac03e3af456592d2fa195">bu ýerde</a> run edip bilersiňiz</blockquote><blockquote>condition false ýagdaýyna geçiriň we netijä serediň.</blockquote><h3>Enhanced enums (Kämilleşdirilen enumlar)</h3><p>Dart-da köp adamlara tanyş bolan enum görnüşleri bar, iň ýönekeý enum-y şeýle yglan etmek bolýar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab08d1a0846811de949b76030a205ac4/href">https://medium.com/media/ab08d1a0846811de949b76030a205ac4/href</a></iframe><p>Diliniň 2.17 wersiýasyndan başlap, <em>Enhanced enums</em> goşuldy.</p><p>Enhanced enum — öz meýdanlary, usullary we gurluşyjylary (konstruktor) bar bolan klasdyr, emma onda kesgitli çäklendirmeler bardyr:</p><ul><li>Klas meýdanlary final bolmaly, with arkaly goşulanlar hem şoňa girýär;</li><li>Hemme gurluşyjylar konstant bolmaly;</li><li>Hemme factory-gurluşyjylar (kostruktor) diňe yglan edilen Enum nusgalaryndan birini gaýtaryp biler;</li><li>index, hashCode ýa-da deňlik operator ==gaýtadan kesgitlenip (override) edilip bilinmez;</li><li>Klas agzalary üçin values adyny ulanmak bolmaýar, sebäbi bu standart enum-laryň API-syndan values getter-i bilen çaknyşýar;</li><li>Enum-yň başynda ähli mümkin bolan bahalary yglan etmeli. Şol bir wagtyň özünde, umumy bahalar bir bahadan az bolmaly däl.</li></ul><p>Enhanced enums köp ýagdaýlarda peýdaly bolup biler. Meselem, ikonkalar bilen işleşeňde:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/015797f29e6a54e5e6982d48fafaaa17/href">https://medium.com/media/015797f29e6a54e5e6982d48fafaaa17/href</a></iframe><h3>Ternar Operator</h3><p>Käbir ýagdaýlarda if-else artykmaç bolsa, şonda ternar (iňlis <em>Ternary</em>) operator kömek edýär:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffa19fc4d99404e0e35d88545a61d416/href">https://medium.com/media/ffa19fc4d99404e0e35d88545a61d416/href</a></iframe><h3>typedef</h3><p>Bu açar söz käbir tipleri (ýada olary gaýtarýan funksiýa) täzeden atlandyrmaga mümkinçilik berýär.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8722ca1a02992ddd74f951f20d054945/href">https://medium.com/media/8722ca1a02992ddd74f951f20d054945/href</a></iframe><h3>Setirler (Tekst, string)</h3><p>Dart tekst bilen amatly işlemek üçin giňişleýin gural toplumyny hödürleýär.</p><h4>Setir döretmek</h4><p>Dart-da setir döretmegiň birnäçe usuly bar:</p><ul><li>Ýekeje tirkegler arkaly &#39;string&#39;;</li><li>Goşa tirkegler arkaly &quot;string&quot;;</li><li>Üç esse tirkegler — ýekeje &#39;&#39;&#39;string&#39;&#39;&#39; ýa-da goşa &quot;&quot;&quot;string&quot;&quot;&quot;;</li><li>“Çig” setir hökmünde r&#39;string&#39;;</li><li>StringBuffer arkaly. Esasan ol setirler bilen manipulýasiýa üçin zerurdyr.</li></ul><p>Ilkinji usul — <a href="https://dart-lang.github.io/linter/lints/prefer_single_quotes.html">has ýörelgeli</a> hasaplanýar. Emma, bu beýlekileriň artykmaçdygyny aňlatmaýar. Indiki mysala seredeliň:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbabf4766270a7ac176502a9aa42ebd1/href">https://medium.com/media/fbabf4766270a7ac176502a9aa42ebd1/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=1292b76c9010288e1bb60e16ae7bf7da">bu ýerde</a> run edip bilersiňiz</blockquote><p>Şeýle seredeňde, “çig” setir mysaly (r’Hello, world! I like dollar$$$$’) düşnüksiz bolup biler. Şony aýdyňlaşdyralyň.</p><p>Meselem, $ — aýratyn belgilenen ýörite simwol we tirkegler (“”) bilen döredilen setirlerde, kompilýator ony interpolýasiýa simwoly hökmünde kabul eder we ony ahyrky setire goşmaz. Kompilýatora setirde ýörite simwollaryň ýokdugyny duýdurmak üçin, çig setirleri r&#39;…&#39; ulanmak zerur.</p><h4>Setirleriň Interpolýasiýasy</h4><p>Ýokarda bahalary çykarmak üçin $ simwolynyň ulanylandygyny görensiňiz. Bu, setirler bilen manipulýasiýa etmäge mümkinçilik berýän diliň mümkinçilikleriniň biridir.</p><p>Dart-da olary birleşdirmegiň üç usuly bar:</p><ul><li>Konkatenasiýa — iki setiri birleşdirip bir setir ýasamak;</li><li>Interpolýasiýa — hasaplanylýan bahalary setire goşmak;</li><li>StringBuffer. Indiki mysalda, şu üç usul bilen bir setiri almagyň ýollaryny görkezeliň:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bc735e83b13e9e1441e7bfff7a9894c/href">https://medium.com/media/3bc735e83b13e9e1441e7bfff7a9894c/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=f832e3657fd63df3f295bce609a23ea9">bu ýerde</a> run edip bilersiňiz</blockquote><p>Olaryň arasynda öndürijilikde (performance) uly tapawut ýok, şonuň üçin öz ýagdaýyňyzda has amatly bolanyny saýlamaklyk size bagly.</p><h4>Ýörite Simwollaryň üstünden aşmak</h4><p>Setirleriň döredilişi barada gürrüň edenimizde, çig setirde ähli ýörite simwollary “öçürip” bolýandygyny aýtdyk. Ýöne bu usul hemişe bize gerek däl, köplenç diňe setirdäki birnäçe simwollary ekranirowka etmek (üstünden aşmak) isleýäris.</p><p>Muny bize başarmakda ýene bir ýörite simwol kömek eder —\ .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/309b4d7cc035cce19a5596d38bfbf632/href">https://medium.com/media/309b4d7cc035cce19a5596d38bfbf632/href</a></iframe><h4>Regulýar Beýanlar (Regular Expressions)</h4><p>Dart-da regulýar beýanlar bilen işlemek üçin amatly mehanizm bar — RegExp.</p><p>Setirde world sözüniň bardygyny barlaýan mysaly getireliň:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16ba9d4a6d704e3d16e7f8b9f6e8ecc2/href">https://medium.com/media/16ba9d4a6d704e3d16e7f8b9f6e8ecc2/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=19e08c3c1b7af9ac2837ac15a9be1305">bu ýerde</a> run edip bilersiňiz</blockquote><p>Regulýar beýanlaryň güýji diňe şunda tamamlanmaýar. Jikme-jik maglumaty <a href="https://api.dart.dev/stable/2.16.1/dart-core/RegExp-class.html">dokumentasiýada</a> okap bilersiňiz.</p><h3>Giriş Modifikatorlary</h3><p>Beýleki dillerden tapawutlylykda, Dart-da giriş modifikatorlary ýok: public, private we protected.</p><p>Diňe bir ululygyň, funksiýanyň ýa-da klasyň görnüşini (görünmek mümkinçiligini, ýa-da elýeterligini) çäklendirmek mümkinçiligi bar, ol hem aşaky çyzyk _ arkaly bellenilýär.</p><blockquote>Bu, ululygyň ýa-da funksiýanyň yglan edilen faýlynyň daşynda (beýleki faýllardan) görnüşini hakykatdan çäklendirýär. Ýöne bir kadadan çykma bar — <a href="https://stackoverflow.com/questions/27763378/when-to-use-part-part-of-versus-import-export-in-dart">part of/part</a> notasiýalary. Biz olaryň üstünde köp durup geçmeris, ýöne olaryň bir faýly “böleklere” bölmäge mümkinçilik berýändigini (hamala olar bir faýl hökmünde göz öňünde tutmaga mümkinçilik berýändigini) aýdyp bileris.</blockquote><p>Meselem, bir klasyň meýdanlarynyň we metodlarynyň görnüşini çäklendirip bilýäris. Şeýlelik bilen, hiç kim olara yglan edilen faýlyň daşyndan giriş edip bilmez:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e76264e2f394f9639d941579de9df2c/href">https://medium.com/media/0e76264e2f394f9639d941579de9df2c/href</a></iframe><p>“Kontekstiň çäklerinden daşary görnüş” pikiri has gowy düşündirmek üçin, şu mysala seredeliň:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10abe19e61a3ad34ce581c210ece1892/href">https://medium.com/media/10abe19e61a3ad34ce581c210ece1892/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=b57941a1731aa0da329b3d911fcab145">bu ýerde</a> run edip bilersiňiz</blockquote><p>MyClass, main() we SecondClass bir faýlyň içinde yglan edilendir, şonuň üçin MyClass-yň hususy bölekleri faýlyň beýleki agzalaryna ýa-da kontekstine görünýär.</p><p>Eger biri başga bir faýldan _privateFunction() çagyrmaga synanyşsa, onda hiç zat başarmaz (görünmez, elýeterli bolmaz).</p><h3>null-safety (null-howpsuzlygy)</h3><p>Dart 2.12 bilen 2.19 aralygynda sound null-safety meýletin funksiýa hökmünde we 3-nji wersiýadan başlap hökmany bölek hökmünde goldaýar. Bu, deweloper NullReferenceExceptiondan, ýagny <a href="https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/">milliard dollarlyk ýalňyşlykdan</a> goraglydygyny aňladýar.</p><p>Dart-da null-safety amala aşyrylyşy barada <a href="https://dart.dev/null-safety">dokumentasiýada</a> has giňişleýin okap bilersiňiz.</p><p>Biz esaslarda ünsümizi jemläris.</p><p>Dart-da null-safety işjeňleşdirilende (aktiw edilende), ähli ululuklar göniden göni ? arkaly bellenilen bolmasa, null bahasyny alyp bilmez:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56c0127af3b4dcb0b2a05cd0fb92d1c2/href">https://medium.com/media/56c0127af3b4dcb0b2a05cd0fb92d1c2/href</a></iframe><p>Kompilýatoryň özi dewelopery yzygiderli yzarlaýar we mümkin bolan howply ýerleri duýdurýar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db6b75ae249186a43c62ed1d26c61588/href">https://medium.com/media/db6b75ae249186a43c62ed1d26c61588/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=4d4e9bd4b9df7b18d281db7429aa972c">bu ýerde</a> run edip bilersiňiz</blockquote><p>Eger kompilýator mümkin bolan howply ýerleri görse, kod asla kompilirlenmez (kompilýasiýa bolmaz).</p><p>Munuň birnäçe çözgütleri bar:</p><ul><li>Operatory ?.;</li><li>Operatory !.;</li><li>Kompilýatoryň tipiny hasaplamagy.</li></ul><h4>Operatory ? ýa-da null-aware (null-duýgur)</h4><p>Howply ýerlerde null-aware ulanyp bolýar. Ol kompilýatora şeýle diýýär: “Eger ululyk null däl bolsa, kody çagyr, ýogsam — null gaýtar”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50df7caa1f0af189cf6937299c22e59f/href">https://medium.com/media/50df7caa1f0af189cf6937299c22e59f/href</a></iframe><p>Kompilýator nägilelik bildirmegi (ýalňyşlary duýdurmagy) bes eder , we biz şuňa meňzeş netijäni alarys:</p><p>value-niň tipy — int?.</p><p>myClass null däl — value == 5.</p><p>myClass berilmedik ýa-da null — value == null</p><h4>! Operatory ýa-da force unwrap</h4><p>Bu operator kompilýatora şeýle diýýär: “Men bu bahanyň asla null bolup bilmejekdigine ynamly! Basyber!”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ce6de4ebb769ac6ee6293d0a6edc6a5/href">https://medium.com/media/7ce6de4ebb769ac6ee6293d0a6edc6a5/href</a></iframe><p>Kompilýator nägilelik bildirmegi bes eder, we biz şuňa meňzeş netijäni alarys:</p><p>value-niň görnüşi — int.</p><p>myClass null däl bellenen — value == 5.</p><p>myClass bellenmedik ýa-da null — kod iş wagtynda (run-time)NullReferenceException çykaryp biler.</p><blockquote><strong>Seresaply ulanmak möhümdir!</strong>. Force unwrap bizi null-safe koddan mahrum edýär, şonuň üçin ahyrynda mümkin bolan NullReferenceException ýalňyşlygy ünsden gaçyrmaklyk mümkinçiligi bar. ?. we ?? ulanmak has gowsy hasaplanýar.</blockquote><h4>Kompilýatoryň Tiplerini Hasaplamagy</h4><p>Biz nullable bahany ýerli (lokal) ululyga goýup (belläp) we şol ýerli ululygy null barlagyndan geçirip bileris.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d98111601b7ec9bce0b62ef878769a9/href">https://medium.com/media/3d98111601b7ec9bce0b62ef878769a9/href</a></iframe><p>Ahyrky netijede, aşakdaky zatlary alarys:</p><p>value görnüşi — int? ýa-da siziň ony yglan edeniňizde beren bahanyz (öňki dynamic);</p><p>Ilkinji element null däl — value == 5;</p><p>Ilkinji element null — value == null.</p><blockquote>Dart kolleksiýanyň ilkinji elementiniň bardygyny görmeýär. Bu, full sound safety sebäpli bolýar, kompilator diňe ýerli (lokal) ululuklar üçin hasaplama kepilini berip bilýär.</blockquote><blockquote>Jikme-jik maglumat üçin, <a href="https://dart.dev/null-safety">dokumentasiýa</a> ýa-da deweloperlar tarapyndan taýýarlanan <a href="https://www.youtube.com/watch?v=iYhOU9AuaFs&amp;ab_channel=Flutter">wideolara</a> ýüz tutup bilersiňiz.</blockquote><h3>Bonus</h3><p>Dart dilinde goşmaça birnäçe operatoryň bardygy aýratyn bellenmäge mynasyp:</p><p>?? — null operatory. Eger çep operatoryň bahasy null bolsa, kody sagdan-çepe çalşyp ýerine ýetirer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76a5e61dfbd7338091bc29e9e00cc631/href">https://medium.com/media/76a5e61dfbd7338091bc29e9e00cc631/href</a></iframe><p>?… — <em>null-spread</em> operatory. Diňe null däl kolleksiýalary açar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c28bd1b2d1bd2fa5b8d3b75757f9e30a/href">https://medium.com/media/c28bd1b2d1bd2fa5b8d3b75757f9e30a/href</a></iframe><p>??= — <em>null-aware assignment</em> (null barada habardar bellemek operatory). Diňe çep tarapdaky ululuk häzirki wagtda null bolsa, onda oňa baha bellär.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfd82a0f1549656d0988128582d4af95/href">https://medium.com/media/dfd82a0f1549656d0988128582d4af95/href</a></iframe><h3>Funksiýalar</h3><p>Dart, tendensiýalary yzarlap, funksiýalar bilen işlemek üçin uly gural toplumyny hödürleýär. Şu paragrafda ony gözden geçireliň.</p><h4>Funksiýanyň parametrleri</h4><p>Ähli görnüşdäki parametrleri şertli ýagdaýda aşakdaky diagrammada tertipläp bileris.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NdAhppJAUO6-cc7faX78Zg.png" /></figure><p>Indi tertibe görä.</p><p>positional (ýerine görä, ýerleşiş) — funksiýanyň parametrleri.</p><p>Olary hatda olaryň biri nullable (ýagny meýletin) bolsa-da hökmany berilmeli, :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c67f9016cb93ad2942a3cffbc10c5222/href">https://medium.com/media/c67f9016cb93ad2942a3cffbc10c5222/href</a></iframe><p>optional positional (meýletin ýerleşiş ) — çagyryşda berilmegi hökman däl parametrler. Ýöne şeýle parametrleriň non-nullable (boş geçirilmeýän) bolup, olara baha berilmedik bolmaly däldir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3551f073201e37d16f73d314aa838450/href">https://medium.com/media/3551f073201e37d16f73d314aa838450/href</a></iframe><p>named (atly) — çagyryşda uly sanly parametrleri bolan funksiýalary döretmäge we olary çagyryşda ýalňyşman bellemäge mümkinçilik berýän parametrler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/480be6968efab21a6d7d3c16447d009b/href">https://medium.com/media/480be6968efab21a6d7d3c16447d009b/href</a></iframe><p>Ýokarda berlen koduň içinde foo2 ýalňyş yglan edildi, sebäbi biz çagyryşda parametrleriň birini bermän goýup bileris. Şol bir wagtda, parametriň bahasy ýok bolup bilmez. Bu ýagdaýda, required açar sözi kömek edýär — ol çagyryşda atly parametri bermegi hökman edýär:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44876f2cc53a3f6f80ecc4717902f828/href">https://medium.com/media/44876f2cc53a3f6f80ecc4717902f828/href</a></iframe><p>Şeýle hem, positional parametrleri bilen bolşy ýaly, biz atly parametre üçin öňünden kesgitlenen bahany bellemek mümkinçiligine eýe bolup, şonda required talabynyň zerurlygyndan aýyrlyp, ony çagyryşda bermekden boýun gaçyryp bileris:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/718520e237320f7399ed8f5679294bee/href">https://medium.com/media/718520e237320f7399ed8f5679294bee/href</a></iframe><h3>Ýokary derejeli funksiýalar we ululuklar</h3><p>Bu düşünje köp atlar bilen tanalýar: global funksiýalar, ýokary derejeli funksiýalar, ýönekeýje funksiýalar.</p><p>Ygtybarlylyk üçin, biz olary aşakda üst derejeli funksiýalar diýip atlandyrarys.</p><p>Emma olaryň manysy birdir — olar we üýtgeýjiler her hili klas kontekstinden daşarda bolup biler.</p><p>Muňa iň ýönekeý mysal — main(). Bu diňe programma girýän nokat däl, eýsem üst derejeli funksiýadyr.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcc57e10d33a6ffe2f7be173ac0e3ed8/href">https://medium.com/media/dcc57e10d33a6ffe2f7be173ac0e3ed8/href</a></iframe><p>Giriş modifikatoryna we faýlda yglan edilen ýerine garamazdan, şeýle funksiýalar “bibliotekalaryň” ähli agzalaryna görnükli, özleri hem şeýle üst derejeli funksiýalary we üýtgeýjileri görüp bilerler.</p><p>Strelka funksiýalary bir setirde beýan etmäge mümkinçilik berýär:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3814497d1ffe2032e93fc6ec55f2d5b6/href">https://medium.com/media/3814497d1ffe2032e93fc6ec55f2d5b6/href</a></iframe><h3>Näbelli Funksiýa</h3><p>Dart-da funksional programmirleme ýörelgelerden anonim funksiýalar geçdi — olary Function tipindäki obýekt hökmünde kabul etmek bolýar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42646b9b317ae3d94b889b0cf3eea699/href">https://medium.com/media/42646b9b317ae3d94b889b0cf3eea699/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=7b5086c14ef308610fcebd3b790873d6">bu ýerde</a> run edip bilersiňiz</blockquote><p>Function tipinde call metody bar, onuň özi funksiýanyň çagyrylyşydyr. Eger funksiýa-üýtgeýji null bolup biler ýaly bolsa, ony ulanmak peýdaly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2a841b33fbc57f6cc5af151b1c82974/href">https://medium.com/media/f2a841b33fbc57f6cc5af151b1c82974/href</a></iframe><h4>Kaskad usuly bilen metody çagyrmak</h4><p>Bu funksiýa, bir üýtgeýjiniň metodlaryny yzygiderli çagyrmaga mümkinçilik berýär:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1cf55113a1e6b7c5909275bd0ac87ed/href">https://medium.com/media/f1cf55113a1e6b7c5909275bd0ac87ed/href</a></iframe><p>Kaskad çagyryşyň netijesi — başlangyç bahadyr. Muny has gowy düşündirmek üçin, aşakdaky mysaly göz öňünde tutalyň: toLowerCase() we toUpperCase() funksiýalary value-nyň üýtgedilen gymmatyny gaýtaryp berýärler, ýöne kaskad çagyryşda programma bu funksiýalaryň netijelerini çykarmaz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4da2f3db3a26bff9fdd955ece9f71e0c/href">https://medium.com/media/4da2f3db3a26bff9fdd955ece9f71e0c/href</a></iframe><h4>Zamýkaniýalar</h4><p>Bu mehanizm, başga bir funksiýanyň içinde yglan edilen anonim funksiýanyň ýokarydaky “kontekste” girmegine mümkinçilik berýär.</p><p>Bu biraz çylşyrymly ýaly görünýär, şonuň üçin zamýkaniýanyň mysalyna seredeliň:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f17e89b4c9e4df2fa882ea86272fcf0/href">https://medium.com/media/5f17e89b4c9e4df2fa882ea86272fcf0/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=1c4a5a4b8471c273bb90db9f223c211e">bu ýerde</a> run edip bilersiňiz</blockquote><p>Üst derejeli robotFactory funksiýasy RobotBuild tipindäki anonim funksiýany gaýtaryp berýär.</p><p>Özi anonim funksiýa, berlen name we robotFactory kontekstinden elýeterli model we specifications üýtgeýjileri bilen setir döredýär.</p><h4>Generatory</h4><p>Dart-da sinhron we asinhron generatory bar. Bu ýerde biz sinhron generatorlar hakynda gürrüň bereris, asinhron generatorlar bolsa biraz soň, <a href="https://education.yandex.ru/handbook/flutter/article/dart-concurrency-izolyaty">Dart Concurrency</a>, izolýatorlar paragrafynda serediler.</p><p>Meselem, sinhron generatorlar, köp sanly test maglumatlaryny döretmek isleseňiz peýdaly bolup biler:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a76846d7084211ba6f23da5df25496b/href">https://medium.com/media/2a76846d7084211ba6f23da5df25496b/href</a></iframe><blockquote><a href="https://dartpad.dev/?id=52668da9d56ad519971d1fda8eecd45e">bu ýerde</a> run edip bilersiňiz</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0bf1a032afa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Priloženiýanyň resurslary]]></title>
            <link>https://medium.com/@meinnps/prilo%C5%BEeni%C3%BDany%C5%88-resurslary-c65a02b4cee7?source=rss-c93de175ef16------2</link>
            <guid isPermaLink="false">https://medium.com/p/c65a02b4cee7</guid>
            <category><![CDATA[türkmen-dili]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Merdan Durdyyev]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 08:36:06 GMT</pubDate>
            <atom:updated>2024-04-20T04:08:11.111Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bölüm #3</h4><p><em>Bu makalada, Flutter proýektinde suratlar we şriftler ýaly resurslary (assets) nädip goşmalydygyny we dolandyrmalydygyny düşündirýär. Şeýle hem programma ikonkalary we başlangyç ekrany (Launch Screen)</em> <em>ýaly platforma mahsus amallar bilen işlemegi öz içine alýar.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcNH5-wggl5f_7biH2S2sA.png" /></figure><p>Flutter proýekti diňe kod faýllaryny öz içine almaýar, eýsem dürli serişde faýllaryny (resurslary), olara umumy <strong>asset</strong> (iňlisçe: <em>assets</em>) diýilýär. Köplenç ulanylýan <strong>assets</strong>-lara statiki maglumatlar, ýagny konfigurasiýa faýllary, ikonkolar (iňlisçe: <em>icon</em>) we şekiller (suratlar) girýärdir.</p><blockquote>Ähli bölümleri gömek üçin <a href="https://medium.com/@meinnps/flutter-a-giri%C5%9F-kursy-3d4b28de3f32">şu ýere </a>salgylanyp bilersiňiz.</blockquote><h3>Täze resursy (asset) nädip goşmaly?</h3><p>Täze resursy goşmak üçin ilki bilen, zerur faýly proýektiň papkasyna geçirmeli. Umumy kabul edilen çözgüt — assets atly papka döretmek we proýektiň ähli serişdelerini şonda saklamak. Mysal üçin assets/images, assets/fonts we ş.m. Soňra, pubspec.yaml faýlynda flutter: bölüminde resursyň (serişdäniň) ýerleşýän ýerini görkezmeli.</p><h4>Suratlar</h4><p>Meselem, pubspec.yaml proýekt faýlyna suraty nädip goşmalydygy barada mysal:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93858ff1c84cae76a28a35acac7fe5c5/href">https://medium.com/media/93858ff1c84cae76a28a35acac7fe5c5/href</a></iframe><p>Proýekte goşlandan soň, <a href="https://api.flutter.dev/flutter/painting/AssetImage-class.html">AssetImage</a> klasy ýa-da <a href="https://api.flutter.dev/flutter/widgets/Image/Image.asset.html">Image.asset</a> klass arkaly surata girmek mümkin. Meselem, assets/folder_name/asset_name.png ýolundaky suraty görkezmek üçin, Image.asset mysalyny şeýle döretmeli: Image.asset(‘assets/folder_name/asset_name.png’) .</p><h4><a href="https://en.wikipedia.org/wiki/Pixel">Pixel</a> ratio gatnaşygyna bagly suratlar</h4><p>Enjamyň öz piksel gatnaşygyna (iňlisçe: pixel ratio) laýyk gelýän razreşeniýaly (<a href="https://www.gsmarena.com/glossary.php3?term=resolution">resolution</a>) suratlary Flutter ýüklemäge ukyplydyr.</p><blockquote><strong>Pixel gatnaşygy diýmek näme?</strong></blockquote><blockquote>Bu enjamyň fiziki pikselleriniň sanynyň we programma bilen işleýän logiki pikselleriniň sanynyň arasyndaky gatnaşyk.</blockquote><blockquote>Mobil enjamlarda dürli-dürli fiziki ekran resolution ulanylýar. Ýokary resolution enjamlar ekranlarynda köp sanly fiziki pikselleri öz içine alýar, bu bolsa suratlary has ýokary aýdyňlyk we jikme-jiklik bilen görkezmäge mümkinçilik berýär.</blockquote><blockquote>Şol bir wagtyň özünde, programma öndürijilikde logiki resolution köp ulanylýar, ol logiki piksellerde ölçenilýär.</blockquote><blockquote><strong>Logiki piksel </strong>— programma interfeýsini döretmek üçin ulanylýan abstrakt ölçeg birliği.</blockquote><blockquote>Enjamyň piksel koeffisiýenti enjamyň ekranynyň fiziki çözgütine laýyklaşdyrmaga mümkinçilik berýär. Ol programmada her bir logiki pikseli görkezmek üçin näçe fiziki pikselden peýdalanyljakdygyny kesgitleýär. Eger enjam 1.0-dan tapawutly piksel koeffisiýentli bolsa, her bir logiki piksel üçin birnäçe fiziki piksel ulanylyp, has aýdyň we jikme-jik surat görkezilip bilner.</blockquote><blockquote>Meselem, pixel gatnaşygy 2.0 bolan enjam her bir logiki pikseli görkezmek üçin dört fiziki pikseli ulanar (iki hatar we iki setir).</blockquote><p>AssetImage klasy awtomatiki usulda ulanjak suraty, enjamyň piksel gatnaşygynyň iň laýyk gelýän resolution bilen deňeşdirer.</p><p>Awtomatiki deňeşdirmäniň işlemegi üçin, surat assets-lary kesgitlenen katalog strukturasyna laýyklykda gurnalmaly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d45b4c0cc1d5319cd24a039c57369ca9/href">https://medium.com/media/d45b4c0cc1d5319cd24a039c57369ca9/href</a></iframe><p>M we N — suratyň resolution-a laýyk gelýän sanly identifikatorlar. Olar enjamyň piksel gatnaşygynyna niýetlenen suratlary görkezýäler. Bu mysalda, icon.png esasy resurs (asset) hasaplanýar, Mx/icon.png we Nx/icon.png bolsa wariantlardyr. Esasy resursy 1.0 resolution-a gabat gelýändigi hasap edilýär.</p><p>my_icon.png diýlip atlandyrylan suratyň resursyny nädip kataloglara bölmek barada mysal:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cced76faa0151017fc18a04e691c6c1e/href">https://medium.com/media/cced76faa0151017fc18a04e691c6c1e/href</a></iframe><p>1.8 piksel koeffisiýentli enjamlarda 2.0x/my_icon.png resurslary saýlanylar. 2.7 piksel koeffisiýentli enjam üçin 3.0x/my_icon.png serişdesi saýlanylar.</p><p>Resolution-a bagly serişdeler bilen işleýän wagtyňyz, diňe esasy resurs ýa-da onuň ene-ata (roditel, parent) katalogyny görkezmeli. Aşakdaky mysalda my_icon üçin iki wariant görkezilýär:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f756d2f55609b152583db84a5c740bfa/href">https://medium.com/media/f756d2f55609b152583db84a5c740bfa/href</a></iframe><h3>Baglylyklardan (paketlardan) suratlary ulanmak</h3><p>Eger surat import edilýän paketde ýerleşdirilen bolsa, onda ony ulanmak üçin AssetImage-de package meýdany görkezilmeli.</p><p>Meselem, eger my_icons paketi şeýle gurluşa eýe bolsa —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e41495019c0a3a46c8bada5603f4681f/href">https://medium.com/media/e41495019c0a3a46c8bada5603f4681f/href</a></iframe><p>onda suraty şeýle ýüklemek bolýar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e7e987b539a3e95024b52f03c09fec3/href">https://medium.com/media/4e7e987b539a3e95024b52f03c09fec3/href</a></iframe><h3>Şriftler</h3><p>Şriftleri goşmak üçin, .ttc, .ttf ýa-da .otf formatlaryndaky faýllary, olar şrift konfigurasiýasyny saklaýar, we olary fonts: meýdanynda görkezmeli:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0e5b7ba3b519520c821e5b14813ec82/href">https://medium.com/media/b0e5b7ba3b519520c821e5b14813ec82/href</a></iframe><p>family parametri şrift maşgalasyny kesgitleýär. Bu parametr <a href="https://api.flutter.dev/flutter/painting/TextStyle-class.html">TextStyle</a> klasynyň <a href="https://api.flutter.dev/flutter/painting/TextStyle/fontFamily.html">fontFamily</a> häsiýetinde (swoýstwasynda) ulanylýar.</p><p>asset — bu pubspec.yaml faýlyna göni baglanyşykly şrifta çenli ýolydyr. Ýokardaky mysalda, Raleway-Regular.ttf faýly assets/fonts bukjasynda ýerleşýär, ol pubspec.yaml faýly bilen deň derejede ýerleşýär.</p><p>Bir şrift birnäçe faýllara dürli şrift stili bilen salgylanyp biler:</p><ul><li>weight şriftyň dokunlygyny kesgitleýär, bu 100-den 900-e çenli 100 birlikli (ädimi 100 bolan, 200, 300, 400) sanly bir bahadyr. Bu bahalar <a href="https://api.flutter.dev/flutter/dart-ui/FontWeight-class.html">FontWeight</a>-e gabat gelýär we <a href="https://api.flutter.dev/flutter/painting/TextStyle-class.html">TextStyle</a> klasynyň fontWeight häsiýetinde ulanylýar. Meselem, RobotoMono-Bold ulanmak üçin FontWeight.w700 görkezmeli</li><li>style şriftiň kontury — <em>italic</em> ýa-da adaty. Bu bahalar TextStyle klasynyň fontStyle meýdanyna gabat gelýär we <a href="https://api.flutter.dev/flutter/painting/TextStyle-class.html">FontStyle</a> obýekti bilen kesgitlenýär. Meselem, Raleway-Italic ulanmak üçin fontStyle-i FontStyle.italic-e deňlemek gerek.</li></ul><h3>Tekst</h3><p>Tekst serişdeleri — mysal üçin, .txt ýa-da .json faýllary bilen işlemek üçin <a href="https://api.flutter.dev/flutter/services/AssetBundle-class.html">AssetBundle</a> ulanylýar.</p><p>AssetBundle bilen işlemegiň iki usuly bar:</p><h4>rootBundle statiki obýektini ulanmak</h4><p>package:flutter/services.dart-dan import edilen <a href="https://api.flutter.dev/flutter/services/rootBundle.html#:~:text=The%20rootBundle%20contains%20the%20resources,application%20when%20it%20was%20built.">rootBundle</a> obýektyndan.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c5189db6b72f6acc96c7004c6940274/href">https://medium.com/media/2c5189db6b72f6acc96c7004c6940274/href</a></iframe><h4>DefaultAssetBundle ulanmak</h4><p>Nesilleri üçin esasy <a href="https://api.flutter.dev/flutter/widgets/DefaultAssetBundle-class.html#:~:text=A%20widget%20that%20determines%20the,no%20bundle%20is%20specified%20explicitly.">DefaultAssetBundle</a> kesgitleýän widget.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b3f4b5da282ea0256e254346ac10ded/href">https://medium.com/media/7b3f4b5da282ea0256e254346ac10ded/href</a></iframe><h3>Platforma bagly assetlar (resurslar)</h3><h4>Programmanyň ikonkasy</h4><p>Flutter programmasynyň ikonkany (icon) täzelemek üçin Android ýa-da iOS üçin edil natiw programmalar üçin ikonkany täzeläniň ýaly hereketler amala aşyrylýar.</p><h4>Android</h4><p>Flutter proýektiniň kök (düýb, root) bukjasynda geçiň we android/app/src/main/res bukja giriň. <a href="https://developer.android.com/reference/android/graphics/Bitmap">bitmap</a> formatly dürli asset bukjalary, mysal üçin mipmap-hdpi, eýýäm ic_launcher.png atly suratlary öz içine alýar. <a href="https://developer.android.com/training/multiscreen/screendensities">Android Developer Guide</a>-da görkezilen her bir ekranyň dykyzlygy üçin maslahat berilýän ölçeglerine laýykda olary islän suratyňyz bilen çalyşyň.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/0*MlZBtmztbcOUuqax.png" /></figure><h4>iOS</h4><p>Flutter proýektiňiziň kök bukjasynyň ios/Runner-e geçiň. Assets.xcassets/AppIcon.appiconset bukjasynda eýýäm boş ýer tutujy suratlary öz içine alýar. Olary <a href="https://developer.android.com/training/multiscreen/screendensities">Apple Human Interface Guidelines</a>-däki maslahatlara laýyklykda, faýllaryň atlaryna degişli ölçegdäki suratlar bilen çalyşyň, asyl faýl atlaryny saklaň.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/0*sAc2s_feuHx5NsDf.png" /></figure><h3>Başlangyç Ekrany (Launch Screen)</h3><p>Launch Screen— bu ulanyjynyň ilkinji görýän ekranydyr. Ol programma işledilenden soň peýda bolýar we Flutter ilkinji kadr çekýänçä (render edýänçä) saklanýar. Ol natiw programmalardaky ýaly şol bir usulda täzelener.</p><h4>Android</h4><p>Programmada başlangyç ekrany goşmak üçin android/app/src/main bukjasyna geçmeli. res/drawable/launch_background.xml faýlynda <a href="https://developer.android.com/guide/topics/resources/drawable-resource#LayerList">layer list drawable</a> XML faýlyny başlangyç ekrany üýtgetmek üçin ulanyp bolýar.</p><p>Goşmaça maglumatlar resmi (ofisial) <a href="https://docs.flutter.dev/platform-integration/android/splash-screen">dokumentasiýada</a> tapylýar.</p><h4>iOS</h4><p>Ekranyň merkezine surat goşmak üçin, ios/Runner/Assets.xcassets/LaunchImage.imageset bukjasyna LaunchImage.png, LaunchImage@2x.png, we LaunchImage@3x.png atly suratlary goýmaly. Başga atly faýllary ulanmak üçin ios/Runner-däki Contents.json faýlyny täzelemeli.</p><p>Şeýle hem Xcode-da başlangyç ekrany şablonyny ios/Runner.xcworkspace açmak arkaly doly sazlap bolýar. Proýekt nawigatornda Runner/Runner-a geçip, Assets.xcassets açmak ýa-da LaunchScreen.storyboard faýlynda <strong>Interface Builder</strong> ulanmak arkaly başlangyç ekrany sazlap bolýar.</p><p>Goşmaça maglumatlar resmi <a href="https://docs.flutter.dev/platform-integration/ios/launch-screen">dokumentasiýada</a> okap bolýar.</p><p>Bu tema boýunça Flutter dokumentasiýada <a href="https://docs.flutter.dev/ui/assets">Assets &amp; Media</a> bölümi okamaga peýdaly hem bolar.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c65a02b4cee7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: proýektiň baglylyklary]]></title>
            <link>https://medium.com/@meinnps/flutter-pro%C3%BDekty%C5%88-baglylyklary-e88abec85b03?source=rss-c93de175ef16------2</link>
            <guid isPermaLink="false">https://medium.com/p/e88abec85b03</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[turkmen-dili]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dependencies]]></category>
            <dc:creator><![CDATA[Merdan Durdyyev]]></dc:creator>
            <pubDate>Tue, 16 Jan 2024 16:42:30 GMT</pubDate>
            <atom:updated>2024-04-20T04:08:41.392Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bölüm #2</h4><p><em>Bu bölümde biz proýektäki baglylyklary</em> (<em>ýagny</em> <em>dependency, зависимости) barada içgin gürrüň ederis we tanyşarys.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBErngZsDpQEdurxbRMrdQ.png" /></figure><p>Flutter taslamasynda bibliotekalar priloženiýany işläp taýýarlamakda ähmiýetli orny eýeleýär. Işläp taýýarlaýjylar (deweloperlar) tarapyndan priloženiýany işläp taýýarlamak prosesini ýeňilleşdirmek we tizleşdirmek üçin, öňünden kesgitlenen funksiýalaryň, klaslaryň we komponentleriň jemini bibliotekalarda jemlenýär. Geliň indi bibliotekalary Flutter-da nädip ulanmalydygyny we dolandyrmalydygyna seredeliň.</p><blockquote>Ähli bölümleri gömek üçin <a href="https://medium.com/@meinnps/flutter-a-giri%C5%9F-kursy-3d4b28de3f32">şu ýere </a>salgylanyp bilersiňiz.</blockquote><h3>Bibliotekalaryň görnüşleri</h3><p>Bibliotekalar iki görnüşde bolýar:</p><ul><li>Paketlar (iňlis dili — <a href="https://docs.flutter.dev/development/packages-and-plugins/developing-packages#types">packages</a>) — olaryň mazmunynda diňe Flutter/Dart dilinde ýazylan kodlar bar</li><li>Plaginler (iňlis dili — <a href="https://docs.flutter.dev/development/packages-and-plugins/developing-packages#types">plugins</a>) — Dart we Flutterden başga olaryň mazmunynda platforma-spetsifiki kodlar bar (platforma degişli, Android, iOS we ş.m.), şeýle hem oňa — natiw kod hem atlandyrylýar (natiw — asyl öz platfoma degişli kod meselem Kotlin we Java Android üçin natiw kodyr). Flutteriň birnäçe platformada ýazmak mümkinçiligine garamazdan, käbir ýagdaýlarda diňe bir plartforma degişlililikde mümkin bolan spetsifiki funksionaly ulanylmagy zerur bolup biler. Meselem, operasion ulgamlaryň notifikasiýa integrasiýasy, ustroýstwanyň, enjamyň funksiýalaryny (kamera, batareýka, datçiklere, bluetooth we başgalara) ulanmak mümkinçiligi ýa-da diňe kesgitli bir platformada işleýän beýleki priloženiýalar bilen özarabaglanşygy — bularyň ählisi ýokarky kegsitlemä mysal bolup biler.</li></ul><h3>pub.dev</h3><p>Haçanda Flutter-daky paketlar barada aýdylanda ilkinji nobatda meşhur — <a href="http://pub.dev/">pub.dev</a><strong> </strong>resursy göz öňüne gelýär. Bu saýt — Dart we Flutter bibliotekalaryň resmi repozitoriýasydyr, ol deweloperlara birnäçe paketlary we plaginlary ulanma mümkinçiligini döredýär we ol bibliotekalar diňe Flutter/Dart taslamalary üçin ulanylyp bilner. Onda Dart we Flutteriň jemgyýeti tarapyndan bilelikde döredilen bibliotekalary, şeýle hem Google tarapyndan goldanylýan we işläp taýýarlanylýan bibliotekalar ýerleşdirilen.</p><p>Her bir bibliotekanyň sahypasy onuň atlandyrylyşyny, aktual wersiýasyny, çap edilen senesini, awtoryny we bu biblioteka ulanylmagynda peýdaly we zerur beýleki maglumatlary özünde jemleýär. Aşakda 14.7.10 wersiýasyndaky <a href="https://pub.dev/packages/firebase_messaging">firebase_messaging</a> bibliotekanyň sahypalarynyň skrinşody görkezilen. Ony <a href="https://docs.flutter.dev/packages-and-plugins/favorites">Flutter Favorite</a> ýörite nyşan (badge) bilen sylaglanandygyny hem görmek bolar</p><blockquote>Flutter Favorite — bu bibliotekanyň ýokary hilliligini subut edýän nyşandyr</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Np6J2LPjotUuYHN7gC7bow.png" /></figure><p><a href="http://pub.dev/">pub.dev</a> bilen işlemek üçin, biz birinji bölümde tanyşan, pub enjamyny (instrumendy, tool) ulanyp bilers.</p><h3>Baglylyklar</h3><p>Proýekt baglylyklary goşmak üçin pubspec.yaml faýlynda dependencies meýdany ulanylýar, onuň aşagynda pakedyň ady, onuň çeşmesiniň we wersiýasynyň ady görkezilýär (saýlanan çeşmäniň görnüşi üçin zerur bolsa görkezilýär). Alynýan baglylyklaryň çeşmeleriň nukdaýnazaryndan seredente <strong>dört görnüşde</strong> bolýar.</p><h4><a href="http://pub.dev/"><strong>pub.dev </strong></a><strong>— dan gelýän baglylyklar</strong></h4><p>Dart we Flutter üçin niýetlenen bibliotekalaryň resmi köpçülikleýin repozitoriýasynyň <a href="https://pub.dev/">pub.dev</a> salgyda çap (publikasiýa) edilen baglylygy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af7143d7396807a48e46e222cb3a74f5/href">https://medium.com/media/af7143d7396807a48e46e222cb3a74f5/href</a></iframe><h4><a href="https://dart.dev/tools/pub/dependencies#git-packages"><strong>Git-baglylyk</strong></a></h4><p>Git-repozitorivadan gelip çykan baglylyk (mysal üçin öz <a href="https://github.com/">GitHub</a> ýa-da <a href="https://about.gitlab.com/">GitLab</a> repozitoriýaňyzda).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6c806581f3ec6815b16bf29fccbaf80/href">https://medium.com/media/d6c806581f3ec6815b16bf29fccbaf80/href</a></iframe><p>Salgydan (link, ssylka) başga biz ref we path parametrlerini görkezip bilers:</p><ul><li>ref — baglylygy Git repositorisyndan master ýa-da main şahamçadan (branch, wetkada) çekip çykarmaz ýaly (ýüklemez ýaly), identifikatora baglylykda kommityň (<a href="https://git-scm.com/docs/git-commit">git-commit</a>) belgisini (nomeriny), wetkanyň ýa-da <a href="https://git-scm.com/book/en/v2/Git-Basics-Tagging">tag</a>-yň adyny görkezmek üçin hyzmat edýär.</li><li>path — egere bukja taslamanyň kökinde (root) ýerleşmedik ýagdaýynda biblioteka çenli ugry (ýoly) görkezmäge mümkinçilik berýär.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edbe3f7cd3c09042ae675ca6a0a1eea8/href">https://medium.com/media/edbe3f7cd3c09042ae675ca6a0a1eea8/href</a></iframe><h4><a href="https://academy.yandex.ru/handbook/flutter/article/flutter-struktura-proekta">Lokal</a> (ýerli) baglylyk</h4><p>Ýerli, faýllar ulgamynda ýerleşen (öz komputeriňde birýerde, ýa-da proýektyň bukjasynyň içinde birýerde), baglylyklary lokal ýagdaýda gurnap (ýükläp) bolýär. Munuň üçin ol baglylyga çenli doly ýa-da <a href="https://en.wikipedia.org/wiki/Path_(computing)#:~:text=A%20path%20(or%20filepath%2C%20file,delimiting%20character%2C%20represent%20each%20directory.">otnositel</a> (relative) ýolyny jikme-jik beýan etmek gerek .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c38cfcb528fbdff565dde5b8ab7f086/href">https://medium.com/media/5c38cfcb528fbdff565dde5b8ab7f086/href</a></iframe><h4><a href="https://dart.dev/tools/pub/dependencies#hosted-packages"><strong>Hosted</strong></a><strong>-baglylygy</strong></h4><p>pub.dev ýaly bir resurs emma siziň öz serweriňizde.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae190814d5892023cc55749387635d15/href">https://medium.com/media/ae190814d5892023cc55749387635d15/href</a></iframe><p>Bular ýaly bibliotekalaryň ýapyk (private) saklawhanany (storage, hranilishe) unpub ýaly ýörite paketyň kömegi bilen döredip bolýar.</p><blockquote>unpub barada <a href="https://pub.dev/packages/unpub">şu ýerde</a> okap bilersiňiz.</blockquote><h3>Baglylyklary wersiýa bölmek (wersiýalaşdyrmak)</h3><p><a href="https://medium.com/@meinnps/flutter-pro%C3%BDekty%C5%88-gurlu%C5%9Fy-30e0fa7fdef1">Bölüm #1</a>-den bilşimiz ýaly, bibliotekalar pubspeс.yaml faýlynda version atly ýörite setiriň bolmagy zerurdyr.</p><p>Bibliotekalaryň <a href="https://dart.dev/tools/pub/versioning">wersiýasyny</a> Dart-da kesgitlemek üçin nokatlar bilen bölünen 3 sandan düzülen <a href="https://semver.org/lang/ru/">semantiki wersionirlenme ulanylýar</a> (iňlis. semantic versioning), ýagny major.minor.patch. Sanlaryň her biri bibliotekada dürli üýtgeşmeleri aňladýar:</p><ul><li>major (baş esasy wersiýa) — API-daky üýtgeşmeler häzirki programmanyň wersiýasy bilen işlemäge mümkinçilik berenok (breaking changes — kritiki üýtgeşmeler). Bular ýaly üýtgeşmeler bibliotekanyň öňki wersiýasyny ulanýanlara täsirini ýetirýär we işlemegi dowam eder ýaly, ol kodda, üýtgeşmeleri ýa-da modifikasiýalary talap edip bilýär;</li><li>minor — API-ky bar bolan täze funksionallygyň goşulmagy bilen öňli wersiýany ulanýanlara gapma garşylyklara (breaking changes) getirmeýär;</li><li>patch — API täsir etmeýän, pakedyň näsazlyklary (baglary) düzetmek.</li></ul><p>Dart — da baglylyklaryň wersiýasynyň çäklendirmelerini görkezmek üçin, wersiýalaşdyrma operatorlaryny ulanmak bolar. Konstreýntlar (iňlis <em>constraints</em>) diýip hem atlandyrylýan wersiýalaşdyrma operatorlary öz içinde şu aşaakdakylary jemleýär:</p><ul><li>any — taslamanyň baglylygyň ähli wersiýalary bilen gabat gelýänligini görkezmek üçin ulanylýar. Bu bolsa, taslamany gurnama pursadynda mümkin bolan (el ýeterli) baglylygyň islendik wersiýasyny ulanmak bolýandygyny aňladýar;</li><li>x,y,z — x,y,z wersiýasy gurnalýar, bu ýerde x — major, y — minor, z — bolsa path;</li><li>&gt; x,y,z — şu buýurmada görkezilenlerden x,y,z-dan ýokary, maksimal ýagdaýda mümkin (elýeter) bolan wersiýalar gurnalar;</li><li>&gt;= x,y,z — şu buýurmada ýokarda görkezilenlerden x,y,z-da deň ýa-da ýokary, maksimal ýagdaýda mümkin (elýeter) bolan wersiýalar gurnalar;</li><li>&lt; x,y,z — şu buýurmada ýokarda görkezilenlerden x,y,z — den pes, maksimal ýagdaýda mümkin (elýeter) bolan wersiýalar gurnalar;</li><li>&lt;= x,y,z — şu buýurmada ýokarda görkezilenlerden x,y,z-da deň ýa-da pes, maksimal ýagdaýda mümkin (elýeter) bolan wersiýalar gurnalar;</li><li>^x,y,z — bu buýurma şu ýagdaýda düşünmeli, ýagny &gt;= x,y,z &lt; (x +1).0.0 ekwiwalentdir ýagny “<em>Iň ýokarky, ýöne major wersiýasy geçmeýän bir wersiýa isleýärin” </em>diýmek bolýar. Meselem: ^1.2.3 bu diýmek &gt;=1.2.3 &lt;2.0.0 deňdir. Emma major 0 bolsa onda bu düzgün braz üýtgeýär. Meselem: ^0.1.2 bu &gt;=0.1.2 &lt; 0.2.0 deňdir. Eger major nola deň bolsa, onda biblioteka entek <a href="https://en.wikipedia.org/wiki/Software_release_life_cycle">beta</a> wersiýada bolup, islendik minor üýtgeşmeleri <em>breaking changes </em>bolup biler.</li></ul><p>Semantiki wersiýalaşdyrma barada resmi <a href="https://dart.dev/tools/pub/versioning#semantic-versions">dokumentasiýada</a> tanşyp bolar. Şol dokumentasiýanyň soňky abzasynda nola deň bolan major wersiýalary barada beýan edilen.</p><p>Şeýle hem, şu kombinirlemäniň kömegi bilen wersiýanyň diapazonyny görkezip bolar &lt;,&lt;=, &gt;,&gt;=. Meselem: &gt;=1.12.8 &lt;=3.0.0 şu konstruksiýa 1.12.8 — den başlap 3.0.0 çenli wersiýany gurnamagy meýilleşdirýänimizi aňladýar.</p><h4>Maksimal mümkin (elýeter) bolan wersiýa nämäni aňladýar?</h4><p>Bu ýagdaýa düşünmek üçin baglylyklary bölmegiň ýene bir görnüşini bilmegimiz gerek: <strong>göni</strong>, <strong>tranzitiw</strong> we <strong>şered</strong> (iňlis <em>shared, </em>bilelikdäki ulanylýan).</p><p>Ine şular ýaly ýagdaýa <strong>gönimel baglylyk</strong> diýilýär, şeýdip hem biz <strong>A</strong> Pakedy biziň priloženiýamyza goşýarys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*2lPsrF4rJaS-7V0CPKyntA.png" /></figure><p><strong>Tranzitiw</strong> (iňlis dili <em>transitive</em>) baglylyk bolsa baglylyk hökmünde gurnan pakedyň içinden çykarylýar. Bu baglylyk biziň baglylygmyzyň baglylygy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z4cCCOyqaITZEkvThenD9Q.png" /></figure><p><strong>Şered</strong> baglylyk — biz we biziň bir ulanýan pakedymyz çekýän şol bir baglylygydyr.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*KJ4sXcJxjfS3KOZQMVzxmg.png" /></figure><p>Maksimal mümkin bolan wersiýa — bu gönimel, tranzit we şared baglylyklaryň çekilende emele gelýän diapazony <strong>kanagatlandyrýan wersiýadyr.</strong> Nusga üçin ýokardaky suratda biz B pakedy hem ^1.0.0 wersiýada hem şol sanda ^2.0.0 wersiýany gurnamaga synanşýarys. Bular ýaly ýagdaýa konflikt diýip atlandyrylýar, we flutter pub get buýurmasynda konsolida aşakdaky habarlar ýüze çykar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/967cbdc67760cb12436e5ecffc13cad4/href">https://medium.com/media/967cbdc67760cb12436e5ecffc13cad4/href</a></iframe><p>Bu meseläni çözmegiň 3 sany usuly bar:</p><ol><li><strong>B</strong> <strong>Pakedyn</strong> wersiaýsyny biziň priloženiýamyzda ^2.0.0 wersiýa çalşyrmaly.</li><li><strong>B</strong> <strong>Pakedyn</strong> ^1.0.0 wersiýasyny ulanýan, <strong>A Pakedyň</strong> wersiýasyny gurnamaly (şol A Pakedyň wersiýada B Paketdyň wersiýasy ^1.0.0 )</li><li><a href="https://dart.dev/tools/pub/dependencies#dependency-overrides">dependency_overrides</a> parametryň kömegi bilen baglylygy täzeden kesgitlemeli. Adyndan belli bolşy ýaly biz bibliotekamyzy gaýtadan kesgitleýäris. dependency_overrides parametyrynda pakedyň, wersiýany we çeşmesini görkezip bolýar we bu ýagdaýda pub bu aňlatmalary dependencies –da görkezilýän ýa-da tranzitiw arkaly çekilýän wersiýalary ulanman, siziň bellän wersiýaňyzy ulanar.</li></ol><p>Biziň ýokardaky ýagdaýymyzda <strong>A Pakedy</strong> tranzitiw ýagdaýda <strong>B Pakedyň</strong> 2.0.0 wersiýany gurnaýa. Emma <strong>A Paketda </strong>biz <strong>B Pakedyň</strong> 1.0.0 wersiýany ulanmak isleýäris, we munuň üçin <strong>A Pakedyň</strong> pubspec.yaml faýlda şu aşakdakylary görkezmeli:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/782dbe2981ef1e748f47829d972ae238/href">https://medium.com/media/782dbe2981ef1e748f47829d972ae238/href</a></iframe><p>Wersiýalar täzeden kesgitlenende (override edilende) örän (ünsli) seresaply hereket etmeli. Sebäbi, <em>override</em> edilenden soň proýekt kompilirlemesini bes etme howpy bar, ýagny özünden pes ýa-da ýokary bolan wersiýany ulanýan bibiliotekalarda özüne kesgitlenen wersiýada bolmaly funksionalyň ýetmezçiligi bolup biler. Şeýle hem bibliotekalaryň taslamasyna aktual däl wersiýalary gurnamaly däl, sebäbi freýmwork we bibliotekalar tiz kämilleşýänligi üçin, gabat gelmeýän üýtgeşmeler ýüze çykyp biler (<em>breaking changes</em>). Bibliotekany näçe giç obnowleniýa etseler, wagtyň geçmegi bilen obnowleniýa etmek has çylşyrymlaşýar. Şeýle hem taze wersiýalarda hasabat bermegiň (nedootçýoty) täze mümkinçilikleri we düzedişleri ýüze çykyp biler.</p><p>dependencies hökmünde pubspec.yaml — da görkezilýän baglylyklardan başgada dev_dependensies hem bar. Bu ýerde bellenilýän baglylyklar diňe işläp taýýarlama (developing) etabynda gerek bolan baglylyklardyr, olar priloženiýanyň düzülişine (sborkasyna, kompilýasiýasyna) girmeýär. Olara linter, kodogenerasiýa we annotasiýa üçin dürli baglylyklar, priloženiýany düzmek üçin ulanylmaýan beýleki baglylyklar we testlar üçin baglylyklar degişli bolýar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef64f3b0943f7d1964a2e26b41753cee/href">https://medium.com/media/ef64f3b0943f7d1964a2e26b41753cee/href</a></iframe><h3><strong>pubspec.lock</strong></h3><p>pubspec.lock — bu Flutter ýa-da Dart taslamasynda pub get buýurmasynyň üstünlikli amala aşyrylanda awtomatik ýagdaýynda generirlenýän (döredilýär) faýldyr. Ol faýla taslama üçin gurnalan şol sanda tranzitiw baglylyklary hem öz içinde jemlemek bilen, baglylyklaryň faktiki (hakyky) wersiýalary baradaky maglumatlary özünde jemleýär.</p><p>pubspec.lock faýly taslamada gurnalan her bir bukjanyň kesgitli wersiýalary barada maglumatlary özünde jemleýär. Bu ýagdaý bolsa gaýtadan bukjalar gurnalanda ilkinji gezekde ulanylan baglylyklary ulanylýandygyny kepillendirýän faýl (sazlamalar).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a09b93ea7d193f8e2d0e256e6a5d486/href">https://medium.com/media/5a09b93ea7d193f8e2d0e256e6a5d486/href</a></iframe><h4>Bu faýly Git-repozitoriýada saklamak gerekmi?</h4><p>Priloženiýalar üçin — hawa zerur. Ol dürli platformada zapusk (run) edilende, deweloperlar üçin, bibliotekalaryň wersiýalary üýtgewsiz galmagyny kepillendirýär. Bu agzalan ýagdaýy aşakdaky mysalda görkezip bolar. Meselem: topara taze deweloper gelip pub get buýurmasyny çagyrsada — oňa bibliotekalaryň täze major wersiýalary gurnalmaýar, sebäbi pubspec.lock faýly eýýäm bar we ol üýtgewsiz galýar.</p><p>Ýöne bibliotekalar üçin bu faýly repozitoriýada ignorirlemek gerek. Sebäbi bir tarapdan biblioteka deweloperlar köne (öňkiden galan) generirlenen pubspec.lock faýly bilen işlemez ýaly, başga tarapdan bolsa biblioteka ulanyjylar bolsa taslama bilen gabat gelmeýän tranzitiw bibliotekalary gurnamaz ýaly, biziň bibliotekamyz hemişe aktual wersiýalaryny saklap (täzeläp) durmaly.</p><h3><strong>Kitaphanalaryň döredilişi</strong></h3><p>Flutter taslamany döretmek üçin flutter create buýurmasy ulanylýar. Pakedy ýa-da plaginy <a href="https://docs.flutter.dev/packages-and-plugins/developing-packages">döretmek üçin</a> ýörite bellik (flag)--template görkezilýär. flutter create --template=package package_name buýurmasy pakedy döretmek üçin ulanylýar, flutter create --template=plagin plagin_name buýurmasy bolsa plaginy döretmek üçin ulanylýar.</p><p>Bibliotekalar üçin bolsa adatça şu aşakdaky strukturany (gurluşy) döredilýär:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*7Xf_bX2NNdhke1jdCd8f7A.png" /></figure><p>Bibliotekanyň strukturasy proýektyň gurluşyndan tawudy, bibliotekada lib/src bukça bar. Ähli amala aşyrylan işler lib/src bukjasynda saklanylýar we gizlin bolýar, ýagny daşky ulanyjylara görünmeýär. Şunlukda lib bukjasyndaky ähli faýllar elýeterli. Şol faýýlaryň içinde bolsa ähli gerekli bolan funksionaly export edilen faýllar ýerleşmeli.</p><p>export bibliotekanyň düýbünde ýerleşýän we kitaphana bagly taslamanyň beýleki böleklerine import üçin zerur bolan faýlda ulanylýar. Köplenç export faýllarynyň atlary bibliotekanyň adyna gabat gelýär.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26050011c1a3e1b44ad6522375d1661c/href">https://medium.com/media/26050011c1a3e1b44ad6522375d1661c/href</a></iframe><p>Proýektyň funksionalyny we faýlaryny ulanmak üçin, ulanjak ýerdeimport ulanalylýar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ee3726fd11131079175c066dd5ffe71/href">https://medium.com/media/5ee3726fd11131079175c066dd5ffe71/href</a></iframe><p>Bibliotekalarda eksport faýldan başgada ýene bir aýratynlyk bar, ýagny CHANGELOG.md.</p><h3>CHANGELOG.md</h3><p>CHANGELOG.md faýly täzeläp durmak zerur hasaplanylýar. Ol faýlyň gurluşynda bibliotekada täze wersiýasynda näme grizildi, düzedildi we ýok edilen zatlar baradaky maglumaty saklaýar. Şeýle hem ol faýlda käwagt gelejekgi meýilleşdirilýän üýtgeşmeler, soňky wersiýadaky ýerine ýetirilip ýetişilmedik zatlar beýan edilýär. Deweloper üçin bu faýlyň bir böleginiň görnüş nusgasyny şeýle görkezmek bolar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c19556f80b1dc515ff40337e9d19a38f/href">https://medium.com/media/c19556f80b1dc515ff40337e9d19a38f/href</a></iframe><p>Bu bolsa okyjylara görünýän görnüşi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0winuBq0hOOZH5LTao-sRg.png" /></figure><h3>Gowy (ygtybarly) bibliotekany nädip saýlamaly?</h3><p>Gynansakda bibliotekany saýlamakda ýeke-täk bir düzgüni ýok, ýöne muňa garamazdan käbir parametrlere üns berip bolar:</p><h4><strong>Kitaphananyň soňky obnowleniýa senesine we ona häzirki wagtda nähili goldaw (maintainance, podderjka) edilýäne üns bermeli.</strong></h4><p>pub.dev — da bu maglumatlary bibliotekanyň atlandyrmasynyň aşagyndan tiz görüp bolýar. Meselem: şu makala döredilme pursadyna kitaphana <a href="https://pub.dev/packages/firebase_messaging">firebase.messaging</a> soňky gezek 9 gün öň publikasiýa edilipdir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BOAzk_NNCrhwAVy3jeh-YA.png" /></figure><h4>CHANGELOG <strong>-yň jikme-jik ýöredilşi</strong></h4><p>Bibliotekanyň wersiýasyny ýokarlananda bu maglumatlar dewelopera haýsy funksionaly gaýtadan seredilmegini ýa-da goldamalydygyna düşünmäge kömek eder.</p><h4>issue_tracker –e näçe gezek ýüzlenilipdir.</h4><p>Eýeçilik edýän deweloper nähili tizlikde (çaltlykda) näsazlyklary düzedýär we täze ýüze çykýan soraglara jogap berýär.</p><h4><strong>Meşhurlygyň dürli bahalandyrylyş metrikalary</strong></h4><p>Gitub — daky ýyldyzjyklara ýa-da <a href="http://pub.dev/">pub.dev</a> — ky Scores bölümine seredip baha berip bolar — Scores bölüminde bibliotekanyň hem meşhurlygyny (ulanylyş derejesini), halananlary (halananlary) we pub points -yň şahsy bahalandyrma ölçegini özünde jemleýän köp sanly metrikalar görkezilen, (pub points bahalandyrmasy — bibliotekanyň derejesini, baglylyklaryň aktuallygyny, dokumentasiýanyň bardygy baradaky maglymaty görkezýär, şeýle hem biblioteka Dart-yň gaýdlaýnlaryň (ulanyň maslahatlaryna) düzgünine we Dart-yň 3 wersiýasy bilen gabat gelýänligi barada maglumatlary görkezýär)</p><blockquote><a href="https://dart.dev/null-safety">Null safety</a> — <em>Null howpsuzlygy, </em>diýmek, programmirleme dillerinde, bir üýtgeýjäniň (variable, peremennaýa) “null” (hiç zat ýok) bahasy almak mümkinçiliginiň öňüni almak ýa-da şol barlagy dolandyrmak üçin ulanylýan bir usuldyr. Ol Dart 2.12 wersiýasyndan başlap elýeterli boldy we proýektlerden we bibliotekalardan null bahalaryna garşy howpsuzlyk goldawyny talap etdi. Dart 3 wersiýasyna çenli, proýektleri --no-sound-null-safety baýdagy (tag) bilen işletmek we null bahalary bilen howpsuz işlemek barada duýduryşlary ignor (üns bermezlik, äsgermezlik) etmek mümkindi. Dart 3 esasy wersiýa bilen, buny edip bolmaz — ähli bibliotekalar we proýektyň özi nullable (ýagny null bolyp bilýän) bahalar bilen howpsuz işlemäge borçludyr.</blockquote><h3>Peýdaly maslahatlar</h3><ol><li>Proýekti işledip başlamazdan ozal, ähli zerur baglylyklary gurnamak üçin, flutter pub get buýrugyny işletmegi ýatdan çykarmaň. Eger proýekt näbelli sebäplere görä jemlenmese (run bolmasa ýa-da kompilýasiýa bolmasa), flutter clean buýrugy kömek edip biler. Ol .dart_tools bukjany arassalar we mümkin bolan näsaz keşi aýyrar. Onsoň ýene-de flutter pub get buýrugy bilen baglylyklary gaýtadan gurnamaly bolarsyňyz.</li><li>Internet birikmesi ýok wagty, kesişden bibliotekalary gurnamak üçin flutter pub get — offline buýrugyny ulanyp bilersiňiz.</li><li>flutter pub get buýrugyny işledenimizde, .pub_cache bukja döredilýär, ol keşlanan bibliotekalary öz içine saklaýar. Käwagt keşiň hatardan çykmagy mümkin. Meselem, kodogenerasiýa goşulanda ýa-da bibliotekanyň birinde kody ýalňyşlyk bilen üýtgedilende. Kesişdäki faýllary öz eliň bilen üýtgetmek asla maslahat berilmeýär. Bu ýagdaý ýüze çykanda, flutter pub cache clean buýrugyny işledip, keşi doly arassalamak we flutter pub cache repair buýrugy bilen her bir bibliotekany gaýtadan gurnamak gowy bolar.</li><li>Kähalatlarda, platforma-aýratynlykly bibliotekalarda ýalňyşlyklar döreýär. Bu, görkezilen bibliotekalar gurnalyp bilmändigi sebäpli bolup biler. Natiw baglylyklary arassalamak we olary gaýtadan gurnamak üçin <strong>iOS</strong> üçin pod deintegrate &amp;&amp; pod install we <strong>Android</strong> üçin gradlew clean buýruklaryny işletmeli.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e88abec85b03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: proýektyň gurluşy]]></title>
            <link>https://medium.com/@meinnps/flutter-pro%C3%BDekty%C5%88-gurlu%C5%9Fy-30e0fa7fdef1?source=rss-c93de175ef16------2</link>
            <guid isPermaLink="false">https://medium.com/p/30e0fa7fdef1</guid>
            <category><![CDATA[türkmençe]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[türkmen-dili]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Merdan Durdyyev]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 13:26:11 GMT</pubDate>
            <atom:updated>2024-04-20T04:09:22.212Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bölüm #1</h4><p><em>Bu bölümde biz proýektdaky indiki işlerimizde girişmek ýeňil bolar ýaly, priloženiýanyň gurluşy bilen, şeýle hem onuň her bir bukjasy we faýly bilen tanyşarys.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BjVQyP1NG52FVAoekyfQcg.png" /></figure><p><a href="https://github.com/dart-lang"><strong>Dart</strong></a><strong> — </strong>bu Google kompaniýasy tarapyndan işlenip taýýarlanylan programmirleme dili, <a href="https://github.com/flutter/flutter"><strong>Flutter</strong></a> bolsa — Dart dilinde ýazylan kross-platformaly UI-freýmworkdyr. Bu innowasion freýmworky 6 platformada, ýagny: Android, iOS,Linux, MacOS, Web we Windows platformalarda işläp bilýär we olarda priloženiýalary işläp taýýarlamaga mümkinçilik berýär. Bu mümkinçilikler esasynda hem deweloperlar öz wagtlaryny we resurslaryny tygşytlaýarlar: ýagny her bir platforma üçin priloženiýanyň aýratyn wersiýalaryny (görnüşlerini) döretmek we saklamak (goldamak) zerurlygy ýok.</p><blockquote>Ähli bölümleri gömek üçin <a href="https://medium.com/@meinnps/flutter-a-giri%C5%9F-kursy-3d4b28de3f32">şu ýere </a>salgylanyp bilersiňiz.</blockquote><p>Geliň indi bolsa Flutteriň gurnalşyndan başlalyň.</p><h3><strong>Flutter-iň gurnalşy</strong></h3><p>Flutterde<strong> </strong>ýazyp başlamak çylşyrymly däl (aňsat) — munuň üçin şu aşakdaky yzygiderlikde gerekli enjamlary (instrumentlary) gurnamaly:</p><ol><li><a href="https://docs.flutter.dev/">docs.flutter.dev</a> girmeli</li><li><a href="https://docs.flutter.dev/get-started/install">gözükdirmä</a> laýyklykda enjamlary (okruženiýany) gurnamaly</li><li>Işlemek üçin <a href="https://docs.flutter.dev/get-started/editor">amatly (ykjam)</a> gurşawy saýlamaly</li><li>flutter create my_app — buýurmasynyň kömegi bilen proýekt döredilýär. Şeýlelikde başlangyç priloženiýa taýýar</li></ol><h3>Pub</h3><p><a href="https://dart.dev/tools/pub/cmd#:~:text=The%20pub%20package%20manager%20has,dependencies%20for%20a%20Flutter%20package">Pub</a>, Dart programmirleme dili üçin paket dolandyryjysy. Onda Flutter we umumy Dart programmalary üçin gaýtadan ulanylýan bibliotekalar we paketler bardyr.</p><p>Aşakdaky gollanmada pub buýurma setirini (komandny stroka) Flutter proýektlarynda we Dartda baglylyklary (zawisimostlary) we bukjlary dolandyrmak üçin köp duş geler. Ol Dart SDK –yň düzümine girýär we priloženiýany işläp taýýarlamak üçin ykjam serişdeleri hödürleýär. Islendik proýekt flutter pub get buýurmasy bilen işläp başlaýar, ol buýurma gerek bolan zerurlyklary (baglylyklary), şol sanda Flutteri gurnaýar.</p><h3><strong>Proýektyň gurluşy</strong></h3><p>Flutterda proýektlar iki görnüşe bölünýär: priloženiýa we biblioteka.</p><p><strong>Priloženiýa</strong> — ahyrky ulanyjy tarapyndan enjama gurnamak üçin niýetlenen, <strong>Biblioteka</strong> bolsa — bu beýleki proýektlarda gaýtadan ulanyp bolýan, enjamlaryň we komponentlaryň toplumydyr.</p><blockquote>Biblioteka, olaryň gurnalyşy we öz bibliotekanyň döredilişi barada indiki bölümlerde içgin seredip geçeris.</blockquote><p>Priloženiýada, bibliotekada birmeňzeş gurluşly bolup, olar şu aşakdaky bukjalardan we faýllardan düzülen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*qGKE7nt65AaddLkQucrZrA.png" /><figcaption>Sada Flutter proýektyň düzümi</figcaption></figure><h4>android, ios, linux, macos, web, windows</h4><p>android, ios, linux, macos, web, windows bukjalary Flutter proýektynda her bir platforma üçin spetifiki (ähmiýetli) bolan koda we gurluşa (nastroýka) eýedir. Bukjalarda priloženiýanyň degişli platformada düzülmegi, toplumlanmagy we işe başlamagy üçin zerur bolan faýllar we kataloglar ýerleşýär.</p><p>Bu bukjalaryň her biri, priloženiýany gerekli platformada üstünlikli işletmek we düzmek üçin, gurnamak we sazlamak zerur bolan şahsy enjamlaryň we baglylyklaryň toplumyna eýe. Flutter priloženiýalar işenilip taýýarlanylanda bu aýratynlyklary göz öňünde tutmak we priloženiýany onuň ähli niýetlenen platformlarynda test geçirmek (barlamak) zerurdyr.</p><p>Eger proýektyň niýetlenilmesi kesgitli (belli bir) platformalar üçin meýilleşdirilen bolsa, onda olary --platforms parametrlerde belläp geçmeli, ýagny, aralarynda “ , ” otur goýmak bilen zerur platformalaryň sanawyny bellemeli. Meselem: eger proýekt diňe Android we iOS-da işleýän bolsa, onda komda şu aşakdaky görnüşde bolar: <br>flutter create –platforms=ios,android . .</p><h4><strong>lib</strong></h4><p>Flutter proýektyndaky lib bukjasy — bu esasy bukja bolup, ol bukjada priloženiýanyň başlangyç (ulanylýan) kody ýerleşýär. Ol bukjada priloženiýanyň logikasyny we interfeýsyny kesgitleýän proýektyň ähli Dart faýllary ýerleşýär. Bu bukjada main.dart faýly ýerleşen.</p><h4><strong>main.dart</strong></h4><p>Flutter proýektynda main.dart faýly — priloženiýa girmek üçin başlangyç nokatdyr, ol ýerde esasy main() funksiýasy ýerleşen. Bu faýl priloženiýanyň esasy kodyny düzýär we onuň işe girmeginde (başlamagy) üçin itergi nokady bolup çykyş edýär.</p><p>main.dart faýlynda köp möçberde logikany ýa-da UI-komponentleri ýerleşdirmek göz öňünde tutulmaýar, sebäbi bu ýagdaý kody işläp taýýarlamakda we saklamakda işiň haýýalamagyna getirip bilýär. Köplenç bu faýlda diňe main funksiýasy döredilýär, has çylşyrymly logikalar bolsa aýratyn faýllara we klasslara çykarylýar.</p><h4><strong>pubspec.yaml</strong></h4><p><a href="https://dart.dev/tools/pub/pubspec">pubspec.yaml</a> faýly Flutter ýada Dart proýektyň esasy komponentlaryna degişli. Ol faýl proýektyň konfigurasiýasyny kesgitleýär we proýektyň baglanşyklaryny (baglylyklaryny), bibliotekanyň görnüşini (wersiýasyny), proýektyň düzüliş sazlamalaryny (nastroýkalaryny) we beýleki düzüjilerini kesgitlemek üçin ulanylýar.</p><p>Aşakda my_app atly proýektyň düzülişiniň mysallary getirilen:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba1be1d003f7daac57fd0b2c6f5b0516/href">https://medium.com/media/ba1be1d003f7daac57fd0b2c6f5b0516/href</a></iframe><p>pubspec.yaml faýlyň hökmany parametrleri bar:</p><ul><li><a href="https://dart.dev/tools/pub/pubspec#name">name</a> — proýektyň ady. Adatça onuň ady, proýekt ýerleşýän ady bilen gabat gelýär. Ýokardaky getirilen mysalda onuň ady my_app diýip atlandyrylan, şonuň üçin pubspeс.yaml faýlda name:my_app ýerleşen;</li><li><a href="https://dart.dev/tools/pub/pubspec#sdk-constraints">environment</a> — bu proýektyň gurşawynda Dart we Flutter wersiýany kesgitleýän parametrdyr. Biziň pubspec.yaml<strong> </strong>faýlymyzda Dart wersiýany görkezmek üçin sdk parametry ulanylýar. Diýmek my_app proýektymyzda Dart-yň wersiýasy 3.2.3 ulanylyar.</li></ul><p>Şeýlelikde, <strong>biblioteka</strong> üçin hem ýörite bolan parametrlar bar:</p><ul><li><a href="https://dart.dev/tools/pub/pubspec#version">version</a> — kitaphananyň aktual (häzirki wagtda ulanylýan) wersiýasy;</li><li><a href="https://dart.dev/tools/pub/pubspec#description">description</a> — proýektyň beýany. Her bir täze döredilýän proýekt üçin ol ýokarda getirilen mysaldaky ýaly A new Flutter projectbolar. Ýa-da flutter create komandasynda — description parametr ulanyp öz isegiňize görä belläp bilersiňiz.</li></ul><p>Şu aşakdakylar ýene-de käbir hökmany däl parametrler:</p><ul><li><a href="https://dart.dev/tools/pub/pubspec#homepage">homepage</a> — proýektyň baş sahypasyna çykmak üçin salgy (link), köplenç ýagdaýda salgy repozitorisyna salgylanýar.</li><li><a href="https://dart.dev/tools/pub/pubspec#repository">repository</a> — başlangyç kodly özinde saklaýan proýektyň repozitorisyna çykmak üçin salgy;</li><li><a href="https://dart.dev/tools/pub/pubspec#issue-tracker">issue_tracker</a> - proýektyň ulanyjylary tarapyndan ýüze çykan kemçilikleriň (meseleleriň) we teklipleriň trekerine çykylýan salgy. Meselem: käwagt issue seksiýasyna (bölümine) çykmaga salgyny <a href="https://docs.github.com/en/issues/tracking-your-work-with-issues/about-issues">GitHub issue</a> –da görkezýärler;</li><li><a href="https://dart.dev/tools/pub/pubspec#documentation">documentation</a> — proýektyň dokumentasiýasyna gönükdirilen salgy;</li><li><a href="https://dart.dev/tools/pub/pubspec#executables">executables</a> — buýurma setirinden (komandny stroka, command-line) ugradyp bolýan, ýerine ýetiriji faýl görnüşindäki proýektyň skriptlary:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f3eea23cf39ee7c75605a7fc426d8b8/href">https://medium.com/media/5f3eea23cf39ee7c75605a7fc426d8b8/href</a></iframe><ul><li><a href="https://dart.dev/tools/pub/pubspec#platforms">platforms</a> — proýekty saklaýan platformalar:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8882e93b7626a008dc724a77f0e71e39/href">https://medium.com/media/8882e93b7626a008dc724a77f0e71e39/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7278552c032f50a7f65c6dedbd614e6/href">https://medium.com/media/f7278552c032f50a7f65c6dedbd614e6/href</a></iframe><ul><li><a href="https://dart.dev/tools/pub/pubspec#publish_to">publish_to</a> — biblioteka ýerleşen (publikasiýa edilen we el ýeterli) paketlaryň çap (publikasiýa) edilme serwerine salgy (mysal üçin <a href="https://pub.dev/">pub.dev</a> saýt). Eger berilen salgy boş bolsa, onda çap edilýän bukjalar pub.dev salga ugradylýar ol salgy barada biz indiki bölümde giňişleýin düşündirers. Egerde siz proýekty publikasiý etmek islemeseňiz,onda publish_to:`none`gönükdirmeli. Edil şolar ýaly hem bu parametry bukjalary publikasiýa etmegiň ulanyjy (öz) serwerini görkezmek üçin hem ulanyp bolýar.</li><li><a href="https://dart.dev/tools/pub/pubspec#funding">funding</a>- işläp taýýarlaýjy awtory tapmak we oňa ýardam bermek üçin salgylaryň sanawy:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e664a57beec02812d9398ddd55f3a13d/href">https://medium.com/media/e664a57beec02812d9398ddd55f3a13d/href</a></iframe><ul><li>false_secrets — gizlinligi (sekretlary) barlanmaýan faýllary görkezmek üçin bölüm. Paket pub-a publikasiýa edilende, pub gizlinlikleriň (sekretlaryň) barlygy ýa ýoklugyny barlaýar: meselem API açarlaryň ýa-da kriptografiki maglumatlaryň barlygyny ýa ýoklugyny barlaýar. Eger paketda ýokardaky ýaly gizlinlikler ýa-da maglumatlar bar bolsa, onda bukja publikasiýa edilmeýär. Emma käwagt barlag ýalňyş maglumat hem kabul edip biler — ýagny sekret däl faýly, gizlin faýl hökmünde kabul edip biler. Şonuň üçin, eger barlag döwründe siz faýlda hiç hili sekredyň ýokdugyna ynamly bolsaňyz onda ol faýly false_secrets meýdanyna goşuň we barlag geçende ol faýla pub tarapyndan üns bermän geçer:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/859de617fe871cd210ff8b2de46992ee/href">https://medium.com/media/859de617fe871cd210ff8b2de46992ee/href</a></iframe><ul><li>screenshots- biblioteka bilen baglanşykly ekransuratlary: widjetleriň ýa-da proýektyň beýleki wizual elementleriň mysallary:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71bb11d86205051a78c25c27b2cc5ca0/href">https://medium.com/media/71bb11d86205051a78c25c27b2cc5ca0/href</a></iframe><ul><li>dependencies, dev_dependencies we dependency_overrides baglylyklar (zawisimost). Bu baglylyklar barada indiki bölümde durup geçers.</li></ul><p>Ähli mümkin bolan meýdanlary ulanýan pubspec.yaml faýl şu aşakdaky mysaldaky ýaly görnüşde bolýar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/991f68c405ee7bf54f9529c7211923a1/href">https://medium.com/media/991f68c405ee7bf54f9529c7211923a1/href</a></iframe><h4><strong>analysis_options.yaml</strong></h4><p><a href="https://dart.dev/tools/analysis#the-analysis-options-file">analysis_options.yaml </a>— bu faýl <a href="https://github.com/dart-lang/linter">linteryň</a> konfigurasiýasyny sazlamaga mümkinçilik berýär. Bibliotekalar üçin, <a href="https://dart.dev/tools/linter-rules">Linter</a> proýektda ulanyp bolýan standart (adaty) kadalar toplumyny şöhlelendirýär. Ýöne ulanyjy proýektyň talaplaryna laýyklykda kadalar toplumyna üýtgeşme girizip biler.</p><p>Aşakda getirilen mysallarda <a href="https://pub.dev/packages/lints">lint</a> pakedy ulanylýar. Bu Dart-proýekty üçin ähli göz öňünde tutulan düzgünler jemlenen resmi paketydyr. Mundan başga ol aşakdaky mysalda paketdyň özünde bar bolan çäklendirmelerden daşary (öz) çäklendirmeler goşulan.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ddd3a2cad3100fd7a885cfa01e33d91/href">https://medium.com/media/6ddd3a2cad3100fd7a885cfa01e33d91/href</a></iframe><p>include meýdany beýleki, faýlyň içinden düzgünleri (prawilalary) ulanmaga mümkinçilik berýär. Ýokarda görkezilen mysallarda lints bukljasyndaky reсommended.yaml faýlyndan alynan düzgünler analysis_options.yaml faýlynda gaýtadan ulanylýar (ikisini goşýar).</p><p>analyzer meýdany — statiki seljermäni (analizy) gurnamak üçin niýetlenendir meselem: tipleriň has berk (pugta) barlagyny işe girizmek, faýllary barlagdan aradan aýyrmak, kesgitli (bellenilen) düzgünlere üns bermezlik, düzgünleriň berkligini üýtgetmek ýa-da synaglary amala aşyrmak.</p><blockquote>Şeýlelikde, strict-inference: true parametry final myMap={}; ýaly koda ýalňyş diýip habar berer.</blockquote><p>linter meýdany düzgünleri aradan aýyrmak we goşmak üçin, linteri kastomizirlemek (öz islegiňe görä sazlamak) üçin ulanylýar.</p><blockquote>Bar bolan düzgünler (prawilalar) barada <a href="https://dart.dev/tools/linter-rules">şu ýerden</a>, we ol düzgünleri sazlamak barada <a href="https://dart.dev/guides/language/analysis-options#the-analysis-options-file">şu ýerden</a> okap bilersiňiz.</blockquote><h4><strong>test</strong></h4><p>Bu bukjada işläp taýýarlaýjy (deweloper) tarapyndan ýazylan <a href="https://docs.flutter.dev/testing">ýunit- we widjet </a>testlar ýerleşdirilen.</p><h4><strong>.gitignore</strong></h4><p>Bu faýl git <a href="https://git-scm.com/book/en/v2/Getting-Started-What-is-Git%3F">wersiýanyň sazlama ulgamynda</a> proýektyň haýsy faýllaryny ýa-da bukjalaryny ignorirlemelidigini (üns bermeli däldigini, hasaba almaly däldigini) bellemage mümkinçilik berýär.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/496f50f6293fb6b06ff34f3d69e68015/href">https://medium.com/media/496f50f6293fb6b06ff34f3d69e68015/href</a></iframe><p>Dart we Flutter proýektler üçin, başgada .dart_tool we build bukjalaryny, bibliotekalarda we paketlarda bolsa, ýokarda agzalanlardan daşary, pubspeс.lockfaýly .gitignorefaýlyna goşmak maslahat berilýär.</p><h4>pubspec.lock</h4><p>Flutter-däki <a href="https://medium.com/codingmountain-blog/what-is-pubspec-lock-and-why-should-flutter-devs-care-86ab4d0b47fc">pubspec.lock</a> — bu döredilen wagtynda proýektyň ulanylýan baglylyklaryň (dependency, zawisimost) anyk wersiýalaryny belläp (şaýat bolýan) awtomatiki usulda döredilen dokument (resminama) faýlydyr. Bu, “Flutter” taslamasynda işleýän ähli deweloperlaryň semantik wersiýadan soň paketlerde bolup biläýjek täzelenmelere garamazdan yzygiderli garaşlylyk toplumyna eýe bolmagyny üpjün edýär.</p><blockquote>pubspec.lock barada giňişleýin ikinji bölümde gürrüň açarys</blockquote><h4><strong>README</strong></h4><p>README — bu proýekt barada, onuň niýetlenilişi, funksionallygy we ulanylyşy barada maglumat saklaýan faýldyr. Bu faýl proýektyň işäp taýýarlaýjynyň (deweloper) ýa-da ulanyjynyň proýekt bilen tanyşlygynda ilkinji okaýan faýlydyr, ol adatça proýektyň asyl (düýp) direktoriýasynda ýerleşýär.</p><p>README faýly köplenç aşakdaky maglumatlary şöhelelendirmek üçin ulanylýar.</p><ul><li>Proýektyň mazmuny — bu proýektyň mazmuny, onuň niýetlenilişi we ulanylyş düzgünleri. Adatça bu maglumatlar README faýlyň ilkinji abzasynda bolýar.</li><li>Gurnamak we işe girizmek — ulanyja proýekt bilen işlemegi başlamak üçin, kömek edýän proýekty gurnamak we işe girizmek boýunça gözükdirme maglumatlary;</li><li>Ulanylyşy — proýektyň funksionall taýdan düşündirilişi we dürli komponentleriň ýada funksiýalaryň ulanylyş ädimleri we usullaryny içgin beýan edýär.</li><li>Mysallar — proýektyň ulanylyş mysallary, bu mysallar ulanyja proýekta, onuň işleýşine has gowy düşnmäge we olaryň kömegi bilen ýerine ýetirilýän işleri bilmäge ýardam berýär.</li><li>Baglanşyklary (baglylyklary) — proýektyň işi üçin zerur bolan bukjalaryň (paketlaryň we bibliotekalaryň) wersiýalarynyň we baglylyklarynň sanawy;</li><li>Lisenziýa (rugsatnama, kepillik) — proýektyň lisenziýasyny göz öňünde tutmak bilen onuň ulanylşy boýunça çäklendirmeler we hukuklar baradaky maglumat.</li></ul><p>Takyk ýazylan README faýly ulanyjylara proýekta tiz girişmäge we onuň bilen ýeňil işlemäge mümkinçilik berýär. Onuň bilen birlikde ol işläp taýýarlaýjylara we ahyrky ulanyjylara proýekt üçin resminamalar çeşmesi hem bolup durýar.</p><p>Esasy bellemeli zat hem README ähli ulanyjylar üçin açyk faýl bolaýr, şonuň üçin onuň içinde gizlin maglumatlary goýmaklyk göz öňünde tutulmaýar.</p><h4>LICENSE</h4><p>Public (ähli adamlara elýeterli) edilýän repozitoriýalar üçin kody <a href="https://en.wikipedia.org/wiki/Software_license">lisenzirlemek</a> (kepillendirmek) üçin LICENSE faýly goşmak maksada laýyk hasaplanýar. Bu faýl beýleki ulanyjylara kody goşmaga, aýyrmaga we köpeltmäge mümkinçilik berýär. Käbir lisenziýalar ýazylan kody gaýtadan ulanmak isleýän dewelopera hiç hili çäklendirmelerini bildirmeýärler, käbiri bolsa repozitoriýanyň ýa-da awtoryň adyny görkezmegini ýa-da pakedy ulanan ýagdaýynda tölege hem şertlendirýärler.</p><p>Lisenziýalaryň örän köp sanly möçberiniň barlygy sebäpli, özüňe gabat gelýän amatlysyny tapmak çylşyrymly bolýar. Biziň bu meselämize bolsa GitHub tarapyndan işlenilen <a href="https://choosealicense.com/">choosealicense</a> proýekty ýardam berer. Ol nähili lisenziýalaryň barlygyny, olaryň arasyndaky tapawutlyklary seljermäge we biziň proýektymyza gabat gelýän lisenziýany saýlap almakda ýardam berýär.</p><h4><strong>.dart_tool</strong></h4><p>.dart_tool bukjasy proýektda enjamlar we paketlar bilen baglanşykly operasiýalar ýerine ýetirilende awtomatik usulda döredilýär. Ol bukjanyň içinde wagtlaýyn faýllar, keşlar, artefaktlar we kodyň ýerine ýetirilmeginde, seljerilende we kompilýasiýasynda döredilen (generasiýa bolan) beýleki maglumatlary saklaýar.</p><p>Şu aşakda .dart_tool bukjasynyň içinde bolup biläýjek birnäçe belli faýllar we bukjalar getirilen:</p><ul><li>build — proýektyň düzülişiniň netijeleri saklanylýan bukjadyr. Onda düzüliş enjamlary we ýerine ýetirilişiniň gurşawy bilen baglanşykly bukja asty bukjalar (sub folder) bolup biler.</li><li>.dart_tool/paсkage_config.json — proýektyň baglylyklary, şeýle hem proýektlarda ulanylýan paketlara barýan ýollar (path, adres) baradaky maglumatly faýllar.</li><li>.dart_tool/paсkage_config_subset — bu faýly baglylyklar baradaky köpdürli maglumatlary, proýektyň tiz düzülmegi (kompilasiýa bolmagy) we işläp başlamagy üçin zerur bolan maglumatlar.</li><li>.dart_tool/pub — proýektyň baglylyklaryny seljermek we gurnamak üçin ulanylýan pub paketlaryň menedjerligi bilen baglanşykly bolan wagtlaýyn faýllar saklanylýar.</li></ul><h4><strong>.metedata</strong></h4><p>.metedata — bu gizlin faýl bolup, Flutter — proýektyň parametrlerini yzarlamak (gözegçilik) etmek üçin ulanylýar we iş gurşawy (sreda) tarapyndan awtomatiki döredilýär. Bular ýaly faýlda proýektda ulanylýan freýmworkyň wersiýasy barada, proýektyň bir freýmworkdan beýleki freýmworkyň beýleki wersiýasyna migrirlenmek (geçmek) üçin kömekçi faýllary we beýlekileri saklanylýar. Olar ýaly faýl iş gurşawy bilen awtomatik usulda döredilýär we ol özbaşdak redaktirlenmeli (üýtgetmeli) däl.</p><h4><strong>dart doc</strong></h4><p>Biblioteka we proýektlar üçin resminamany döretmäge <a href="https://dart.dev/tools/dart-doc">dartdoc</a> ýardam berýär. Bu buýurma koddaky ýazgylar boýunça reminamalary generirlemäge (döretmäge) mümkinçilik berýär. Aşakda ýokardaky käbir mysaly ýazgylar getirilen:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6805b7c74ac19e9bf278f161f72db40c/href">https://medium.com/media/6805b7c74ac19e9bf278f161f72db40c/href</a></iframe><p>Dokumentasiýany generirlenmesi (döredilmegi) üçin dart doc . buýurmany ulanmaly.</p><h3>Beýleki peýdaly linkler</h3><ul><li>pubspec.yaml barada <a href="https://docs.flutter.dev/development/tools/pubspec">dokumentasiýasy</a></li><li>Git-da kommit etmeli däl zatlaryň <a href="https://dart.dev/guides/libraries/private-files">adalgalary</a></li><li>.gitignor <a href="https://git-scm.com/docs/gitignore">faýly</a></li><li>Linter düzgünleri barada <a href="https://dart.dev/tools/linter-rules">dokumentasiýa</a></li><li>Linter düzgünleri ulanmagynyň <a href="https://dart.dev/guides/language/analysis-options#the-analysis-options-file">dokumentasiýasy</a></li></ul><h3><strong>Netije</strong></h3><p>Birinji bölüminde biz proýektyň möhüm faýllary we bukjalary bilen, ýagny: platformalaryň bukjalary, konfigurasiýa faýllary, linteri sazlamagyň faýly we beýlekiler bilen tanyşlyk geçdik. Proýektyň bu bölekleri entek iş prosesynda kän duş geler.</p><p>Indiki böümlerde biz programmirleme diliniň nýuanslary barada agzap geçers we ýuwaşlyk bilen Flutterde birinji proýektyň döredilişine başlarys.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30e0fa7fdef1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>