Tip 81 : Use quicktype.io to generate serializer/deserializer
for dart
Convert a JSON
into Dart class
with fromJSON()
and toJSON()
methods easily with quicktype.io
Just paste your JSON and select dart
from languages (right-top), you will get the dart class
.
try quicktype
Alternative:
Or json to dart
You can display PDF easily with pdf_flutter
-
Add
pdf_flutter
on pubspec.ymldependencies: pdf_flutter: ^version
-
On
iOS
enable PDF preview like by adding this on ios/Runner/info.plist:<key>io.flutter.embedded_views_preview</key> <true/>
-
Start Using
//Load PDF from Network PDF.network( 'https://raw.githubusercontent.com/FlutterInThai/Dart-for-Flutter-Sheet-cheet/master/Dart-for-Flutter-Cheat-Sheet.pdf', height: 500, width: 300,) //Load PDF from Assets PDF.assets("assets/pdf/demo.pdf",height:400,width:300) //Load PDF from file File fileName; PDF.file(fileName,height:400,width:300)
Visit pdf_flutter
An obvious but underappreciated tip:
More than half of the unexpected/strange build errors can be solved by flutter clean
The first step towards fixing any build errors in Flutter should be:
flutter clean
🤡Remember this command, it will save you hours of frustration
Alice records Http request,payload & response which can be viewed in simple UI (notification or widget). Alice can work with http:http, dart:io/HttpClient, Chopper & Dio.
-
Add dependency.
-
Create Alice instance (global is OK)
Alice _alice = Alice(showNotification: true, showInspectorOnShake: true);
-
Pass
_alice.getNavigatorKey()
as NavigatorKey of Material/Cupertino App.MaterialApp( navigatorKey: _alice.getNavigatorKey(), child:.... )
-
Start logging (using http:http for sample)
import 'package:http/http.dart' as http; http .post('https://jsonplaceholder.typicode.com/posts', body: body) .interceptWithAlice(_alice, body: body); http .get('https://jsonplaceholder.typicode.com/posts') .interceptWithAlice(_alice); http .put('https://jsonplaceholder.typicode.com/posts/1', body: body) .then((response) { _alice.onHttpResponse(response, body: body); });
-
See the HTTP call details
Simply call_alice.showInspector();
or
Just shake the phone
to
open the Http call details screen.
clay_containers
makes it easy to build Neumorphic UI.
-
Add dependency
dependencies: clay_containers: ^version
-
Start using
ClayContainer( color: baseColor, height: 200, width: 200, child:Center(child:newChild) //Put child inside Center to align it centrally. depth:45, // negative elevation(both +ve & -ve) curveType: CurveType.convex, //Curve of surface (concave, convex, plane) borderRadius: 200, )
Passing an object/bloc from a parent widget to it's children across the widget tree by passing it through every Widget constructor between parent and the reciever child is hard.
With provider
you can easily pass object/bloc from parent to any widget below it in widget tree.
- Add dependency
provider: ^4.1.3
- Pass object/model/bloc from Parent Widget by wrapping any widget with Provider.
@override
Widget build(BuildContext context) {
return Provider(
create:(_)=> User("erluxman"),
child: ScreenA(
child:ScreenB(
child:ScreenC(),
),
),
);
}
class User{
String name;
User(this.name);
}
- Recieve object/model/bloc/ by calling
Provider.of<ObjectType>(context)
class ScreenC extends StatelessWidget {
@override
Widget build(BuildContext context) {
User user = Provider.of<User>(context);
print(user.name); //erluxman
return Container(
child: Center(
child: Text(user.name), //erluxman
),
);
}
}
Using Flutter snippets helps gain speed and become productive by eliminating the time typing the boilerplate code by autocompleting various snippets.
When we get too used to using Icon in FloatingActionButton, we tend to forget that we can use various types of widget as FloatingActionButton's child.
We can use emoji Text as Child to FloatingActionButton to get wonderful colorful Fabs without any image.
FloatingActionButton(
backgroundColor: Colors.white,
child: Text(
"🚀",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 30),),
)
You can run any task repeatedly in a certain time period like this:
Timer.periodic(const Duration(seconds: 1), (Timer time) {
setState(() {
// Your code that runs periodically
secondsPast += 1;
});
});
Don't want to create launcher Icons for platform and put them in place manually?
use flutter_launcher_icons
- Add dev dependency (
remember dev_dependencies
).
dev_dependencies:
flutter_launcher_icons: ^0.7.5
- Configure flutter_icons (
no spaces before flutter_icons:
)
flutter_icons:
android: "launcher_icon"
ios: true
image_path: "assets/images/ic_launcher.png" #use your image path
- Generate Icons
flutter pub run flutter_launcher_icons:main
- Run app
Android icon | iOS icon |
---|---|
Want to make Flutter widgets smooshy like Jelly or Dough? Use the package dough
- Add
dough
to dependency
dependencies:
dough: ^version
- Wrap any widget with
PressableDough()
.
PressableDough(
child: FloatingActionButton(
onPressed: () {},
child: Text("🧠",style: TextStyle(fontSize: 40)),
),
)
- Sorry to disappoint but you are already done 😜
Autocomplete TextField can be implemented with flutter_typeahead
Package.
- Add Dependency
dependencies:
flutter_typeahead: ^version
- Use
TypeAheadFormField
/TypeAheadField
var platforms = ["Flutter", "Android", "iOS", "Mac", "React", "Cordova"];
final TextEditingController input = TextEditingController();
TypeAheadFormField(
textFieldConfiguration: TextFieldConfiguration(
decoration: InputDecoration(labelText: 'City'),
controller: this.input),
//Search and return found values
suggestionsCallback: (pattern) => platforms.where(
(item) => item.toLowerCase().contains(pattern.toLowerCase()),
),
itemBuilder: (_, item) => ListTile(title: Text(item)),
onSuggestionSelected: (query) => this.input.text = query,
),
connectivity
package makes it easy to read network state of device.
- Add dependency
dependencies:
connectivity: ^version
- Read network states
class State ...{
@override
initState() {
super.initState();
subscription = Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult result) {
if (result == ConnectivityResult.mobile) //mobile connected.
else if (result == ConnectivityResult.wifi) //Wifi Connected.
else if(result == ConnectivityResult.none) //No network
});
}
@override
dispose() {
subscription.cancel();
super.dispose();
}
}
supercharged
brings awesome utility features from other languages to dart 🎯. making developers life easier.
dependencies:
supercharged: ^1.6.0
"#ff00ff".toColor();
"red".toColor();
"flutter is cool".allBefore(" is"); // "flutter"
12.between(0, 30); // true
[1, 2, 3].elementAtOrNull(4); // Don't throw, return null
[1, 2, 3].elementAtOrElse(4, () => 0); //Don't throw, return default value
//Create Pages from list
["a", "b", "c"].chunked(2, fill: () => ""); // [ ["a", "b"], ["c", ""] ]
var duration = 5.minutes + 30.seconds;
duration += 0.5.hours
100.0.tweenTo(200.0); // Tween(begin: 100.0, end: 200.0)
Colors.red.tweenTo(Colors.blue); // ColorTween(...)
//Easy for loop
["dog", "cat"].forEachIndexed((index, value) {
print("$i : $value") // 1 : dog, 2 : cat
});
We can apply TextStyle to all the widgets in the hirarchy by wrapping it with DefaultTextStyle.
DefaultTextStyle(
child: Column(
children: <Widget>[
Text(
"DefaultTextStyle With Green text color",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20, color: Colors.black),
),
Text("Title"), //Green color, size 30
Text("SubTitle", style: TextStyle(fontSize: 25)), //Green color, size 25
Text("Heading", style: TextStyle(fontSize: 20)), //Green color, size 20
],
),
style: TextStyle(fontSize: 30, color: Colors.green),
);
You can use flutter_cache_manager
to Download and / or
Cache files.
//Get file from Cache and download if not cached already.
File file = await DefaultCacheManager().getSingleFile(url);
//Download File without caching
File file = await DefaultCacheManager().downloadFile(url);
flutter_linkify
is a Text Widget that automatically finds the URL link in the string and makes it clickable.
- Add dependency
dependencies:
flutter_linkify: ^version
- Enjoy
Linkify(
text: "My twitter https://twitter.com/erluxman",
onOpen: (LinkableElement url) {
Scaffold.of(context).showSnackBar(
SnackBar(content: Text("${url.text} clicked")),
);
},
)
We need to show loading/progress
in almost every apps, but CircularProgressBar
everywhere is boring.
flutter_spinkit
provides many awesome Progress indictors that we can use.
- Add dependency
flutter_spinkit: ^4.1.2+1
- Start Using
- Give
color (@required)
,size(optional)
andduration(optional)
to SpinKit* widgets.
SpinKitCircle(size: 90, color: Colors.cyan),
SpinKitChasingDots(size: 190, color: Colors.blue),
SpinKitCubeGrid(size: 90, color: Colors.blue),
SpinKitDualRing(size: 90, color: Colors.blue,),
SpinKitFadingCube(size: 90, color: Colors.red),
SpinKitFadingFour(size: 90, color: Colors.green)
We can show toast with oktoast
package.
- Add dependency:
dependencies:
oktoast: ^2.3.2
- Wrap
(Material/Cupertino)App
withOKToast
OKToast(
child: MaterialApp( home: child)
)
- Show
Text/Widget
asToast
by callingshowToast()/showToastWidget()
from anywhere.
import 'package:oktoast/oktoast.dart';
showToast("Hello world");
showToast(Text("Hello world"));
Almost every app needs setting page, but doing it right across multiple platform is not a easy.
- Add dependency
dependencies:
settings_ui: ^version
- Start Using
SettingsList( // Whole setting Page
sections: [
SettingsSection( // Set of similar settings items
title: 'Common',
tiles: [
SettingsTile( // Single Setting item
title: 'Language',
subtitle: 'English',
leading: Icon(Icons.language),
),
SettingsTile( // Single Setting item
title: 'Environment',
subtitle: 'Production',
leading: Icon(Icons.cloud_queue),
),
],
),
],
)
SettingList
-> Whole setting Page
SettingsSection
-> Set of similar settings Eg. Account, Security
SettingTile
-> Single Setting item Eg. Phone Number, Email
Android Setting | iOS Setting |
---|---|