<?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 Ankeet Karki (Tej Bikram) on Medium]]></title>
        <description><![CDATA[Stories by Ankeet Karki (Tej Bikram) on Medium]]></description>
        <link>https://medium.com/@bikramtej3?source=rss-16046549f28b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WeQYUnDvr7y27aYa.jpg</url>
            <title>Stories by Ankeet Karki (Tej Bikram) on Medium</title>
            <link>https://medium.com/@bikramtej3?source=rss-16046549f28b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:37:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bikramtej3/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[Custom Scrolling in Flutter]]></title>
            <link>https://medium.com/@bikramtej3/custom-scrolling-in-flutter-e40cc54880db?source=rss-16046549f28b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e40cc54880db</guid>
            <dc:creator><![CDATA[Ankeet Karki (Tej Bikram)]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 06:16:34 GMT</pubDate>
            <atom:updated>2023-06-04T06:16:34.176Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you want to implement custom scrolling in your Flutter application where you can position specific widgets at the top of your device like this?</p><p><a href="https://www.youtube.com/shorts/QoJ08Wwa0l0">Custom Scrolling in Flutter</a></p><p>It’s really easy to implement using CustomScrollView.</p><p>First, create a new project using flutter create project_name</p><p>Now, open it in your desired code editor. Navigate to the lib folder and copy the following content into your main.dart file.</p><pre>import &#39;package:custom_scroll/home_page.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br></pre><pre>void main(){<br>  runApp(const MyApp());<br>}</pre><pre>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return const MaterialApp(<br>      title: &quot;custom scroll&quot;,<br>      home: HomePage(),<br>    );<br>  }<br>}</pre><p>Now, create a new file named home_page.dart inside your lib folder and copy the following block of code inside that file.</p><pre>import &#39;package:flutter/material.dart&#39;;</pre><pre>class HomePage extends StatefulWidget {<br>  const HomePage({super.key});</pre><pre>  @override<br>  State&lt;HomePage&gt; createState() =&gt; _HomePageState();<br>}</pre><pre>class _HomePageState extends State&lt;HomePage&gt; {<br>  Widget horizontalList() {<br>    return SingleChildScrollView(<br>      scrollDirection: Axis.horizontal,<br>      child: Row(<br>        children: [<br>          &quot;First&quot;,<br>          &quot;Second&quot;,<br>          &quot;Third&quot;,<br>          &quot;Fourth&quot;,<br>          &quot;Fifth&quot;,<br>          &quot;Sixth&quot;,<br>          &quot;Seventh&quot;,<br>        ]<br>            .map((e) =&gt; Padding(<br>                  padding: const EdgeInsets.symmetric(horizontal: 10),<br>                  child: Chip(<br>                    label: Text(e.toString()),<br>                  ),<br>                ))<br>            .toList(),<br>      ),<br>    );<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(),<br>      body: CustomScrollView(<br>        slivers: [<br>          SliverToBoxAdapter(<br>            child: horizontalList(),<br>          ),<br>          SliverAppBar(<br>            title: horizontalList(),<br>            pinned: true,<br>            titleSpacing: 0,<br>            backgroundColor: Theme.of(context).scaffoldBackgroundColor,<br>          ),<br>          SliverToBoxAdapter(<br>            child: horizontalList(),<br>          ),<br>          SliverAppBar(<br>            title: horizontalList(),<br>            pinned: true,<br>            titleSpacing: 0,<br>            backgroundColor: Theme.of(context).scaffoldBackgroundColor,<br>          ),<br>          SliverToBoxAdapter(<br>            child: ListView.separated(<br>              physics: const NeverScrollableScrollPhysics(),<br>              separatorBuilder: ((context, index) =&gt; const SizedBox(<br>                    height: 5,<br>                  ),<br>                ),<br>              shrinkWrap: true,<br>              itemCount: 50,<br>              itemBuilder: (context, index) {<br>                return Container(<br>                  height: 50,<br>                  alignment: Alignment.center,<br>                  color: Colors.yellow,<br>                  width: double.infinity,<br>                  child: Text(&quot;$index&quot;),<br>                );<br>              },<br>            ),<br>          )<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>Great! We’ve just implemented the scrolling displayed above in the embedded video.</p><p>Let me explain a few points:</p><ul><li>The widget you want to pin must be contained in a SliverAppBar as the SliverAppBar contains a pinned property, that helps you to pin/unpin specific widgets as per your choice.</li><li>The other normally used widgets such as Container, ListView, Column, etc must be wrapped by SliverAppBar/SliverFillRemaining/SliverToBoxAdapter or something else which I currently don’t know of, otherwise, you might encounter an error telling: A RenderViewport expected a child of type RenderSliver but received a child of type RenderRepaintBoundary.</li></ul><p>With these points in mind, you can make this effect in just a few minutes. The source code is available at: <a href="https://github.com/ankeet7x/custom_scroll">https://github.com/ankeet7x/custom_scroll</a></p><p>P.S. This is a way I implement it. If you guys know of some other ways, feel free to advice. Thanks :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e40cc54880db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running JavaScript Code in Flutter Webview]]></title>
            <link>https://medium.com/@bikramtej3/running-javascript-code-in-flutter-webview-d65a93f2a6ba?source=rss-16046549f28b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d65a93f2a6ba</guid>
            <dc:creator><![CDATA[Ankeet Karki (Tej Bikram)]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 06:12:27 GMT</pubDate>
            <atom:updated>2023-06-04T06:12:27.455Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever used the <a href="https://pub.dev/packages/webview_flutter">webview_flutter</a> package? It’s awesome. You can render web view with ease. Have you ever stumbled upon a requirement when you had to run custom JavaScript code in Flutter on a certain website with or without rendering the website?</p><p>You might already know about WebViewController().runJavaScript() method. Let&#39;s dive deep into it.</p><p>Let us suppose, We need to scrape certain data from a website and you need to render those in your Flutter app. In my case, I’m using my friend Nirav’s website: <a href="https://niravko.com/">https://niravko.com</a>. I’m going to scrape all the titles of the blogs that he has posted so far. Firstly, I need to head to his website in the browser and write custom javascript codes to fetch all the titles as displayed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JfpZp6bWbIEG2Qok.png" /></figure><p>This JavaScript code runs fine in the browser. Now, we need to implement it in the app.</p><p>First, create a Flutter app, and add <a href="https://pub.dev/packages/webview_flutter">webview_flutter</a> in pubspec.yaml file and run flutter pub get.</p><p>Make a new screen where you need to display the data scraped (HomePage in my case).</p><p>Add these codes in the initState method your HomePage()</p><pre>late WebViewController _controller;<br>  String? message;<br></pre><pre> @override<br>  void initState() {<br>    _controller = WebViewController()<br>      ..setJavaScriptMode(JavaScriptMode.unrestricted)<br>      ..loadRequest(Uri.parse(&quot;https://niravko.com&quot;))<br>      ..addJavaScriptChannel(&quot;myChannel&quot;,<br>          onMessageReceived: (JavaScriptMessage message) {<br>        setMessage(message.message);<br>      })<br>      ..setNavigationDelegate(<br>        NavigationDelegate(<br>          onPageFinished: (String url) {<br>            injectJavascript(_controller);<br>          },<br>        ),<br>      );</pre><pre>    super.initState();<br>  }</pre><p>You need to initialize the web controller with the above properties. To run the JavaScript you need to set JavaScript mode as unrestricted with setJavascriptMode(JavaScriptMode.unrestricted) and to listen to the message that is to be passed via running JavaScript to the Flutter app, you need to add a JavaScript channel with some name and you can receive the message that is passed via JavaScript code.</p><p>The setMessage function sets the message variable with the String passed through JavaScript.</p><pre>setMessage(String javascriptMessage) {<br>    if (mounted) {<br>      setState(() {<br>        message = javascriptMessage;<br>      });<br>    }<br>  }</pre><p>Inside the injectJavaScript function, We need to run the JavaScript code that we were running earlier in the browser. The only additional thing to the previous code is we need to notify our JavaScript channel i.e. myChannel with the message in String form i.e. myChannel.postMessage(message) is enough to send a message to the channel that we set up earlier.</p><pre>injectJavascript(WebViewController controller) async {<br>    controller.runJavaScript(&#39;&#39;&#39;<br>   const items = Array.from(document.getElementsByClassName(&quot;Post_title__MJ8Hr __className_ff0aba&quot;));<br>   function getTitle(data){<br>        return data.textContent.trim();<br>    }<br>    const titleList = items.map(getTitle);<br>    //nameList is the list of titles that we scraped.<br>    myChannel.postMessage(JSON.stringify(titleList));<br>&#39;&#39;&#39;);<br>  }</pre><p>The basic flow is that once the website is rendered completely, the channel is set up and the JavaScript code is run and when myChannel.postMessage is triggered, then setMessage function is triggered and the message variable is set with the titleList in String form.</p><p>Now to display the fetched title list, we can add the following code in the build method of HomePage.</p><pre>@override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: message == null<br>          ? const Center(<br>              child: CircularProgressIndicator(),<br>            )<br>          : Builder(<br>              builder: (context) {<br>                List&lt;dynamic&gt; items = jsonDecode(message!);<br>                return ListView.builder(<br>                  itemCount: items.length,<br>                  itemBuilder: (context, index) {<br>                    return ListTile(<br>                      title: Text(items[index]),<br>                    );<br>                  },<br>                );<br>              },<br>            ),<br>    );<br>  }</pre><p>Now, the result will be displayed as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*PApuBXX-bkOLZ-FzMGjPDQ.jpeg" /></figure><p>And you’re done :)</p><p>The full source code is available at: <a href="https://github.com/ankeet7x/javascript_injection_in_flutter_webview">https://github.com/ankeet7x/javascript_injection_in_flutter_webview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d65a93f2a6ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Change Theme in Flutter using BLOC]]></title>
            <link>https://medium.com/@bikramtej3/change-theme-in-flutter-using-bloc-fbace1e9d65b?source=rss-16046549f28b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbace1e9d65b</guid>
            <dc:creator><![CDATA[Ankeet Karki (Tej Bikram)]]></dc:creator>
            <pubDate>Sun, 25 Dec 2022 07:02:34 GMT</pubDate>
            <atom:updated>2022-12-25T07:02:34.051Z</atom:updated>
            <content:encoded><![CDATA[<p>As a user of any application, We try to switch between the themes and choose which the theme that we like the most and as a mobile app developer, We should give our application users a flexibility to switch between themes which improves user experience.</p><p>Here, We’re going to learn theme switching using Bloc as state management.</p><p>First, create a new app using flutter create appname and open it in IDE of your preference.</p><p>Well, in your pubspec.yaml file add</p><pre>shared_preferences: ^2.0.15<br>  flutter_bloc: ^8.1.1</pre><p>Flutter bloc is for state management while shared preferences is for saving theme locally so that while opening app next time, we can check which theme is activated and then set the theme.</p><p>Add a new extension bloc from store in your IDE and then right click the lib folder and then click option and then new bloc and then give the bloc a name of the theme. A new folder with the name theme_bloc will be generated.</p><p>Now remove theme_state file from the folder and you’ll get this folder file structure and also a few errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/0*E8kan9L3PNK7trBP.png" /></figure><p>Now, go to theme_bloc.dart file and you&#39;ll see errors in ThemeState as theme state is not recognized since we&#39;ve removed the file. Replace that ThemeState by ThemeData. Import necessary imports and remove unrecognized and unnecessary imports. You&#39;ll get this:</p><pre>class ThemeBloc extends Bloc&lt;ThemeEvent, ThemeData&gt; {<br>        ThemeBloc() : super(ThemeData.light()) {<br>         on&lt;ThemeEvent&gt;((event, emit){});<br>        }</pre><p>Now, our ThemeBloc’s state will be of ThemeData type i.e. when we emit state in this bloc, we’ll have to emit state in for ThemeData.light(), ThemeData.dark(), etc.</p><p>Now in theme_event.dart file add two events. ThemeSwitchEvent and InitialThemeSetEvent extending ThemeEvent like this:</p><pre>part of &#39;theme_bloc.dart&#39;;</pre><pre>  @immutable<br>  abstract class ThemeEvent {}</pre><pre>  class InitialThemeSetEvent extends ThemeEvent {}</pre><pre>  class ThemeSwitchEvent extends ThemeEvent {}</pre><p>Now, We’re going to handle the logic in theme_bloc.dart file as per our event. Firstly, let&#39;s work on ThemeSwitchEvent. The main use case is: When a user clicks a switch that is used to change the theme, we need to add this event. And when this event is triggered, we need to check what theme is currently activated and we need to change the theme to dark if the light is activated currently and to light, if dark is activated We&#39;ll also need to add certain values to shared preferences in such a way that we can identify what theme is currently activated in the app so that when the user restarts the app, we can activate that theme initially. This initial theme setting logic is handled by the InitialThemeSetEvent.</p><p>Now, create a file theme_helper.dart just to add two functions to set bool value in shared preferences with key &quot;is_dark&quot; that keeps a value true if the theme is dark and false if the theme is true.</p><p>In theme_helper.dart file add these two functions:</p><pre>Future&lt;bool&gt; isDark() async {<br>    final SharedPreferences prefs = await SharedPreferences.getInstance();<br>    return prefs.getBool(&quot;is_dark&quot;) ?? false;<br>  }</pre><pre>  Future&lt;void&gt; setTheme(bool isDark) async {<br>    final SharedPreferences prefs = await SharedPreferences.getInstance();<br>    prefs.setBool(&quot;is_dark&quot;, !isDark);<br>  }</pre><p>The function isDark() which is called while opening the app returns true if the value inside the key “is_dark” is true and false if the value is false or null. The setTheme function is triggered once the theme is updated after clicking the switch i.e. on ThemeSwitchEvent.</p><p>Now, update your theme_bloc.dart a file like this to update the theme.</p><pre>class ThemeBloc extends Bloc&lt;ThemeEvent, ThemeData&gt; {<br>    ThemeBloc() : super(ThemeData.light()) {<br>      //when app is started<br>      on&lt;InitialThemeSetEvent&gt;((event, emit) async {<br>        final bool hasDarkTheme = await isDark();<br>        if (hasDarkTheme) {<br>          emit(ThemeData.dark());<br>        } else {<br>          emit(ThemeData.light());<br>        }<br>      });</pre><pre>      //while switch is clicked<br>      on&lt;ThemeSwitchEvent&gt;((event, emit) {<br>        final isDark = state == ThemeData.dark();<br>        emit(isDark ? ThemeData.light() : ThemeData.dark());<br>        setTheme(isDark);<br>      });<br>    }<br>  }</pre><p>Now the logic is handled here in theme_bloc.dart. Now you need to call the events in the app and it is necessary to understand where to call the event.</p><p>The theme your app is currently using can be switched from MaterialApp where we give theme property. So we need to provide MaterialApp with our state as our state is currently activated theme. Now, Wrap MaterialApp with BlocBuilder of ThemeBloc after clicking (Control + .)/(Command + .). In theme key of MaterialApp gives the state as value as in our ThemeBloc state means ThemeData. The result will be like this:</p><pre>class MyApp extends StatelessWidget {<br>    const MyApp({super.key});</pre><pre>    @override<br>    Widget build(BuildContext context) {<br>      return BlocBuilder&lt;ThemeBloc, ThemeData&gt;(<br>        builder: (context, state) {<br>          return MaterialApp(<br>            theme: state,<br>            debugShowCheckedModeBanner: false,<br>            home: const HomePage(),<br>          );<br>        },<br>      );<br>    }<br>  }</pre><p>Create home.dart inside lib folder and in the content of HomePage add this content: ``` import &#39;package:flutter/cupertino.dart&#39;; import &#39;package:flutter/material.dart&#39;; import &#39;package:flutter_bloc/flutter_bloc.dart&#39;; import &#39;package:theme_switcher/bloc/theme_bloc.dart&#39;;</p><p>class HomePage extends StatefulWidget { const HomePage({super.key});</p><p>@override State createState() =&gt; _HomePageState(); }</p><p>class _HomePageState extends State { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( actions: [ BlocBuilder&lt;ThemeBloc, ThemeData&gt;( builder: (context, themeData) { return CupertinoSwitch( value: themeData == ThemeData.dark(), onChanged: (bool val) { BlocProvider.of(context).add(ThemeSwitchEvent()); }); }, ), ], ), body: const Center(child: Text(“Theme changing app”)), ); } }</p><pre>The code up to here is fine and we need to give a final touch to the code. If we run the above code we&#39;ll run into an exception of Provider not found or something. This is because we&#39;ve not provided ```ThemeBloc``` to our App i.e. we need to provide our app with ThemeBloc above the place in widget tree where it is referenced.</pre><pre>Now,<br>Inside ```runApp``` method where you&#39;re calling MyApp() i.e. the root of your app where you&#39;ve declared ```MaterialApp```, you need to wrap your MyApp() like this:</pre><p>BlocProvider( create: (context) =&gt; ThemeBloc() child: const MyApp(), ) ```</p><p>If we do this, our app will run fine. The theme will also switch and the value is also set in shared preferences. Now, set the theme to dark and restart the app once, you’ll see the theme is light even though we set the theme to dark and also set the value in shared preferences. This is because we didn’t call InitialThemeSetEvent initially, while our app&#39;s starting which led to a Light theme by default as we kept the light theme as default in the theme bloc state. Now to call this, Update the above piece of code like this:</p><pre>BlocProvider(<br>      create: (context) =&gt; ThemeBloc()..add(InitialThemeSetEvent())<br>      child: const MyApp(),<br>    )</pre><p>This’ll provide a theme bloc to the app and also call InitialThemeSetEvent simultaneously. Now, We&#39;re done.</p><p>The full source code is at: <a href="https://github.com/ankeet7x/theme_switch_using_bloc">https://github.com/ankeet7x/theme_switch_using_bloc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbace1e9d65b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extension Methods in Dart/Flutter (Range Error Handling)]]></title>
            <link>https://medium.com/@bikramtej3/extension-methods-in-dart-flutter-range-error-handling-ff2529b2f85e?source=rss-16046549f28b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff2529b2f85e</guid>
            <dc:creator><![CDATA[Ankeet Karki (Tej Bikram)]]></dc:creator>
            <pubDate>Sun, 25 Dec 2022 06:55:38 GMT</pubDate>
            <atom:updated>2022-12-25T06:55:38.215Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s consider a dynamic list with a few elements.</h4><p>List myList = [&quot;mango&quot;, &quot;apple&quot;, &quot;guava&quot;];</p><p>Let’s consider you need to print the item at a specific index. For that index, we could do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*4_mxT2GUPLO-IOch.png" /></figure><p>It simply prints mango in the console.</p><p>Now, Let’s consider there existed a scenario when you need to print the item at any index including the index that might not be available in the list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*jLhsa2PJXfVHWgtZ.png" /></figure><p>In the above list, the item doesn’t exist at index 3, so if we print the item at index 3, we should get null in the console as there exists nothing at myList[3].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qs0ATrcnUgTFIDgX.jpg" /></figure><p>Uncaught Error: RangeError (index): Index out of range: index should be less than 3: 3. This error appeared in the console as we tried to access the item at the index which doesn&#39;t exist. This means that we couldn&#39;t access the index that doesn&#39;t exist expecting it to print null in the console. What if we want to print null if the item at the index doesn&#39;t exist?</p><p>We could do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*VYBcTWuJmTXuF-VV.png" /></figure><p>This code works perfectly fine. What if we want to reuse this code? It isn’t a good idea to hard-code this piece of code everywhere. What we could do is create a function that returns an item if it exists or is null.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*tFkKkjxBWFtpQUa7.png" /></figure><p>Nice, The program is running as we expected it to. Let’s assume, We need to do this multiple times with multiple lists. In the above piece of code, We passed the index and the list to the function to do the operation but should we be passing the list everywhere? What if we don’t want to pass the list?</p><p>That’s where the extension method comes in. According to the extension method definition in Dart documentation, Extension methods, introduced in Dart 2.7, are a way to add functionality to existing libraries. They can be defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/0*qlDVs9eyyqnpQwRO.png" /></figure><p>Here, we need to add functionality to the list i.e. we need to print items at index or null. Since the List is of type Iterable, we can create an extension on Iterables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/0*F0wrlQ5yeSOGgYgf.png" /></figure><p>Now, the question “How to implement this ?” arises. Well, It’s easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bRDlIIAqhbfOuq3g.png" /></figure><p>After clicking the dot after a specific list, The suggestion of itemAtIndexOrNull automatically shows up and we pass the required index and we&#39;re done.</p><p>The complete source code is:</p><p>extension ItemAtIndexOrNull&lt;T&gt; on Iterable&lt;T&gt; { <br> itemAtIndexOrNull(int index) {<br> if (length &gt;= index + 1) {<br> return elementAt(index);<br> } else {<br> return null;<br> }<br> }<br> }</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff2529b2f85e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>