Friday, December 20, 2019

Flutter Important Points,that should we know

1) Hot Reload

You modified your code won’t to be re – executed. This codes are sent into a running Dart Virtual Machine. VM reloads all the update code and libraries. Hot – reload is update classes with new the new of functions and fileds, flutter is provide automatically rebuild, re layout the widget tree. It is allowing quickly view the effects of the changes.

Limitation of Hot – Reload in flutter

Hot – reload is not supported

enum
class used to constant value (fixed type)
Generic types


-----------------------------------------------------------------------------------------
2) key

Key is unique identifier of the widget.
Use : Two or more Container
Example: Container(key:key(”))


-----------------------------------------------------------------------------------------

3) await

Use : await only use inside the async
It is suspends currently running function until the result is completed. Result is completion pf future.

-----------------------------------------------------------------------------------------

4) Asyc

Async: Modifier
Use: Get the data from internet.
When body has executed, that returned by result, that result may be error or successful of response.


-----------------------------------------------------------------------------------------

5) FutureBuilder

It is build itself, provide the latest AsyncSnapshots. It is working one type of bridge between Futures and the UI.



-----------------------------------------------------------------------------------------

6) Media Query

Media query is depends device height and width.
var deviceSize = MediaQuery.of(context).size;


1) deviceSize.height
2) deviceSize.width


-----------------------------------------------------------------------------------------

7) Json Mapping

Parse json response came from web service.

-----------------------------------------------------------------------------------------

8) path_provider

get the location of the file as TemporaryDirectory and ApplicationDocumentDirectory.

-----------------------------------------------------------------------------------------

9) Fetures

Future objects used to Asynchronous operations.
If you sometime your bloc long time of operation perform, we did not run the code block as an async the app freeze.
Asynchronous operations let your program run without getting blocked.
For example: Shooping app


-----------------------------------------------------------------------------------------

10) BuildContext

A BuildContext is reference to the location of widgets within the tree structure of all widgets which are built.
A BuildContext only belongs to one widget.
As a State object is associated with a BuildContext, State object is not directly accessible through another BuildContext.

-----------------------------------------------------------------------------------------


11) FormState

It is used to save, reset and validate every FormField that is descendant of the associated Form.
GlobalKey to save and get from values at any time and for validating.


-----------------------------------------------------------------------------------------

12) Provider

It takes a value and expose it, whatever the value is.


-----------------------------------------------------------------------------------------

13) How to make androidx app in flutter ?

flutter create –androidx project_name


-----------------------------------------------------------------------------------------


14) SharedPreferences

SharedPreferences is used to storing data key – value pair. We can add int, String, double, List, bool using the SharedPreferences.
It is a persistent store data.

-----------------------------------------------------------------------------------------


15) App change Icon

add dependencies: flutter_launcher_icons
flutter_icons:image_path:’icon/icon.png’
android:true
ios:true
command line run
1) flutter pub get
2) flutter pub pub run
flutter_launcher_icon:main

-----------------------------------------------------------------------------------------



16) MobX Pattern

MobX is state – management library. That makes to connect the reactive data of your application with the UI. This wiring is completely automatic data feels very natural.


-----------------------------------------------------------------------------------------

17) MobX principles

1) We have access to an Observable selection of state. (i.e. variables that change over the cource of our application).
2) We can display these state items within our view and respond to Action intents.
3) We can modify the state and thus, update our Observable and corresponding views.


-----------------------------------------------------------------------------------------

18) Platform Channel

Platformm channels provide a simple mechanism for communicating between your Dart code and the platform – specific code of your host app. This means you can expose a platform service in your host app code and have it invoked from the Dart code.


-----------------------------------------------------------------------------------------

19) fromJson

Every time when we need to parse a single class object.
You can find special named constructor .fromJson which constructs class from Map. This map will be created by Dio from endpoint response.


-----------------------------------------------------------------------------------------

20) mainAxisAlignment and crossAxisAlignment?

Row
horizontal – mainAxisAlignment
vertical – crossAxisAlignment
Column
horizontal – crossAxisAlignment
vertical – mainAxisAlignment

-----------------------------------------------------------------------------------------

21) If you your project ios folder remove your application run or not?

Run your application.

-----------------------------------------------------------------------------------------


22) Type of ListView in flutter?

1) ListView.builder
2) ListView
3) ListView.separated
4) ListView.custom
5) ListView(
scrollDirection: Axis.horizontal,
children: List.generate(filterItemList.length, (index) {});


-----------------------------------------------------------------------------------------

23) ListView which property use horizontal and vertical data set?
scrollDirection
1) scrollDirection: Axis.vertical,
2) scrollDirection: Axis.horizontal,

Axis is returns horizontal or vertical.


-----------------------------------------------------------------------------------------

24) Types of gridview flutter?

1) GridView.count()
2) GridView.builder()
3) GridView.custom()
4) GridView.extend()


-----------------------------------------------------------------------------------------

25) When the state changes, widgets …….
rebuild


-----------------------------------------------------------------------------------------

26) What is the material library which contains Flutter widgets implementing Material Design?
Material.dart


-----------------------------------------------------------------------------------------

27) What type of widgets are used by Flutter to achieve Pixcel Perfect in iOS UI?
Cupertino


-----------------------------------------------------------------------------------------

28) Which type of animation allows you In – between animations?
Tweens


-----------------------------------------------------------------------------------------

29) Which type of animation allows you to represent real – world behaviour?
Physics-based


-----------------------------------------------------------------------------------------

30) Each widgets is an ……. declaration of part of the user interface?
immutable


-----------------------------------------------------------------------------------------

31) Skia library is used by flutter for rendering. This helps flutter run fast. What is the other google product which uses Skia for rendering?
Android


-----------------------------------------------------------------------------------------

32) What type of Widgets are created for dynamic type?
Stateful widget


-----------------------------------------------------------------------------------------

33) Which type of animation is governed by physic laws and forces?
Physics-based

-----------------------------------------------------------------------------------------

34) What type of widgets are created for static type?
Stateless widgets

-----------------------------------------------------------------------------------------

35) FlutterActivity

Activity which displays a fullscreen Flutter UI.
FlutterActivity is the simplest and most direct way to integrate Flutter within an Android app.
The Dart entrypoint executed within this Activity is “main()” by default. The entrypoint may be specified explicitly by passing the name of the entrypoint method as a String in EXTRA_DART_ENTRYPOINT, e.g., “myEntrypoint”.
The Flutter route that is initially loaded within this Activity is “/”.
36) Flutter uses ……. compilation to increase the speed while execting.
Ahead-of-Time


-----------------------------------------------------------------------------------------

37) What is the name of the Google project to bring flutter or web?
Humming Bird


-----------------------------------------------------------------------------------------

38) What Library is used for rendering by flutter?
Skia


-----------------------------------------------------------------------------------------

39)FlutterActivity responsibilities?

Displays an Android launch screen.
Displays a Flutter splash screen.
Configures the status bar appearance.
Chooses the Dart execution app bundle path and entrypoint.
Chooses Flutter’s initial route.
Renders Activity transparently, if desired.
Offers hooks for subclasses to provide and configure a FlutterEngine.
-----------------------------------------------------------------------------------------


40) Eliminates the Use of XML files


Android application develop then work is separated into layout and code. Layout should be written in XML and Views written in java. Since flutter is everything widget.

-----------------------------------------------------------------------------------------

41) BLoC

The loading state can be represented by the values of a stream inside a BLoC.

BehaviourSubject is special stream controller that gives us synchronous access to the last value of the stream.
As an alternative to BloC, we could use a BehaviourSubject to keep track of the loading state, and update it as needed.


-----------------------------------------------------------------------------------------

42) ValueNotifier

A ValueNotifier can be used to hold a single value, and notify its listeners when this changes.


-----------------------------------------------------------------------------------------

43) widget
Widget as a visual component (or a component that interacts with the visual aspect of an application).
Flutter, everything is a Widget, down to the final build.call()
Every Widget has its own build() and its context.
The BuildContext is the parent of the widget returned by the build() method.
BuildContext of the Widget that calls build() is not the same as the build context of the widget returned by build().
-----------------------------------------------------------------------------------------


44) Context
Context is indicates location of the widget in widget tree.
A context only belongs to one widget.
Context is a BuildContext instance which gets passed to the builder of a widget in order to let it know where it is inside the Widget Tree of your app.
Each widget in Widget tree has own context, and context is directly attached to state of object. Attachment is permeant mean context of the widget will not be change in entire life time of the App.
Each widget has its own BuildContext, which becomes the parent of the widget returned by the StatelessWidget.build or State.build function. (And similarly, the parent of any children for RenderObjectWidgets.)
Widget we can imaging context in Parent/child manner.
Widget tree like Container -> Column -> Text->Button->Image. Here Each Widget in widget tree has own context like Container has it’s own context. Column has it’s own context… same for others. And context is permanent for it’s widget.
Container widget known as Parent widget in Widget tree and others are child widgets. So same We can imagine Context of Container widget also know as Parent context and others are child context.
State objects with a BuildContext after creating them with StatefulWidget.createState and before calling initState. The association is permanent: the State object will never change its BuildContext. However, the BuildContext itself can be moved around the tree.
BuildContext objects are actually Element objects. The BuildContext interface is used to discourage direct manipulation of Element objects.

-----------------------------------------------------------------------------------------



45) of()
Widgets that want to use the State of inherited widgets need to be able to reference those inherited widgets. This usually comes in the form of the of method.

-----------------------------------------------------------------------------------------


46) RenderObject
When you create any Widget, then widget itself has only configuration information mean If you create Opacity widget then main work of Opacity widget is to manage ‘opacity’ property that either 0 or 1. They don’t care about it’s child. Actually Child is created/Render some where else. That’s why we called each time create widget is not more expensive.
So we can say Widget is only blue-print, Layout/Rendering has been done some where else.

-----------------------------------------------------------------------------------------

47) Element
Element is nothing but instance of the widget at particular location in Widget tree.
When widget created, It inflated into Element. And element get inserted it into the tree at particular location.
Widget is immutable but element is mutable property.
Most of Elements has single child property like, Container, Opacity, Center etc and Some Elements has multiple children call children property. Like Column, Row, ListView and Etc.
Element are created by “createElement()” method.

-----------------------------------------------------------------------------------------


48) NoSuchMethodError: The getter ‘focusScopeNode’ was called on null?

Basically that is error context.
Navigator.of(context).pushNamed(‘/collections’);
//Navigator.pop(context); //Remove this line

-----------------------------------------------------------------------------------------


49) Flutter or Dart capitalize first character or word?

StringUtils.capitalize();

-----------------------------------------------------------------------------------------


50) Arrow Operator in flutter?

Arrow Operator is a short hand in Dart. only one line of code.

-----------------------------------------------------------------------------------------


51) Flutter ListView shadow remove or disable?

physics: ClampingScrollPhysics(); That is used to multiple listview in flutter application.

-----------------------------------------------------------------------------------------

52) Flutter keyboard hide.

FocusScope.of(context).requestFocus(FocusNode());


-----------------------------------------------------------------------------------------


53) Flutter logout after redirect or move login page?

const String loginRoute = '/login';
Navigator.of(context).pushNamedAndRemoveUntil(loginRoute, (Route<dynamic> route) => false);
//route define main.dart
routes: <String, WidgetBuilder>{
      '/': (context) => SplashScreenPage(),
      loginRoute: (BuildContext context) => LoginPage(),
}


-----------------------------------------------------------------------------------------


56) Flutter or dart remove single items using BLoC pattern?

List<DispatchResponse> removeJobId = state.dispatchList;
removeJobId.removeWhere((item) => item.jobId == 'remove unquie id');
yield state.copyWith(jobId: null, dispatchList: removeJobId);

-----------------------------------------------------------------------------------------

57) How to call or define BlocBuilder?

UserBloc _userBloc;
  _userBloc = BlocProvider.of<UserBloc>(context);
   BlocBuilder(bloc: _userBloc, builder: (context, UserState snapshot)
   {
      return Container();
   })
-----------------------------------------------------------------------------------------


58) Flutter circle image using assets folder.

 CircleAvatar(backgroundImage: ExactAssetImage(imageProfile))

-----------------------------------------------------------------------------------------

59) Flutter or Dart get current date and time?

final timestamp = DateTime.now();
print('Tag' + timestamp.toIso8601String());
output:
 2019-11-26T10:32:18.236537

-----------------------------------------------------------------------------------------

60) How to get 2 date difference or calculation?

final timestamp = DateTime.now();
final timeToExpiry = timestamp.difference(DateTime.now()).inSeconds;
print('Tag' + timeToExpiry.toString());

-----------------------------------------------------------------------------------------

61) UserAccountsDrawerHeader set background color in flutter?

UserAccountsDrawerHeader(
    decoration: BoxDecoration(
        color: Colors.red,
    ),
    accountName: Text(sessionUsername),
    accountEmail: Text(mail),
    currentAccountPicture: CircleAvatar(
        backgroundColor: Colors.red,
        backgroundImage: NetworkImage(gravatarUrl),
    ),
),

-----------------------------------------------------------------------------------------

62) How to close or dismiss keyboard in flutter?

FocusScope.of(context).requestFocus(FocusNode());

-----------------------------------------------------------------------------------------

63) Flutter TextField or EditText cursor selection end or last display?

TextEditingController.fromValue(TextEditingValue(text: problemList[index].enterValue,
                                selection: TextSelection.collapsed(
                                offset: problemList[index].enterValue.length)))

-----------------------------------------------------------------------------------------

64) Flutter ListView inside TextField scroll the change, clear, delete, null of the textfield value?

List<TextEditingController> _controllers = new List();
ListView.builder(
      physics: const BouncingScrollPhysics(),
      itemCount: problemList.length,
      shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        _controllers.add(new TextEditingController());
        _controllers[index].text = problemList[index].enterValue;
        return Container();
      });

-----------------------------------------------------------------------------------------

65) Flutter Text SingleLine and elipse ?

Text(overflow: TextOverflow.ellipsis, maxLines: 1, style: TextStyle())

-----------------------------------------------------------------------------------------

66) Flutter Text align right side ?

Text(textAlign: TextAlign.right)
TextAlign properties:
1) left
2) right
3) center
4) justify
5) start
6) end


-----------------------------------------------------------------------------------------

67) Dart Isolates?

To achieve concurrency, Dart uses isolates, it is works independent don’t share memory but use message communication or passing. Every Dart program uses at least one isolate, which is the main isolate. Dart 2 the Dart web platform no longer supports isolates.

Snapshots
Snapshots are a core part of the Dart VM. Snapshots are files which store objects and other runtime data.

1) Script snapshots

Dart programs can be compiled into snapshot files. These files contain all of the program code and dependencies prepared and ready to execute. This allows fast startups.

2) Full snapshots

The Dart core libraries can be compiled into a snapshot file which allows fast loading of the libraries. Most standard distributions of the main Dart VM have a prebuilt snapshot for the core libraries which is loaded at runtime.

3) Object snapshots

Dart is a very asynchronous language. With this, it uses isolates for concurrency. Since these are workers which pass messages, it needs a way to serialize a message. This is done using a snapshot, which is generated from a given object, and then this is transferred to another isolate for deserializing.


-----------------------------------------------------------------------------------------

68) Difference between NetworkImage and Image.network in flutter ?

NetworkImage class creates an object the provides an image from the src URL passed to it. It is not a widget and does not output an image to the screen.
Image.network creates a widget that displays an image on the screen. It is just a named constructor on the Image class(a stateful widget). It sets the image property using the NetworkImage . This image property is used finally to display the image.
If you just want to display the image as a widget on screen use Image.network and use NetworkImage wherever an ImageProvider is expected.

-----------------------------------------------------------------------------------------

69) When flutter is released and stable ?

First alpha version was released on May 2017; and after 1.5 years, Flutter got its first stable 1.0 release on December 4th, 2018.


-----------------------------------------------------------------------------------------

70) ExactAssetImage in flutter ?

Creates an object that fetches the given image from an asset bundle.
ExactAssetImage(“assets/images/mobile_box.png”)


-----------------------------------------------------------------------------------------

71) FileImage in flutter ?

Decodes the given File object as an image, associating it with the given scale. Used to load images from the file system in the target device. e.g. To display a newly downloaded image.
FileImage(file object)


-----------------------------------------------------------------------------------------

72) didChangeAppLifecycleState() in flutter ?

Called when the system puts the app in the background or returns the app to the foreground.

@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
}

-----------------------------------------------------------------------------------------

73) How to add or insert data in firbase with database reference id using flutter ?

final databaseReference = Firestore.instance.collection('/');
await databaseReference.document('unique id set').setData({
      'id': '1',
      'status': 'true'
    });

-----------------------------------------------------------------------------------------

74) Firebase notification background message get application is close ?

onBackgroundMessage using.


-----------------------------------------------------------------------------------------

75) Firebase upload image, file using flutter and How to get upload file url ?

var path = multipleUpload.file.path;
var filename = path.split("/").last;
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(filename);
StorageUploadTask uploadTask1 = firebaseStorageRef.putFile(multipleUpload.file);
StorageTaskSnapshot taskSnapshot = await uploadTask1.onComplete;
String downloadUrl = await taskSnapshot.ref.getDownloadURL();
print('Display image URL path' + downloadUrl);


-----------------------------------------------------------------------------------------

76) How to set laucher icon android and ios application ?

flutter_launcher_icons add dependency in flutter.

flutter_icons:
ios: true
android: true
image_path: “assets/images/flutter_tutorial.png”

Execute command on the terminal: flutter pub pub run flutter_launcher_icons:main


-----------------------------------------------------------------------------------------

77) Dart Map add the value, update and how to get particular key total ?

main(){
  var map = Map<String, int>();
  map.putIfAbsent('2019-07-22', () => 1);
  map.putIfAbsent('2019-07-21', () => 2);
  map.putIfAbsent('2019-07-23', () => 3);
  map.update("2019-07-23", (dynamic val) => 2);
  var sum = map.entries
      .where((e) => e.key.startsWith('2019'))
      .map<int>((e) => e.value)
      .reduce((a, b) => a + b);
  print('sum of total ' + sum.toString());
}

-----------------------------------------------------------------------------------------

78) Android system navigation hide and show in flutter ?

SystemChrome.setEnabledSystemUIOverlays([]);

-----------------------------------------------------------------------------------------

79) CircleAvatar change the background color in flutter ?

CircleAvatar(
              backgroundColor: Colors.black.withOpacity(0.2),
              backgroundImage: new FileImage(), radius: 65.0)

-----------------------------------------------------------------------------------------

80) flutter get extention and file name form file ?

add dependency: path

extension(file.path); //extention
basename(file.path); //filename


-----------------------------------------------------------------------------------------

81) Firebase file upload save the file new name ?

StorageReference storageRef = FirebaseStorage.instance.ref().child(new name);


-----------------------------------------------------------------------------------------

82) what is Flutter inspector ?

The inspector is powerful tool for visualizing and exploring Flutter these widget trees. It is very useful 1) Understanding existing layouts 2) Diagnosing layout issues

Advatage :

1) Select widget mode
2) Refresh widget
3) Show/hide performance overlay
4) Toggle platform
5) Show debug paint
6) show paint baselines
7) Enable slow animations

No comments:

Post a Comment

How to save contact number in flutter

with contacts_service: 0.3.10 https://pub.dev/packages/contacts_service Future < void > contactSave (){ Contact contac...