Home Blog Page 15

Dynamic cached fonts in Flutter

0
flutter dynamic cache fonts
flutter dynamic cache fonts

Dynamically cached fonts offer the ability to load and cache any font from any URL as needed. follow this technique helps reduce the bundle size of your application by allowing fonts to be loaded on-demand. By dynamically fetching fonts from external sources you can optimize your web performance and enhance user experience.

Because the font will only need to be downloaded once and used numerous times, caching improves performance while using less network and battery power.

How to Integrate Dynamic Cached Fonts in flutter app

To use the package, add dynamic_cached_fonts as a dependency.

Get started…

Installation.

Step 1): Add this following dependencies project pubspec.yaml file:

dynamic_cached_fonts: ^any

Step 2): Then import it after installing the package using the terminal’s command line:

flutter pub get

Step 3): import the file

import 'package:dynamic_cached_fonts/dynamic_cached_fonts.dart';

Loading the flutter dynamic cached fonts on page…

When a page loads, for instance, you can load a font on demand.

@override
void initState() {
  final DynamicCachedFonts dynamicCachedFont = DynamicCachedFonts(
    fontFamily: fontFamilyName, // The font family name to be passed to TextStyle.fontFamily
    url: fontUrl, // A valid url pointing to a font file (.ttf or .otf files only) 
  );
  dynamicCachedFont.load(); // Downloads the font, caches and loads it.

  super.initState();
}
...
Text(
  'Some Text',
  style: TextStyle(fontFamily: fontFamilyName),
)

Load the font , when button click

onPressed: () {
    final DynamicCachedFonts dynamicCachedFont = DynamicCachedFonts(
      fontFamily: fontFamilyName,
      url: fontUrl,
    );

    dynamicCachedFont.load();
  },

Pass in maxCacheObjects and cacheStalePeriod to alter the size of the cache or perhaps the length of time the font remains in cache.

DynamicCachedFonts(
  fontFamily: fontFamilyName,
  url: fontUrl,
  maxCacheObjects: 150,
  cacheStalePeriod: const Duration(days: 100),
);

TextStyle.fontOnly after load() is called are families applied.

What if you need to load several fonts, each with a different weight and style?The DynamicCachedFonts.family constructor can be used for that.

Incorporating a list of URLs directing users to various fonts within the same family enables the utilization of dynamically cached fonts. This approach allows for the dynamic loading and caching of fonts as required. By leveraging this functionality you can effectively reduce the overall size of your bundle while enabling the loading of fonts ondemand based on specific user needs. This approach enhances performance and optimizes user experience by seamlessly integrating range of fonts from different sources within cohesive font family.

DynamicCachedFonts.family(
  urls: <String>[
    fontFamilyNameBoldUrl,
    fontFamilyNameItalicUrl,
    fontFamilyNameRegularUrl,
    fontFamilyNameThinUrl,
  ],
  fontFamily: fontFamilyName,
);

Make use of the static methods if you require more control!

onPressed: () {
  DynamicCachedFonts.cacheFont(fontUrl);
},

The cacheStalePeriod and maxCacheObjects parameters are also available .

loadCachedFont , loadCached , canLoadFontFamily canTo see if the font is cached use the LoadFont method . It frequently works in tandem with the loadCached methods.

Before attempting to load a font, it is advisable to first check if the font is already cached . By verifying the font’s presence in the cache, you can avoid unnecessary network requests. If the font is indeed cached, you can proceed to activate it, ensuring a swift and seamless rendering of the font. This proactive approach optimizes the font loading process by efficiently utilizing the cached resources, resulting in improved performance and a smoother user experience.

if(DynamicCachedFonts.canLoadFont(fontUrl)) {
  // To load a single font...
  DynamicCachedFonts.loadCachedFont(
    fontUrl,
    fontFamily: fontFamilyName,
  );

  // Or if you want to load multiple fonts as a family...
  DynamicCachedFonts.loadCachedFamily(
    <String>[
      fontFamilyNameBoldUrl,
      fontFamilyNameItalicUrl,
      fontFamilyNameRegularUrl,
      fontFamilyNameThinUrl,
    ],
    fontFamily: fontFamilyName,
  );
}

Now, download the font if it isn’t already there in cache!

if(DynamicCachedFonts.canLoadFont(fontUrl)) {
 /// do code here
} else {
  DynamicCachedFonts.cacheFont(fontUrl);
}

RemoveCachedFont

To extend the functionality of RawDynamicCachedFonts and modify the implementation of static methods including the addition of removeCachedFont to permanently remove a font from the cache.

Do you want to load a specific font from Firebase Cloud Storage? Choose the constructor DynamicCachedFonts.fromFirebase! Google Cloud Storage locations with urls beginning with gs:// are accepted. It is similar to the default constructor aside from that.

This implementation file code is shown here;

import 'package:dynamic_cached_fonts/dynamic_cached_fonts.dart';
import 'package:flutter/material.dart';
import 'constants.dart';
import 'src/components.dart';
import 'src/demos.dart';

void main() {
  DynamicCachedFonts.toggleVerboseLogging(true);

  runApp(
    MaterialApp(
      title: 'Dynamic Cached Fonts Demo',
      home: const DynamicCachedFontsDemo1(),
      darkTheme: ThemeData.dark(),
    ),
  );
}

class DynamicCachedFontsDemo1 extends StatefulWidget {
  const DynamicCachedFontsDemo1({Key? key}) : super(key: key);

  @override
  _DynamicCachedFontsDemo1State createState() => _DynamicCachedFontsDemo1State();
}

class _DynamicCachedFontsDemo1State extends State<DynamicCachedFontsDemo1> {
  @override
  void initState() {
    final DynamicCachedFonts dynamicCachedFont = DynamicCachedFonts(
      fontFamily: cascadiaCode,
      url: cascadiaCodeUrl,
    );
    dynamicCachedFont.load();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(demoTitle),
      ),
      body: const Center(
        child: DisplayText(
          'The text is being displayed in $cascadiaCode which is being dynamically loaded and cached',
          fontFamily: cascadiaCode,
        ),
      ),
      floatingActionButton: ExtendedButton(
        icon: Icons.navigate_next,
        label: 'Next Example',
        onPressed: () => Navigator.push(
          context,
          MaterialPageRoute<DynamicCachedFontsDemo2>(
            builder: (_) => const DynamicCachedFontsDemo2(),
          ),
        ),
      ),
    );
  }
}

For this example code click here Github

Conclusion 👍

While the system fonts on Android and iOS are of a high caliber, designers frequently ask for custom fonts.This is a small example of dynamic cached fonts implemented in flutter , you can modify with your needs..

Thanks for reading this article 💙

Have a good day


Recommended Articles

Flutter Google Font’s Package

How to repair or clean cache of all dependencies in flutter

Icons in flutter – font awesome

Play YouTube Video in Flutter

0
flutter youtube video player
flutter youtube video player

Loading videos into flutter application youtube_player_flutter is one of the most popular packages that is been used to play youtube video into flutter app by development. Developers can easily play YouTube videos in their Flutter applications using the widget provided by this flutter package. The youtube_player_flutter package wraps the official YouTube Player API for Android and iOS, making it easy to integrate YouTube videos into your Flutter application.

Building useful user interfaces for mobile apps is made simple by Flutter’s selection of pre-built widgets and tools. Additionally, It has a feature called hot-reload that enables developers to view changes they make to their app immediately without having to restart it.

Introduction youtube_player_flutter

As I said to integrate youtube videos we will make use of flutter package, It is an easy-to-use straightforward package that provides a variety of video players with customizability options. The application is based on the official YouTube iFrame flutter embedded Player API. which provides users with access to a variety of features for controlling and playing back YouTube videos.

Integration into Flutter Project

Create a new Flutter Project or open existing on where you want to integrate youtube video, Open the Project into your favorite IDE (Android Studio, VSCode, InteliJ…).

Step 1: Include the package youtube_player_flutter

Open pubspec.yaml file and under dependencies section add the package.

youtube_player_flutter:^any

Step 2: You can then run the following command to install the desired package:

flutter pub get

Step 3:  Import the package

Now, to use the youtube video widget, you need to import the dart class as shown below.

import 'package:youtube_player_iframe/youtube_player_iframe.dart';

Requirements to make the package work

Android: Set the minSdkVersion property to 17 in the build.gradle file for your app.

iOS: Swift in iOS Xcode version greater than 11.

defaultConfig {
    applicationId "package name"
    minSdkVersion 17
    targetSdkVersion 30
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}

Now, let’s get started on how to use youtube_player_flutter package

Now that our project has been set up and the youtube_player_flutter package has been added in .yaml file.

play the youTube video

1) Create a YoutubePlayerController object

2) Create a YoutubePlayer widget


Creating a YoutubePlayerController Object

The YoutubePlayerController class controls how YouTube videos playback works in our app. When creating an instance of this class we must pass YouTube video ID that we want to play.

YoutubePlayerController _controller = YoutubePlayerController(
  flags: YoutubePlayerFlags(
    autoPlay: true,
    mute: false,
  ),
);

The initialVideoId parameter of the YoutubePlayerController received the YouTube video ID that we want to play.  In the example that was provided that was made. Additionally you have set autoPlay and mute options to  true or false bool value. This means that when the player is ready the sound will turn back on and the video will either start playing or not.

How to Make a YoutubePlayer Widget

The play YouTube video in our flutter application we can create a YoutubePlayerController object and a YoutubePlayer widget . The stateful or stateless YoutubePlayer widget renders the YouTube video player in application using YoutubePlayerController object.

example,

YoutubePlayer(
            controller: _controller,
            showVideoProgressIndicator: true,
            progressIndicatorColor: Colors.blueAccent,
            topActions: <Widget>[
              const SizedBox(width: 8.0),
              Expanded(
                child: Text(
                  _controller.metadata.title,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 18.0,
                  ),
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                ),
              ),
            ],
            onReady: () {
              _controller.addListener(listener);
            },
            onEnded: (data) {},
          )

Use the YoutubePlayer widget to display the video:

Note: In addition to adding the following to your project directory AndroidManifest.xml file. you may need enable playing YouTube videos in flutter app .

<uses-permission android:name="android.permission.INTERNET"/>
<application
  android:usesCleartextTraffic="true"
  ...>
  ...
</application>

Error handling

The development of any mobile application including those that make use of the youtube_player_flutter package must include handling errors and exceptions. Although the package offers a simple method for incorporating YouTube videos into your Flutter app errors and exceptions can happen during video playback, which can negatively affect the user experience.

The youtube_player_flutter package offers a number of callbacks that can be used to detect errors , exceptions , handle them. OnPlayerError, OnPlayerStateChange, OnReady, OnEnded and OnPlaybackQualityChange are few of the callbacks.

class VideoPlayerScreen extends StatefulWidget {
  final String ?videoId;

  const VideoPlayerScreen({Key? key, @required this.videoId}) : super(key: key);

  @override
  _VideoPlayerScreenState createState() => _VideoPlayerScreenState();
}

class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
  YoutubePlayerController? _controller;

  @override
  void initState() {
    super.initState();
    _controller = YoutubePlayerController(
      initialVideoId: widget.videoId ?? "",
      flags: const YoutubePlayerFlags(
        autoPlay: true,
        mute: false,
      ),
    )
      ..addListener(listener);
  }

  void listener() {
    if (_controller?.value.errorCode != null) {
      print(_controller?.value.errorCode);
    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('YouTube Video Player'),
      ),
      body: Center(
        child: YoutubePlayer(
          controller: _controller!,
          showVideoProgressIndicator: true,
          onReady: () {
            print('Player is ready.');
          },
          onEnded: (data) {
            _controller!
              ..load(widget.videoId ?? "")
              ..play();
          },
        ),
      ),
    );
  }
}

Flutter YouTubeVideoPlayer if we want to play the specified video by using the videoId parameter of the VideoPlayerScreen widget. here we have defined in this example youTubeVideo player ID. In order to control video playback speed ,rotation , audio..

We have created the _controller instance and added a listener to handle errors and exceptions in the initState . The listener will print error codein console if one occurs during playback.

We have defined a YoutubePlayer widget in the build method that plays the specified YouTube video using the _controller instance. Additionally, callbacks for the onReady and onEnded events have been defined to address a variety of playback-related conditions.

Click here to access this YouTube player sample app code.  click here…..

Conclusion

Programmers can use the youtube_player_flutter builtin package’s widget to embed YouTube videos in Flutter applications . The widget has a variety of configuration options, including managing audio, displaying video progressValue, and autoPlaying videos.use mainly. This package controls full-screen video playback and makes it possible for users to exit full-screen mode with just one tap.

One of the main benefits of use youtube_player_flutter package is that it provides an easy way to integratation video content into your Flutter app. This package simply the process of including YouTube videos in your application and offers an extensive number of customise option using  improve the look of our videos in flutter app .

Thanks for reading this article….. ❤️

Have a nice day…..

Difference between SharedFlow, StateFlow, LiveData in kotlin

0
Kotlin LiveData, StateFlow, SharedFlow
Kotlin LiveData, StateFlow, SharedFlow

In Kotlin Language SharedFlow, StateFlow, and LiveData are classes that comes with Kotlin Coroutines library which are basically used for communication between component in android application in an asynchronous way. However, there are many key differences in terms of their functionality & use cases.

Difference between SharedFlow, StateFlow, LiveData

1. Kotlin LiveData

In Kotlin language LiveData is a Data Model Class used to hold data and is designed to continously observed by it’s UI components may be activities and fragments. Kotlin LiveData is designed to hold and keep observing data that can be attached to the lifecycle of android component such as Activity or a Fragment. In Other words LiveData automatically handles updates to the UI Component when there are active observers and stops updates when there are no active observers, this helps us in preventing memory leaks. Note that LiveData is not a component or feature of Kotlin Coroutines library. Code Example Below

2. Kotlin Stateflow

In Kotlin StateFlow is a part asynchronous event stream, non-blocking I/O Stream that updates all the subsequent states and it’s current state of the emited data to i;s observers. As I said StateFlow is also a part of Kotlin coroutines library that gives a way to handle and represent state-based data flows. In Kotline StateFlow is used in ViewModel to immediatly update when the state changes to UI components. You might be wondering StateFlow seems similar to LiveData but it offers more flexibility, specially when it is combined with coroutines, as it support you to get control over data emission and transformation. Code Example Below

3. Kotlin Sharedflow

In Kotlin SharedFlow is another way to handle asynchronous stream, non-blocking updates, but unlike as we saw in StateFlow, When a observer starts observing SharedFlow does not emit it’s current state. SharedFlow is been designed for use cases when the initial state is not critical or you can ignore it. SharedFlow is designed in such a way that it allows multiple collectors to receive the emitted values concurrently. Suppose you have multiple subscribers and you want to broadcast data to all the subscribers we can use SharedFlow in Kotlin. Code Example Below



Kotlin LiveData Example

Here is a simple example how to integrate kotlin LiveData

1. Add LiveData dependencies in your android kotlin `build.gradle` file under dependencies section:

dependencies {
    def lifecycle_version = "2.4.0-alpha03"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
}

2. Create a class of which data you want to observe:

data class User(val name: String, val age: Int)

3. Create ViewModel Class that contains a LiveData Object

class UserViewModel : ViewModel() {
    private val _user = MutableLiveData<User>()
    val user: LiveData<User> get() = _user

    fun updateUser(newUser: User) {
        _user.value = newUser
    }
}

4. Now Finally you can keep observe changes of the ‘user’ LiveData Object in your Activity

class MyActivity : AppCompatActivity() {
    private val viewModel by viewModels<UserViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel.user.observe(this, { user ->
            // Update the UI with the new user data
        })

        // Call the update function to trigger the observer
        viewModel.updateUser(User("John Doe", 30))
    }
}


Kotlin Stateflow Example

Here is a simple example how to use kotlin StateFlow into your android application:

1. Add StateFlow dependencies in your android kotlin `build.gradle` file under dependencies section:

dependencies {
    def lifecycle_version = "2.4.0-alpha03"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
}

2. Create a class of which data you want to observe:

data class User(val name: String, val age: Int)

3. Create ViewModel Class that contains a StateFlow Object:

class UserViewModel : ViewModel() {
    private val _user = MutableStateFlow(User("", 0))
    val user: StateFlow<User> get() = _user

    fun updateUser(newUser: User) {
        _user.value = newUser
    }
}

4. Now Finally you can keep observe changes of the ‘user’ StateFlow Object in your Activity or in Fragment by using coroutunes:

class MyActivity : AppCompatActivity() {
    private val viewModel by viewModels<UserViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lifecycleScope.launch {
            viewModel.user.collect { user ->
                // Update the UI with the new user data
            }
        }

        // Call the update function to trigger the observer
        viewModel.updateUser(User("John Doe", 30))
    }
}


Kotlin Sharedflow Example

Here is a simple example How to use kotlin SharedFlow into your android application:

1. Add SharedFlow dependencies in your android kotlin `build.gradle` file under dependencies section:

dependencies {
    def lifecycle_version = "2.4.0-alpha03"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
}

2. Create a class of which data you want to emit:

data class Message(val text: String)

3. Create ViewModel Class that contains a ShareFlow Object:

class MessageViewModel : ViewModel() {
    private val _messages = MutableSharedFlow<Message>()
    val messages: SharedFlow<Message> get() = _messages

    fun sendMessage(message: Message) {
        viewModelScope.launch {
            _messages.emit(message)
        }
    }
}

4. Now Finally you can keep observe and collect the emitted data/message/changes of the ‘user’ StateFlow Object in your Activity or in Fragment by using coroutunes:

class MyActivity : AppCompatActivity() {
    private val viewModel by viewModels<MessageViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lifecycleScope.launch {
            viewModel.messages.collect { message ->
                // Do something with the message
            }
        }

        // Call the send function to emit a new message
        viewModel.sendMessage(Message("Hello, world!"))
    }
}

Exploring the Power of Flutter InAppWebView

0
flutter in app webview

Hi Guy’s Welcome to Proto Coders Point.

Are you looking for a easiest way to integrate InApp WebView in Futter app? Now need to research anymore! In this Flutter Article blog, we will be exploring Flutter InAppWebView. From understanding what web views and headless web views are.

Flutter is booming now a days as it has revolutionized the way that the developers are create mobile applications as well as web, desktop using flutter frameware that too with its fast development times and excellent performance capabilities. Flutter framework has the ability to integrate webviews seamlessly into the Flutter application. Flutter_InAppWebView is a powerful package using which a flutter developer can create highly interactive and responsive web-embedded apps to show external third party website pages into flutter app itself.


What is webview in Flutter?

Support you are building a Flutter Application, and want to show a external website page into the app for this you can make use of Flutter Webview. Basically a Web View allows a developers to embed a web page into a mobile application.

What is headless WebView?

A Headless WebView, is basically a Webview that don’t display any content from the web page. Instead the website/web page content get’s loaded at background and the developers can use it to get data from the website and use it for building flutter app. This headless Webview is now a days used for web-based API’s.

Adding the InAppWebView Widget into your Flutter App

Integrating InAppWebView widget into your Flutter app is much easy then you think. Now with just a few lines of code, You can build a awesome web-embedded Flutter Application where you can load you website into flutter app.

Integrating InApp Webview in Flutter App – Example

To Add InApp Webview into flutter app we will make use of flutter_inappwebview library, This flutter package will help you to open an in-app browser window.

InAppWebView Widget Syntax

InAppWebView(
                initialUrlRequest: URLRequest(
                  url: Uri.parse("https://protocoderspoint.com/")
                ),
                onWebViewCreated: (InAppWebViewController controller){
                  inAppWebViewController = controller;
                },
                onProgressChanged: (InAppWebViewController controller , int progress){
                  setState(() {
                    _progress = progress / 100;
                  });
                },
  ),

In InAppWebView widget there are various properties though which you can customize WebView in Flutter, Out of all those i have make used of:

initialUrlRequest: used to load a website or web page through URL.

onWebViewCreated(): This property is used to take control to the webview, Using this the flutter developer can attach a InAppWebViewController so that developer can create a controller for the webview and handle it.

onProgressChanged(): This function is been used to get the progress of how much percentage the website is loaded.


Complete Source Code Example – Flutter InAppWebView

In Below Code I have make used of a Stack Widget so that I can show a Webview and a progress indicator, Through Progress Indicator the app user can understand how much percentage of webview is loaded.

To handle webview to navigate to previous page that the user has open in the webview, I am using WillPopScope Widget to check on backpress is the webview can go back, if it can go back then go back one step to previous Web Page within the WebView.

import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class MyWebsite extends StatefulWidget {
  const MyWebsite({Key? key}) : super(key: key);

  @override
  State<MyWebsite> createState() => _MyWebsiteState();
}

class _MyWebsiteState extends State<MyWebsite> {

  double _progress = 0;
  late InAppWebViewController  inAppWebViewController;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: ()async{

        var isLastPage = await inAppWebViewController.canGoBack();

        if(isLastPage){
          inAppWebViewController.goBack();
          return false;
        }

        return true;
      },
      child: SafeArea(
        child: Scaffold(
          body: Stack(
            children: [
              InAppWebView(
                initialUrlRequest: URLRequest(
                  url: Uri.parse("https://protocoderspoint.com/")
                ),
                onWebViewCreated: (InAppWebViewController controller){
                  inAppWebViewController = controller;
                },
                onProgressChanged: (InAppWebViewController controller , int progress){
                  setState(() {
                    _progress = progress / 100;
                  });
                },
              ),
              _progress < 1 ? Container(
                child: LinearProgressIndicator(
                  value: _progress,
                ),
              ):SizedBox()
            ],
          ),
        ),
      ),
    );
  }
}

Flutter InAppWebView Example

Video Tutorial

How to change Flutter android minSdkVersion & targetSdkVersion

0
How to Change minSdkVersion & TargetSdkVersion flutter sdk
How to Change minSdkVersion & TargetSdkVersion flutter sdk

Hi Guy’s Welcome to Proto Coders Point, In this article let’s checkout how to change minSdkVersion, targetSdkVersion, compileSdkVersion of your flutter project android module, follow below steps:

Flutter Change minSdkVersion, TargetSdkVersion

Step 1: Go to path where you have kept or installed flutter sdk, or where you have extracted flutter sdk zip file, May be at path:

C:\flutter

Step 2: Follow the below path to navigate to flutter.gradle file

C:\flutter\packages\flutter_tools\gradle

Step 3: search for flutter.gradle file in gradle folder

The complete path to file “flutter.gradle” is as below:

C:\flutter\packages\flutter_tools\gradle\flutter.gradle

Open the file in any editor

In this file, There is a class “FlutterExtension” where you can change sdkversion like minSdkVersion, targetSdkVersion, compileSdkVersion ,ndkVersion.

After Changing desired SdkVersion, save the file.

Video Tutorial

Completer – Handling Future async operation using Flutter Completer

0
Completer in Flutter
Completer in Flutter

In flutter a Completer is a Class that is built to manually complete a future task at some time in future. Basically it’s a way to generate & handle your own Future.

In other words, A ‘Completer’ is an inbuilt class that comes with DART SDK that is basically used to control & manage a ‘Future’ object. A ‘Future’ in flutter we can say it as a value that will be available in future at sometime in time, May be as soon as any asynchronous operation completes.

Video Tutorial on Flutter Completer


When to use completer in flutter

Just Imagine you have ordered a package from a ECommerce Application.

Now you are waiting fro the package to arrive a your door steps.

Then you know that package will be delivered sometime in future or you may know estimate time but not sure exectly when.

In this scenerio, Let’s say Future as Package & Completer as delivery person.

Now, when the delivery person arrives at doorstep the deliver the package, The delivery person make use of Completer to complete the Future i.e The delivery person will mark the package a delivered may be using OTP.


How to use Completer in Flutter App

Syntax of Completer

Completer<dataType> _completer = Completer<dataType>();

Code Example

void main() {
 Completer<String> myCompleter = Completer<String>();

 Future<String> futureValue = myCompleter.future;

 Future.delayed(Duration(seconds: 3),(){
   myCompleter.complete("Hello World");
 });

 futureValue.then((value) {
   print(value);
 });
}

In above code example, First we create a “Completer” object that will result a “String” & then we have created a Future Object by using property i.e. myCompleter.future The futureValue will be listen for myCompleter to complete.

Then, Just for delaying operation we simulate a asynchronous operation using Future.delayed method that sleep for 3 seconds , Then after 2 second the Future.delayed async function will execute & the operation complete, we call ‘completer.complete’ and set a string value “Welcome to Proto Coders Point”, thus this sets a “futureValue” as “Welcome to Proto Coders Point”.

after that we can make use of ‘then’ method to listen for the completion & it print the value on the screen.

Flutter Code Example – How to use Completer in Flutter

In below example, App user can manually complete the completer by clicking on a button.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(title: Text("Completer Example")),
            body: FutureWidget()));
  }
}

class FutureWidget extends StatefulWidget {
  @override
  _FutureWidgetState createState() => _FutureWidgetState();
}

class _FutureWidgetState extends State<FutureWidget> {
  Completer<String> _completer;

  void _handleButtonClick() {
    // Complete the future with the user input
    _completer.complete(_textEditingController.text);
  }

  TextEditingController _textEditingController = TextEditingController();

  @override
  void initState() {
    super.initState();

    // Create the completer when the widget is initialized
    _completer = Completer<String>();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        TextField(
          controller: _textEditingController,
          decoration: InputDecoration(
            hintText: 'Enter some text',
            contentPadding: EdgeInsets.all(10.0),
          ),
        ),
        SizedBox(height: 20),
        ElevatedButton(
            onPressed: _handleButtonClick, child: Text("Complete Future")),
        SizedBox(height: 20),
        FutureBuilder(
          future: _completer.future,
          builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasData) {
                return Text("Future completed with: ${snapshot.data}");
              } else {
                return Text("Future completed with no data");
              }
            } else {
              return Text("Future not completed yet");
            }
          },
        ),
      ],
    );
  }
}