Home Blog Page 58

Android emulator was killed – ERROR SOLUTION

0
Android emulator was killed
Android emulator was killed

Hi Guys, Welcome to Proto Coders Point.

So, I just tried starting AVD Android Emulator but what was actually happening is, when i start Emulator it was showing connecting to the emulator & suddenly it showed android emulator was killed.

Then, i tried some solution from stackoverflow and found a solution that worked for me. so just thought to share about this to you.

So here are some solution you need to try. The Solution 1 worked for me.

Solution 1: Check your drive free space( This worked for me)

I have a SSD drive, where my windows OS is installed & Android Studio is allso installed in SSD for fast loading with Emulator.

Android Studio Emulator consume atleast 8 GB of space in C: drive, Then if there is no space in C: drive & you try to start Android emulator then due to low storage, android emulater will kill itself.

Please check drive C:, it should have atleast 10 GB of free memory for emulator to run smoothly.


Solution 2: intel x86 Emulator Accelerator update

Check if you have installed ‘‘intel x86 Emulator Acceleration” SDK tools, if YES check if it updated else just install it and keep it up-to-date.

Android-Studio > Tools > SDK Manager > SDK Tools(Tab) > tick [intel x86 Emulator Accelerator(HAXM installer)] and update it.
android studio install intel x86 emulator accelerator

Solution 3: Install/Update Android Emulator SDK tools

There might be some issue if you are using lower version of SDK tools Android Emulator =, so kindly be updated with latest version of android Emulator.

Android-Studio > Tools > SDK Manager > SDK Tools(Tab) > tick [Android Emulator] and update it
android emulator sdk tools install

final and const keyword in dart – what’s difference

0
final and const keyword in dart
final and const in flutter dart

Hi Guys, Welcome to Proto Coders Point, In this dart tutorial we will learn what is the difference between final and const keyword in flutter dart.

Even dart programming language support assigning a constant value to a dart variable, Here constant value means once a value is assigned to the variable then it cannot be altered/changed.

There are 2 keywords used to declare constant variable in dart:

  1. const keyword.
  2. final keyword.

Const Keyword in dart

The const keyword in dart, are similar to final keyword but, The only different between const & final is, In const variable initialization can only be done during compile-time, means a variable value cannot be initialized at run-time.

Example: 
String name;

//get input to name from user
name = stdin.readLineSync();

//you will get error; doing this
const copyname = name; //error

In Simple words, by using const keyword you cannot take input from user and then assign to const variable in run-time. but by using const you can assign value directly at compile-time only.

Example:
const number = 85785;
// later this can't be changed; like this
number = 854; // cant do this


When to use const keyword

Suppose you have a value that will never alter or should not be changed during run-time. Eg: A String ‘ProtoCodersPoint’ will always be same for a app name, but if you are integrating a time in your app then const should not be used for currect time because it keep change every milli seconds.


final keyword in dart

In final keyword, the only different i we can assign a value to final variable at run-time(but only once), that means we can assign value to final keyword by taking manual input from user, but once value is been assigned then cannot be altered.

Example

final int? number;

number = int.parse(stdin.readLineSync());

Print(number);
//Now number is already assigned.
//then it can’t be altered again like this;

number = 100; // Error: Not Possible to change the value.


Example on final & const keyword

void main(){
     finalvariable(500);
     constvariable(5);
}

void finalvariable(int value){
  final finalvariable = value;
  print(finalvariable);

   //finalvariable = 5000; // this is not possible
}
void constvariable(int value){

  const directinit = 100;
  print(directinit);
 // const variableconst = value; // after compile time, initializing value to const variable is not possible

}

What is ArmStrong Number | ArmStrong Program in dart

0
what is armstrong number - dart program to check armstring number
what is armstrong number - dart program to check armstring number

Hi Guys, Welcome to Proto Coders Point. In this dart tutorial we will learn what is Armstrong number & then let’s write a dark program to check if a given number is a armstrong number or not.

This are the basic program been asked in most of the coding interviews so freshers who are applying for job must know armstring program.

What is Armstrong number

A Armstrong number, when each of its digits is raised to the power, number of digits in a number & the sum of it will be same as the number is called as armstrong number.

Eg: Let's take a number '370'.
  
370, so we have 3 digit number, therefore, each of its digits in 370 will have power of 3.

370 = 33 + 73 + 03
       = 27 + 343 + 0
       = 370
 It's a ArmStrong Number

Let’s Take one more Example(Not an Armstrong)

Let a Number be  '1234'

1234, so it is a 4 digit armstrong number to be checked ok. Therefore each digit in 1234 will have power as 4.

1234 = 14 + 24 + 34 + 44
= 1 + 8 + 81 + 256
1234 != 346

It's not a Armstrong number.

Armstrong are also called as plus perfect or Narcissistic number.

Few Example on armstrong number

1: 11 = 1

2: 21 = 2

3: 31 = 3

371: 33 + 73 +13 = 371

407 = 43 + 03 + 73 = 407

1634: 14 + 64 + 34 + 44 = 1 + 1296 + 81 + 256 = 1643

8208 = 84 + 24 + 04 +84 =8208

Armstrong number program in dart

The following program will check if the given number is armstrong number or not.

import 'dart:io';
import 'dart:math';
void main(){
  
  int? num;
  print('Enter A Number to check ARMSTRONG or NOT ARMSTRONG NUMBER');
  // user will enter a number to check
  num = int.parse(stdin.readLineSync()!);
 
  // user entered number is passed to function
  isArmString(num);

}

//a function to check arm strong
void isArmString(int number){
  //initial some variable
  int temp,digits =0, last = 0, sum = 0;

  //assign user entered number to temp variable
  temp = number;

// loop execute until temp is 0 and increment digits by 1 each loop
  while(temp>0){
    temp = temp~/10;
    digits++;
  }

  //reset temp to user entered number
  temp = number;

  //another loop for getting sum
  while(temp>0){
    last = temp % 10;
    sum = sum + pow(last, digits) as int;
    temp = temp~/10;   
  }

   // now if number and sum are equal its a arm strong number
  if(number == sum){
    print("IT'S A ARMSTRONG NUMBER");
  }else{
    print("IT'S NOT ARMSTRONG NUMBER");
  }
}

Result output

dart armstrong program output
dart armstrong program output

The below Dart Program will print all the ArmString number from 0 to specified input by user.

import 'dart:io';
import 'dart:math';
void main(){
  
  int? num;
  print('Enter A Number to check ARMSTRONG or NOT ARMSTRONG NUMBER');
  // user will enter a number to check
  num = int.parse(stdin.readLineSync()!);
 
  // user entered number is passed to function
  print('________________________________________-');
  for(int i = 0;i<=num;i++)
  {
     //if i is arm strong then print it else don't
     if(isArmString(i))
     {
       print(i);
     }
  }
  

}

//a function to check arm strong
bool isArmString(int number){
  //initial some variable
  int temp,digits =0, last = 0, sum = 0;

  //assign user entered number to temp variable
  temp = number;

// loop execute until temp is 0 and increment digits by 1 each loop
  while(temp>0){
    temp = temp~/10;
    digits++;
  }

  //reset temp to user entered number
  temp = number;

  //another loop for getting sum
  while(temp>0){
    last = temp % 10;
    sum = sum + pow(last, digits) as int;
    temp = temp~/10;   
  }

   // now if number and sum are equal its a arm strong number
  if(number == sum){
    return true;
  }else{
    return false;
  }
}

result output

print arm strong number from range specified


Recommended Dart programs

How to generate random number in dart

pattern program in dart

palindrome program in dart

String to ASCII in dart

Fibonacci sequence in dart

prime number program in dart

GetX Flutter check internet connection – Connectivity – State Management

0

Hi Guys, Welcome to Proto Coders Point.

In this Flutter tutorial(Article) we will learn how to check internet connection continuously in flutter by using flutter connectivity package & implement network change state management using Flutter GetX package.

About flutter connectivity package

This plugin is very useful if your app need internet connection to run the application perfectly, This Library allows your flutter Application to Discover Network Connectivity. This Flutter Library will also check if your  mobile is currently using cellular mobile data  or is using WiFi Connection.

This Flutter Plugin Perfectly works for Both Android and iOS devices, So it is been rated with 100 points in Flutter Library Store.

Video Tutorial


Flutter check internet connection using Connectivity and GetX State management package

Project Files Structure of references

Note: In File Structure, ‘generated_plugin_registrant.dart’ get automatically created when you add below dependencies. You no need to create it.

1. Add Dependencies

dependencies:
  get:
  connectivity:

As we know, we need 2 packages i.e. Flutter GetX and Flutter connectivity.

Flutter GetX: To implement State Management, suppose if Internet Connection changed, to update the state of app and tell about the network change by updating UI screen of users.

Flutter Connectivity: This package plugin helps to check connectivity, if you are connected to WIFI or Mobile Data or if flutter no internet connection. Note: Connectivity plugin has stopped further updated, so Kindly use Connectivity_plus. Don’t worry code is same as it is in Connectivity plugin.

2. GetX State management- flutter check internet connection

Now, Create a dart file in lib directory of your flutter project.

I have created the file and named it as ‘GetXNetworkManager.dart’

GetXNetworkManager.dart

This Class manager all the network related task such as checkConnectivity, ConnectivityResult weather your mobile is connected to WIFI, Mobile Data, or no Internet connection.

import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

class GetXNetworkManager extends GetxController
{
   //this variable 0 = No Internet, 1 = connected to WIFI ,2 = connected to Mobile Data.
   int connectionType = 0;

   //Instance of Flutter Connectivity
   final Connectivity _connectivity = Connectivity();

   //Stream to keep listening to network change state
   late StreamSubscription _streamSubscription ;

  @override
  void onInit() {
     GetConnectionType();
     _streamSubscription = _connectivity.onConnectivityChanged.listen(_updateState);
  }

  // a method to get which connection result, if you we connected to internet or no if yes then which network
   Future<void>GetConnectionType() async{
    var connectivityResult;
    try{
      connectivityResult = await (_connectivity.checkConnectivity());
    }on PlatformException catch(e){
      print(e);
    }
    return _updateState(connectivityResult);
   }

   // state update, of network, if you are connected to WIFI connectionType will get set to 1,
   // and update the state to the consumer of that variable.
   _updateState(ConnectivityResult result)
   {
     switch(result)
     {
       case ConnectivityResult.wifi:
               connectionType=1;
               update();
               break;
       case ConnectivityResult.mobile:
         connectionType=2;
         update();
         break;
       case ConnectivityResult.none:
         connectionType=0;
         update();
         break;
       default: Get.snackbar('Network Error', 'Failed to get Network Status');
       break;

     }
   }

  @override
  void onClose() {
    //stop listening to network state when app is closed
     _streamSubscription.cancel();
  }
}

3. Getx initial Binding

Now, create one more dart file for bindings between GetXNetworkManager.dart and main.dart.

I have create it and named it as ‘NetworkBinding.dart’

This dart file, class extends Bindings & must have a @override method i.e. Dependenies(), which will then load our GetXNetworkManager class by using Get.LazyPut().

import 'package:get/get.dart';
import 'package:getx_check_internet/GetxNetworkManager.dart';

class NetworkBinding extends Bindings{

  // dependence injection attach our class.
  @override
  void dependencies() {
    // TODO: implement dependencies
    Get.lazyPut<GetXNetworkManager>(() => GetXNetworkManager());
  }

}

4. main.dart file

In main.dart file , instead of simple MaterialApp, we are using GetMaterialApp, inside it we are using a property called as initialBinding that then invoke GetXNetworkManager class.

Then in stateful widget, we create an Instance of GetXNetworkManager(GetXController) class so that we can use properties of GetXNetworkManager from main.dart.

main.dart

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_check_internet/GetxNetworkManager.dart';
import 'package:getx_check_internet/NetworkBinding.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      //Initiate Bindings we have created with GETX
      initialBinding: NetworkBinding() ,
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {


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

class _MyHomePageState extends State<MyHomePage> {

  // create an instance
  final GetXNetworkManager _networkManager = Get.find<GetXNetworkManager>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Network Status',style: TextStyle(fontSize: 20),),
            //update the Network State
            GetBuilder<GetXNetworkManager>(builder: (builder)=>Text((_networkManager.connectionType == 0 )? 'No Internet' : (_networkManager.connectionType == 1) ? 'You are Connected to Wifi' : 'You are Connected to Mobile Internet',style: TextStyle(fontSize: 30),)),

          ],
        ),
      ),
    );
  }
}


Output


Palindrome program in dart – Check if Number, String is palindrome or not

0
palindrome program in dart
palindrome program in dart

Hi Guys, Welcome to Proto Coders Point.

In this dart programming article, we will learn what is a palindrome, A dart Programs on “how to check if a number is palindrome”, “check if string is palindrome or not”.

What is a Palindrome – number, string

Palindrome meaning(defination), A Number or a string when reversed looks same and pronounced same as it was before reversing.

For Example: 656 when reversed will be same, ( it’s a palindome number), 657 when reversed is 756 so ( it’s not a palindrome number). like wise 252,25252,49694.

String Example for palindrome: NITIN, MADAM, ABBA, MAM, STRAW WARTS, DAMMIT IM MAD.

Palindrome Number algorithm – Code Work flow

  1. Get a number to check if palindrome or not.
  2. Store the same number, in temp variable.
  3. Reverse number using mathematical operation or string methods.
  4. Now compare temp variable with the reversed number value.
  5. If both number match ‘Then it’s a palindrome number’
  6. Else ‘Not a Palindrome Number’

Now Let’s see a palindrome number program in dart language.

void main(){
  int reminder, sum =0, temp;
  int number = 54545;

  temp = number;

  // a loop to reverse a number
  while(number>0)
  {
    reminder = number % 10;  //get remainder
    sum = (sum*10)+reminder;
    number = number~/10;
  }
  
  if(sum == temp)
  {
    print('Its A Palindrome number');

  }else{
    print('Its A Not Palindrome number');
  }


 // StringNumber();
}
palindrome number output
not a palindrome number

Palindrome program in dart programming language (Another way)

Here in below dart program, A user can input either a number or string to check for palindrome or not.

Here we are accepting a input from a user and then reverse the string and then matching them.

How to reverse a string in dart

stringValue!.split('').reversed.join('')
import 'dart:io';
void main(){
print('Enter Words or number');
    // User enter a string or a number
    String? original =  stdin.readLineSync();
  
   // then we will reverse the input
   String? reverse = original!.split('').reversed.join('');

  // then we will compare
  if(original == reverse)
  {
    print('Its A Palindrome');

  }else{
    print('Its A Not Palindrome');
  }
 
}
check is given input is palindrome or not a palindrome

Recommended dart basic programs

Generate random number in dart

String to ASCII in dart

Pattern Program in dart

Fibonacci program in dart

prime number program in dart

Learn dart basic programs

How to make a Count Down Timer in flutter dart

0
flutter count down timer
count down timer in flutter

Hi Guys, Welcome to Proto Coders Point.

In this flutter tutorial, we will implement a count down timer in flutter application using Timer Class of dart language.

Note: In this tutorial, we will cover 2 ways to implement count down timer flutter.

  1. Count-down timer using setState() to update Timer Value.
  2. Count-down timer using Getx StateManagement to update Timer Value.

If you are android developer, I have written a tutorial with source code for implementing count down timer in android app.

How we will use Timer Class in flutter

We are going to make use of dart Timer Class with periodic function to implement CountDownTimer. A Timer Class can we used to make count down in flutter app.

use a periodic timer to repeatedly loop in same interval time. Inside Timer.periodic set a fixed interval duration so that a loop runs exactly at a duration as defined.

Example: Snippet code

Timer _timer = Timer.periodic(Duration(seconds: 1), (timer) {
       
   // The Inner Block works Exactly after every 1 second as defined.
   
   // You can perform  variable count down here

   // Important, you need to Stop the Timer loop when you want to end it Eg: when value = 0
   _timer.cancel(); // will stop it

    });


1. Implementation of Count Down Timer using setState to update the Timer Value

Video Tutorial

main.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_timer/ByGetXStatemanagement.dart';
import 'package:flutter_timer/BySetState.dart';
import 'package:flutter_timer/CountDownTimerState.dart';
import 'package:get/get.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(
              height: 10,
            ),
            ElevatedButton(
                onPressed: () {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (build) => BySetState()));
                },
                child: Text('Count Down Timer using setState ();')),
            SizedBox(
              height: 30,
            ),
            ElevatedButton(
                onPressed: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (build) => ByGetXStateManagement()));
                },
                child: Text('Count Down Timer using GetX StateManagement')),
          ],
        ),
      ),
    );
  }
}

BySetState.dart

import 'dart:async';

import 'package:flutter/material.dart';

class BySetState extends StatefulWidget {
  @override
  _BySetStateState createState() => _BySetStateState();
}

class _BySetStateState extends State<BySetState> {
  int _counter = 10;
  late Timer _timer;

  void _startTimer() {
    _counter = 10;
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_counter > 0) {
        setState(() {
          _counter--;
        });
      } else {
        _timer.cancel();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Count Down Timer using SetState to keep updating'),
            SizedBox(
              height: 20,
            ),
            Text(
              '$_counter',
              style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
            ),
            SizedBox(
              height: 10,
            ),
            ElevatedButton(
                onPressed: () {
                  _startTimer();
                },
                child: Text('Start Timer')),
            SizedBox(
              height: 10,
            ),
            ElevatedButton(
                onPressed: () {
                  _timer.cancel();
                },
                child: Text('Pause')),
            SizedBox(
              height: 10,
            ),
            ElevatedButton(
                onPressed: () {
                  setState(() {
                    _timer.cancel();
                    _counter = 10;
                  });
                },
                child: Text('Reset'))
          ],
        ),
      ),
    );
  }
}
count down timer gif


2. Implementing Count down timer using GetX StateManagement to update Timer Value

Video Tutorial (GetX State Management Example by implementing Count Down Timer)

#Soon

Create a Statemanagement dart class ‘CountDownTimerState.dart’.

CountDownTimerState.dart

import 'dart:async';
import 'package:get/get.dart';

class CountDownTimerState extends GetxController{
  // Initial Count Timer value
  
  var SCount = 10;
  
  //object for Timer Class
  late Timer _timer;

  // a Method to start the Count Down
  void StateTimerStart(){
     //Timer Loop will execute every 1 second, until it reach 0
    // once counter value become 0, we store the timer using _timer.cancel()
    
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {

      if(SCount > 0){
        SCount--;
        update();
      }else{
        _timer.cancel();
      }
    });
  }

  // user can set count down seconds, from TextField
  void setnumber(var num){

        SCount = int.parse(num);
        update();

  }

  // pause the timer
  void Pause(){
    _timer.cancel();
    update();
  }

  // reset count value to 10
  void reset(){
    _timer.cancel();
    SCount = 10 ;
    update();
  }

}

ByGetXStatemanagement.dart

import 'package:flutter/material.dart';
import 'package:flutter_timer/CountDownTimerState.dart';
import 'package:get/get.dart';

class ByGetXStateManagement extends StatefulWidget {
  @override
  _ByGetXStateManagementState createState() => _ByGetXStateManagementState();
}

class _ByGetXStateManagementState extends State<ByGetXStateManagement> {
  final CountDownTimerState TimerState = Get.put(CountDownTimerState());

  final _textEditingController = TextEditingController();

  @override
  void initState() {
    _textEditingController
        .addListener(() => TimerState.setnumber(_textEditingController.text));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Count Down Timer using GetX State management'),
            SizedBox(
                height: 40,
                width: 130,
                child: TextField(
                  controller: _textEditingController,
                  minLines: 1,
                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(10)))),
                )),
            GetBuilder<CountDownTimerState>(
                builder: (_) => Text('${TimerState.SCount}')),
            ElevatedButton(
                onPressed: () {
                  TimerState.StateTimerStart();
                },
                child: Text('Start Getx State Timer')),
            SizedBox(
              height: 20,
            ),
            ElevatedButton(
              onPressed: () {
                TimerState.Pause();
              },
              child: Text('Pause'),
            ),
            SizedBox(
              height: 20,
            ),
            ElevatedButton(
              onPressed: () {
                TimerState.reset();
              },
              child: Text('Reset'),
            ),
          ],
        ),
      ),
    );
  }
}

Recommended Flutter Tutorial Articles

Learn State Management

Flutter Provider – State management

Basic of GetX package

Dark & Light Theme using GETX