{"id":17999847,"url":"https://github.com/ibhavikmakwana/flutterdarttips","last_synced_at":"2025-08-31T13:38:41.488Z","repository":{"id":102082155,"uuid":"165680225","full_name":"ibhavikmakwana/FlutterDartTips","owner":"ibhavikmakwana","description":"Useful Flutter and Dart Tips.","archived":false,"fork":false,"pushed_at":"2020-10-01T16:22:34.000Z","size":1678,"stargazers_count":333,"open_issues_count":1,"forks_count":33,"subscribers_count":32,"default_branch":"master","last_synced_at":"2025-05-19T23:03:48.315Z","etag":null,"topics":["android","dart","flutter","flutter-desktop","flutter-web","ios","programming","technology","tips","tips-and-tricks"],"latest_commit_sha":null,"homepage":"https://ibhavikmakwana.github.io/FlutterDartTips/","language":"Dart","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ibhavikmakwana.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-01-14T14:58:13.000Z","updated_at":"2025-05-05T10:39:21.000Z","dependencies_parsed_at":null,"dependency_job_id":"97eae496-6f6e-409f-8a3b-ef76f35f1bd3","html_url":"https://github.com/ibhavikmakwana/FlutterDartTips","commit_stats":null,"previous_names":[],"tags_count":0,"template":true,"template_full_name":null,"purl":"pkg:github/ibhavikmakwana/FlutterDartTips","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ibhavikmakwana%2FFlutterDartTips","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ibhavikmakwana%2FFlutterDartTips/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ibhavikmakwana%2FFlutterDartTips/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ibhavikmakwana%2FFlutterDartTips/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ibhavikmakwana","download_url":"https://codeload.github.com/ibhavikmakwana/FlutterDartTips/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ibhavikmakwana%2FFlutterDartTips/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":272988777,"owners_count":25026959,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-31T02:00:09.071Z","response_time":79,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["android","dart","flutter","flutter-desktop","flutter-web","ios","programming","technology","tips","tips-and-tricks"],"created_at":"2024-10-29T22:15:00.383Z","updated_at":"2025-08-31T13:38:41.471Z","avatar_url":"https://github.com/ibhavikmakwana.png","language":"Dart","funding_links":[],"categories":[],"sub_categories":[],"readme":"##### Table of Contents  \n- [Articles](#articles)\n- [Tips](#tips)\n\n# Articles\n- [#1 Flutter + Dart Tips](https://medium.com/flutter-community/1-flutter-dart-tips-830854c3a418)\n- [#2 Flutter + Dart Tips](https://medium.com/flutter-community/2-flutter-dart-tips-f149ffe83381)\n- [#3 Flutter + Dart Tips](https://medium.com/flutter-community/3-flutter-dart-tips-18cc8502f451)\n- [#4 Flutter + Dart Tips](https://medium.com/flutter-community/4-flutter-dart-tips-d1c44faa9c05)\n- [#5 Flutter + Dart Tips](https://medium.com/flutter-community/5-flutter-dart-tips-6e554f34cddd)\n\n\n\n# Tips\n\n### 16. Apply `HitTestBehavior.opaque` on GestureDetector to make the entire size of the gesture detector a hit region\nIf 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.\n```dart\nGestureDetector(\n  behavior: HitTestBehavior.opaque,\n  onTap: ()=\u003eprint('Tap!'),\n  child: Container(\n  height: 250,\n  width: 250,\n  child: Center(child: Text('Gesture Test')),\n ),\n),\n```\n`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.\n\nOriginal source: [Twitter](https://twitter.com/mjohnsullivan/status/1219685756739805187?s=19)\n\n### 15. Check if release mode or not\nYou can use `kReleaseMode` constant to check if the code is running in release mode or not.\n`kReleaseMode` is a top-level constant from `foundation.dart`. \n\nMore 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)\n\n```dart\nimport 'package:flutter/foundation.dart';\n\nprint('Is Release Mode: $kReleaseMode');\n```\n\n### 14. Set background image to your Container.\n\nWant to set the background image to your Container? And you are using a Stack to do so?\nThere is a better way to achieve this result.\nYou can use decoration to set the image in the container.\n\n```dart\nContainer(\n  width: double.maxFinite,\n  height: double.maxFinite,\n  decoration: BoxDecoration(\n    image: DecorationImage(\n      image: NetworkImage('https://bit.ly/2oqNqj9'),\n    ),\n  ),\n  child: Center(\n    child: Text(\n      'Flutter.dev',\n      style: TextStyle(color: Colors.red),\n    ),\n  ),\n),\n\n```\n\nYou can provide Image according to your need, also you can use the box decoration properties to provide shape and border.\n\n### 13. Prefer single quotes for strings\nUse double quotes for nested strings or (optionally) for strings that contain single quotes. For all other strings, use single quotes.\n\n```dart\nfinal String name = 'Flutter And Dart Tips';\n\nprint('Hello ${name.split(\" \")[0]}');\nprint('Hello ${name.split(\" \")[2]}');\n\n```\n\n### 12. Implement `assert()` messages in Dart.\n\nDo you know that you can throw your message when your `assert` fails?\n`assert()` takes an optional message in which you can pass your message.\n\n```dart\nassert(title != null, \"Title string cannot be null.\");\n```\n\n### 11. Using Plurals in your Dart String.\n\n**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.\n\nYou can use Plurals in your Dart string by using [`Intl`](https://pub.dev/packages/intl) package. The full set supported by `Intl` package is zero, one, two, few, many, and other.\n\n- Add dependency:\n\n```yaml\ndependencies:\n  intl: version\n```\n\n- How to use:\n\n```dart\nimport 'package:intl/intl.dart';\n...\nnotificationCount(int howMany) =\u003e Intl.plural(\n      howMany,\n      zero: 'You don\\'t have any notification.',\n      one: 'You have $howMany notification.',\n      other: 'You have $howMany notifications.',\n      name: \"notification\",\n      args: [howMany],\n      examples: const {'howMany': 42},\n      desc: \"How many notifications are there.\",\n    );\n\n    print(notificationCount(0));\n    print(notificationCount(1));\n    print(notificationCount(2));\n    \n```\n\n- Output:\n\n```Output\nYou don't have any notification.\nYou have 1 notification.\nThere are 2 notifications.\n```\n\n### 10. Having trouble displaying splashes using an InkWell?\nUse an Ink widget! The Ink widget draws on the same widget that InkWell does, so the splash appears.\n#FlutterFriday tweet by [Flutter.dev](https://twitter.com/FlutterDev/status/1121874600361693189?s=20).\n\nLearn more [here](https://goo.gl/4cx2Kn).\n\n```dart\nclass InkWellCard extends StatelessWidget {\n  Widget build(BuildContext context) {\n    return Card(\n      elevation: 3.0,\n      child: Ink(\n        child: InkWell(\n          child: Center(\n            child: Text(\"Order Bagels\"),\n          ),\n          onTap: () =\u003e print(\"Ordering..\"),\n        ),\n      ),\n    );\n  }\n}\n```\n\n\n### 9. Want to log data on the system console in Flutter?\n\nYou can use the `print()` function to view it in the system console.\nIf your output is too much, then Android sometimes discards some log lines.\nTo avoid this, you can use `debugPrint()`.\n\nYou can also log your print calls to disk if you're doing long-term or background work.\n\nCheck out this [Gist](https://gist.github.com/slightfoot/1770dec7967def3b4d021bba8d814817) by [Simon Lightfoot](https://github.com/slightfoot)\n\n### 8. Cascade Notation - Method Chaining on Steroids :pill::syringe:\n`Cascades Notation (..)` allows chaining a sequence of operations on the same object. Besides, fields (data-members) can be accessed using the same.\n\n[Open in DartPad :dart:](https://dartpad.dartlang.org/a93316aa779a2e0dd1993ae9a3464731)\n\n```dart\nclass Person {\n  String name;\n  int age;\n  Person(this.name, this.age);\n  void data() =\u003e print(\"$name is $age years old.\");\n}\n\nvoid main() {\n   // Without Cascade Notation\n   Person person = Person(\"Richard\", 50);\n   person.data();\n   person.age = 22;\n   person.data();\n   person.name += \" Parker\";\n   person.data();\n   \n   // Cascade Notation with Object of Person\n   Person(\"Jian\", 21)\n    ..data()\n    ..age = 22\n    ..data()\n    ..name += \" Yang\"\n    ..data();\n    \n   // Cascade Notation with List\n   List\u003cString\u003e()\n    ..addAll([\"Natasha\", \"Steve\", \"Peter\", \"Tony\"])\n    ..sort()\n    ..forEach((name) =\u003e print(\"\\n$name\"));\n}\n```\n\n### 7. Want to set different Theme for a particular widget?\n\nJust wrap the widget with the `Theme` Widget and pass the `ThemeData()`.\n\n```dart\nTheme(\n  data: ThemeData(...),\n  child: TextFormField(\n    decoration: const InputDecoration(\n      icon: Icon(Icons.person),\n      hintText: 'What do people call you?',\n      labelText: 'Name *',\n    ),\n    onSaved: (String value) {\n      // This optional block of code can be used to run\n      // code when the user saves the form.\n    },\n    validator: (String value) {\n      return value.contains('@')\n        ? 'Do not use the @ char'\n        : null;\n    }\n  ),\n)\n```\n\n### 6. Use a Ternary operator instead of the if-else to shorter your Dart code.\n\nUse below.\n\n```dart\nvoid main() {\n  bool isAndroid = true;\n  getDeviceType() =\u003e isAndroid ? \"Android\" : \"Other\";\n  print(\"Device Type: \" + getDeviceType());\n}\n```\n\nInstead of this.\n\n```dart\nvoid main() {\n  bool isAndroid;\n  getDeviceType() {\n    if (isAndroid) {\n      return \"Android\";\n    } else {\n      return \"Other\";\n    }\n  }\n  print(\"Device Type: \" + getDeviceType());\n}\n```\n\n### 5. Want to run a task periodically in Dart?\n\nWhat about using `Timer.periodic`\nIt 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.\n\n```dart\nTimer.periodic(const Duration(seconds: 2), (Timer time) {\n  print(\"Flutter\");\n});\n```\n\nYou can cancel the timer using the `timer.cancel()`.\n\n### 4. Apply style as a Theme in a `Text` widget.\nCheck out the below article for detail information about this tip.\n[Apply style as a Theme in a `Text` widget](https://medium.com/flutter-community/flutter-apply-style-as-a-theme-in-a-text-widget-90268328bd23)\n\n```dart\nText(\n  \"Your Text\",\n  style: Theme.of(context).textTheme.title,\n),\n```\n\n### 3. Do not explicitly initialize variables to `null`.\n\nAdding `= null` is redundant and unneeded.\n\n```dart\n// Good\nvar title;\n\n// Bad\nvar title = null;\n```\n\n### 2. Using `ListView.separated()`\nWant to add the separator in your Flutter ListView?\n\nGo for the\n`ListView.separated();`\n\nThe best part about separated is it can be any widget.😃\n\nCheck out the below image for the sample code.\n\n```dart\nListView.seperated(\n  seperatorBuilder: (context, index) =\u003e Divider(),\n  itemBuilder: (BuildContext context, int index) =\u003e new ExampleNameItem(\n    exampleNames: names[index],\n  ),\n  itemCount: names.length,\n  padding: new EdgeInsets.symetric(\n    vertical: 8.0,\n    horizontal: 8.0,\n  ),\n);\n```\n\n### 1. Using `null-aware operators`\nWhile 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.\n\n```dart\n// User below\n\ntitle ??= \"Title\";\n\n// instead of\n\nif (title == null) {\n  title = \"Title\";\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fibhavikmakwana%2Fflutterdarttips","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fibhavikmakwana%2Fflutterdarttips","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fibhavikmakwana%2Fflutterdarttips/lists"}