Hello Reader,
I am trying something new here. A "Week In Review" series where I share the Flutter\Dart tips I tweeted last week.
Let's try this...
1- You can iterate through a map in a null-safe manner using entries.
for (var entry in items.entries) { //print the keys and values print('${entry.key}: ${entry.value}'); }
2- Lists can hold duplicate items. So If you want a collection of unique values, Use a Set instead.
In a Set, two elements cannot be equal, so the code below won’t compile.
final citiesSet = {'Dublin', 'London', 'Paris', 'Dublin'};
3- You can wait for the results of multiple Futures to complete using Future.wait
class someAPI { Future<int> getThings() => Future.value(3000); Future<int> getItems() => Future.value(300); Future<int> getStuff() => Future.value(30); } ... final api = someAPI(); final values = await Future.wait([ api.getThings(), api.getItems(), api.getStuff(), ]); print(values);
4- You can use GridView.count to create a grid that's two tiles wide in portrait mode and three tiles wide in landscape mode
final Orientation orientation = MediaQuery.of(context).orientation; ... Flexible( child: GridView.count( crossAxisCount: (orientation == Orientation.portrait) ? 2 : 3, mainAxisSpacing: 4.0, crossAxisSpacing: 4.0, padding: const EdgeInsets.all(4.0), childAspectRatio: (orientation == Orientation.portrait) ? 1.0 : 1.3, children: someList .map( (catData) => aListItemWidget(catData), ) .toList(), ), ),
5- You can randomly select an item from a list using Random from dart:math
import 'dart:math'; ... int min = 0; int max = someList.length - 1; Random rnd = new Random(); int r = min + rnd.nextInt(max - min); return someList[r];
6- You can use the services library to lock the device orientation
import 'package:flutter/services.dart'; ... void main() async { await SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, ]); runApp(App()); }
7- You can use the dart:io library to write a platform-specific code
import 'dart:io' show Platform; ... if (Platform.isIOS) { doSomethingforIOS(); } if (Platform.isAndroid) { doSomethingforAndroid(); }
8- You can turn any color to a Material Color
const Map<int, Color> color = { 50: Color.fromRGBO(255, 207, 68, .1), 100: Color.fromRGBO(255, 207, 68, .2), 200: Color.fromRGBO(255, 207, 68, .3), 300: Color.fromRGBO(255, 207, 68, .4), 400: Color.fromRGBO(255, 207, 68, .5), 500: Color.fromRGBO(255, 207, 68, .6), 600: Color.fromRGBO(255, 207, 68, .7), 700: Color.fromRGBO(255, 207, 68, .8), 800: Color.fromRGBO(255, 207, 68, .9), 900: Color.fromRGBO(255, 207, 68, 1), }; const MaterialColor custom_color = MaterialColor(0xFFFFCF44, color);
See you next week. 👋🏻
Follow me on Twitter for more tips about #coding, #learning, #technology...etc.
Check my Apps on Google Play
Cover image Immo Wegmann on Unsplash
Top comments (3)
Your duplicate set example compiles just fine. It just has a compile-time warning that can be easily ignored.
Thanks, I'll check it out
Thank you, very useful