All Projects → ibhavikmakwana → Flutterdarttips

ibhavikmakwana / Flutterdarttips

Licence: apache-2.0
Useful Flutter and Dart Tips.

Programming Languages

dart
5743 projects

Projects that are alternatives of or similar to Flutterdarttips

Dica Python Linkedin
⚡ Este repositório é direcionado para dicas com a linguagem python, que estão sendo postadas em meu linkedin.
Stars: ✭ 54 (-83.18%)
Mutual labels:  programming, tips, tips-and-tricks
web
Hugo content for the openshift.tips blog
Stars: ✭ 48 (-85.05%)
Mutual labels:  tips, tips-and-tricks
delphi-tips
A bunch of Delphi language tips migrated from the DelphiDabbler.com website, plus others.
Stars: ✭ 29 (-90.97%)
Mutual labels:  tips, tips-and-tricks
awesome-search-engine-optimization
A curated list of backlink, social signal opportunities, and link building strategies and tactics to help improve search engine results and ranking.
Stars: ✭ 82 (-74.45%)
Mutual labels:  tips, tips-and-tricks
Css Protips
A collection of tips to help take your CSS skills pro
Stars: ✭ 20,279 (+6217.45%)
Mutual labels:  tips, tips-and-tricks
Bookmarks
🔖 +4.3K awesome resources for geeks and software crafters 🍺
Stars: ✭ 210 (-34.58%)
Mutual labels:  programming, tips-and-tricks
tips
Here is what you need to setup your progressive web app dev environment
Stars: ✭ 14 (-95.64%)
Mutual labels:  tips, tips-and-tricks
Preguntas Y Respuestas Entrevistas Frontend
Un listado de preguntas y respuestas que hemos y nos han preguntado en entrevistas para Ingenieros y Desarrolladores de Front End (Para facilitar las entrevistas y el estudio)
Stars: ✭ 207 (-35.51%)
Mutual labels:  tips, tips-and-tricks
git-tips
33 条常用 git 命令详解
Stars: ✭ 115 (-64.17%)
Mutual labels:  tips, tips-and-tricks
mesan-react-native-authentication-app
A React Native app with authentication including Register, Login, Username, Forgot Password and Update Profile using React Hooks and React Context API.
Stars: ✭ 35 (-89.1%)
Mutual labels:  programming, technology
Awesome Courses
😏 📄 An awesome list of educational websites, YouTube playlists, channels and books about programming
Stars: ✭ 99 (-69.16%)
Mutual labels:  programming, technology
AdvancedPeripherals
A Peripheral addon mod for Computercraft 1.16-1.18. This mod aims to add more features to Computercraft.
Stars: ✭ 36 (-88.79%)
Mutual labels:  programming, technology
Learn Vim
Vim 实操教程(Learning Vim)Vim practical tutorial.
Stars: ✭ 1,166 (+263.24%)
Mutual labels:  programming, tips
Comunidade
✊🏽 A comunidade de programação da periferia
Stars: ✭ 252 (-21.5%)
Mutual labels:  programming, technology
Blog
Personal Blog - 博客 | 编程技术,软件,生活
Stars: ✭ 506 (+57.63%)
Mutual labels:  programming, technology
android-development-best-practices
With best practices under your fingertips, you will not lose precious time on reinventing the wheel. Instead, you can focus on writing quality code and getting the job done.
Stars: ✭ 111 (-65.42%)
Mutual labels:  tips, tips-and-tricks
Pharo Wiki
Wiki related to the Pharo programming language and environment.
Stars: ✭ 161 (-49.84%)
Mutual labels:  tips, tips-and-tricks
Guides
Here you will find Guides mainly for Sonarr/Radarr/Bazarr and everything related to it.
Stars: ✭ 207 (-35.51%)
Mutual labels:  tips, tips-and-tricks
xcode-tips.github.io
Community-run website for documenting Xcode Tips
Stars: ✭ 513 (+59.81%)
Mutual labels:  tips, tips-and-tricks
goodmodule
JavaScript tips (ES6, CSS, Benchmarks, React, Redux, ...)
Stars: ✭ 31 (-90.34%)
Mutual labels:  tips, tips-and-tricks
Table of Contents

Articles

Tips

16. Apply HitTestBehavior.opaque on GestureDetector to make the entire size of the gesture detector a hit region

If your GestureDetector isn't picking up gestures in a transparent/translucent widget, make sure to set its behavior to HitTestBehavior.opaque so it'll capture those events.

GestureDetector(
  behavior: HitTestBehavior.opaque,
  onTap: ()=>print('Tap!'),
  child: Container(
  height: 250,
  width: 250,
  child: Center(child: Text('Gesture Test')),
 ),
),

Opaque targets can be hit by hit tests, causing them to both receive events within their bounds and prevent targets visually behind them from also receiving events.

Original source: Twitter

15. Check if release mode or not

You can use kReleaseMode constant to check if the code is running in release mode or not. kReleaseMode is a top-level constant from foundation.dart.

More specifically, this is a constant that is true if the application was compiled in Dart with the '-Ddart.vm.product=true' flag. (from https://api.flutter.dev/flutter/foundation/kReleaseMode-constant.html)

import 'package:flutter/foundation.dart';

print('Is Release Mode: $kReleaseMode');

14. Set background image to your Container.

Want to set the background image to your Container? And you are using a Stack to do so? There is a better way to achieve this result. You can use decoration to set the image in the container.

Container(
  width: double.maxFinite,
  height: double.maxFinite,
  decoration: BoxDecoration(
    image: DecorationImage(
      image: NetworkImage('https://bit.ly/2oqNqj9'),
    ),
  ),
  child: Center(
    child: Text(
      'Flutter.dev',
      style: TextStyle(color: Colors.red),
    ),
  ),
),

You can provide Image according to your need, also you can use the box decoration properties to provide shape and border.

13. Prefer single quotes for strings

Use double quotes for nested strings or (optionally) for strings that contain single quotes. For all other strings, use single quotes.

final String name = 'Flutter And Dart Tips';

print('Hello ${name.split(" ")[0]}');
print('Hello ${name.split(" ")[2]}');

12. Implement assert() messages in Dart.

Do you know that you can throw your message when your assert fails? assert() takes an optional message in which you can pass your message.

assert(title != null, "Title string cannot be null.");

11. Using Plurals in your Dart String.

Plurals: Different languages have different rules for grammatical agreement with quantity. In English, for example, the quantity 1 is a special case. We write "1 book", but for any other quantity we'd write "n books". This distinction between singular and plural is very common, but other languages make finer distinctions.

You can use Plurals in your Dart string by using Intl package. The full set supported by Intl package is zero, one, two, few, many, and other.

  • Add dependency:
dependencies:
  intl: version
  • How to use:
import 'package:intl/intl.dart';
...
notificationCount(int howMany) => Intl.plural(
      howMany,
      zero: 'You don\'t have any notification.',
      one: 'You have $howMany notification.',
      other: 'You have $howMany notifications.',
      name: "notification",
      args: [howMany],
      examples: const {'howMany': 42},
      desc: "How many notifications are there.",
    );

    print(notificationCount(0));
    print(notificationCount(1));
    print(notificationCount(2));
    
  • Output:
You don't have any notification.
You have 1 notification.
There are 2 notifications.

10. Having trouble displaying splashes using an InkWell?

Use an Ink widget! The Ink widget draws on the same widget that InkWell does, so the splash appears. #FlutterFriday tweet by Flutter.dev.

Learn more here.

class InkWellCard extends StatelessWidget {
  Widget build(BuildContext context) {
    return Card(
      elevation: 3.0,
      child: Ink(
        child: InkWell(
          child: Center(
            child: Text("Order Bagels"),
          ),
          onTap: () => print("Ordering.."),
        ),
      ),
    );
  }
}

9. Want to log data on the system console in Flutter?

You can use the print() function to view it in the system console. If your output is too much, then Android sometimes discards some log lines. To avoid this, you can use debugPrint().

You can also log your print calls to disk if you're doing long-term or background work.

Check out this Gist by Simon Lightfoot

8. Cascade Notation - Method Chaining on Steroids 💊💉

Cascades Notation (..) allows chaining a sequence of operations on the same object. Besides, fields (data-members) can be accessed using the same.

Open in DartPad 🎯

class Person {
  String name;
  int age;
  Person(this.name, this.age);
  void data() => print("$name is $age years old.");
}

void main() {
   // Without Cascade Notation
   Person person = Person("Richard", 50);
   person.data();
   person.age = 22;
   person.data();
   person.name += " Parker";
   person.data();
   
   // Cascade Notation with Object of Person
   Person("Jian", 21)
    ..data()
    ..age = 22
    ..data()
    ..name += " Yang"
    ..data();
    
   // Cascade Notation with List
   List<String>()
    ..addAll(["Natasha", "Steve", "Peter", "Tony"])
    ..sort()
    ..forEach((name) => print("\n$name"));
}

7. Want to set different Theme for a particular widget?

Just wrap the widget with the Theme Widget and pass the ThemeData().

Theme(
  data: ThemeData(...),
  child: TextFormField(
    decoration: const InputDecoration(
      icon: Icon(Icons.person),
      hintText: 'What do people call you?',
      labelText: 'Name *',
    ),
    onSaved: (String value) {
      // This optional block of code can be used to run
      // code when the user saves the form.
    },
    validator: (String value) {
      return value.contains('@')
        ? 'Do not use the @ char'
        : null;
    }
  ),
)

6. Use a Ternary operator instead of the if-else to shorter your Dart code.

Use below.

void main() {
  bool isAndroid = true;
  getDeviceType() => isAndroid ? "Android" : "Other";
  print("Device Type: " + getDeviceType());
}

Instead of this.

void main() {
  bool isAndroid;
  getDeviceType() {
    if (isAndroid) {
      return "Android";
    } else {
      return "Other";
    }
  }
  print("Device Type: " + getDeviceType());
}

5. Want to run a task periodically in Dart?

What about using Timer.periodic It will create a repeating timer, It will take a two-argument one is duration and the second is callback that must take a one Timer parameter.

Timer.periodic(const Duration(seconds: 2), (Timer time) {
  print("Flutter");
});

You can cancel the timer using the timer.cancel().

4. Apply style as a Theme in a Text widget.

Check out the below article for detail information about this tip. Apply style as a Theme in a Text widget

Text(
  "Your Text",
  style: Theme.of(context).textTheme.title,
),

3. Do not explicitly initialize variables to null.

Adding = null is redundant and unneeded.

// Good
var title;

// Bad
var title = null;

2. Using ListView.separated()

Want to add the separator in your Flutter ListView?

Go for the ListView.separated();

The best part about separated is it can be any widget.😃

Check out the below image for the sample code.

ListView.seperated(
  seperatorBuilder: (context, index) => Divider(),
  itemBuilder: (BuildContext context, int index) => new ExampleNameItem(
    exampleNames: names[index],
  ),
  itemCount: names.length,
  padding: new EdgeInsets.symetric(
    vertical: 8.0,
    horizontal: 8.0,
  ),
);

1. Using null-aware operators

While checking the null in the Dart, Use null-aware operators help you reduce the amount of code required to work with references that are potentially null.

// User below

title ??= "Title";

// instead of

if (title == null) {
  title = "Title";
}
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].