1673055535
dart-vim-plugin provides filetype detection, syntax highlighting, and indentation for Dart code in Vim.
Looking for auto-complete, diagnostics as you type, jump to definition and other intellisense features? Try a vim plugin for the Language Server Protocol such as vim-lsc configured to start the Dart analysis server with the --lsp
flag.
Looking for an IDE experience? See the Dart Tools page.
Install as a typical vim plugin using your favorite approach. If you don't have a preference vim-plug is a good place to start. Below are examples for common choices, be sure to read the docs for each option.
call plug#begin()
"... <snip other plugins>
Plug 'dart-lang/dart-vim-plugin'
call plug#end()
Then invoke :PlugInstall
to install the plugin.
Clone the repository into your pathogen directory.
mkdir -p ~/.vim/bundle && cd ~/.vim/bundle && \
git clone https://github.com/dart-lang/dart-vim-plugin
Ensure your .vimrc
contains the line execute pathogen#infect()
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
"... <snip other plugins>
Plugin 'dart-lang/dart-vim-plugin'
call vundle#end()
Enable HTML syntax highlighting inside Dart strings with let dart_html_in_string=v:true
(default false).
Highlighting for specific syntax groups can be disabled by defining custom highlight group links. See :help dart-syntax
Enable Dart style guide syntax (like 2-space indentation) with let g:dart_style_guide = 2
Enable DartFmt execution on buffer save with let g:dart_format_on_save = 1
Configure DartFmt options with let g:dartfmt_options
(discover formatter options with dartfmt -h
)
dart format
?The indentation capabilities within vim are limited and it's not easy to fully express the indentation behavior of dart format
. The major area where this plugin differs from dart format
is indentation of function arguments when using a trailing comma in the argument list. When using a trailing comma (as is common in flutter widget code) dart format
uses 2 space indent for argument parameters. In all other indentation following an open parenthesis (argument lists without a trailing comma, multi-line assert statements, etc) dart format
uses 4 space indent. This plugin uses 4 space indent indent by default. To use 2 space indent by default, let g:dart_trailing_comma_indent = v:true
.
The Dart SDK comes with an analysis server that can be run in LSP mode. The server ships with the SDK. Assuming the bin
directory of the SDK is at $DART_SDK
the full command to run the analysis server in LSP mode is $DART_SDK/dart $DART_SDK/snapshots/analysis_server.dart.snapshot --lsp
. If you'll be opening files outside of the rootUri
sent by your LSP client (usually cwd
) you may want to pass onlyAnalyzeProjectsWithOpenFiles: true
in the initializationOptions
. See the documentation for your LSP client for how to configure initialization options. If you are using the vim-lsc plugin there is an additional plugin which can configure everything for you at vim-lsc-dart. A minimal config for a good default experience using vim-plug would look like:
call plug#begin()
Plug 'dart-lang/dart-vim-plugin'
Plug 'natebosch/vim-lsc'
Plug 'natebosch/vim-lsc-dart'
call plug#end()
let g:lsc_auto_map = v:true
Author: dart-lang
Source code: https://github.com/dart-lang/dart-vim-plugin
License: BSD-3-Clause license
1648873833
Table of Contents
LazyStream
in Flutter and DartFutureGroup
in DartIterable<bool>
in DartFuture<bool>
in FlutterString
Data in DartStream.startWith
in FlutterAnnotatedRegion
in FlutterMap
Equality in DartIterable
to ListView
in FlutterObject.toString()
in DartIterable
Subscripts in DartuseState
in Flutter HooksIterable
+/- in DartEmptyOnError
in DartStream<T>
Initial Value in FlutterDouble.normalize
in DartIterable.compactMap
in DartuseEffect
in Flutter HooksIsolate
Stream in DartListTile
Shadow in Flutter@useResult
in Dart@mustCallSuper
in DartObject.hash
in DartAsyncSnapshot
to Widget
in FlutterMap
Values in DartListView
in FlutterObject
in DartMap
in DartValueNotifier
in FlutterFuture
Error Test in FlutterFuture
Errors in DartFuture
Error Handling in DartMap<K,V>
in DartStream<List<T>>
in DartChangeNotifier
in FlutterOrientationBuilder
in FlutterCheckboxListTile
in Flutter-
Operator on String
in DartFuture<T>
List<T?>?
in DartList<T>
in DartList<List<T>>
in DartList<T>
in DartList<T>
in DartList<Uri>
in DartStream
and StreamBuilder
in FlutterStreamBuilder
and StreamController
in DartComparable
in Dartrethrow
ing Exceptions in Dartmixin
s and JSON Parsing in Dartmixin
s vs abstract class
es in DartLayoutBuilder
, CustomPaint
and CustomPainter
const
Constructors in Dartasync
-await
Over Raw Future
s in DartList<num>
in Dart
LazyStream
in Flutter and Dart
import 'dart:developer' as devtools show log;
import 'dart:typed_data' show Uint8List;
import 'package:flutter/services.dart' show NetworkAssetBundle, rootBundle;
import 'package:async/async.dart' show LazyStream;
extension LocalFileData on String {
Future<Uint8List> localFileData() => rootBundle.load(this).then(
(byteData) => byteData.buffer.asUint8List(),
);
}
extension Log on Object {
void log() => devtools.log(toString());
}
void testIt() async {
final stream = LazyStream(
() async {
final allData = await calculateAllData();
return getImagesData(allData);
},
);
await for (final data in stream) {
'Got data, length = ${data.length}'.log();
}
}
Stream<Uint8List> getImagesData(
List<Future<Uint8List>> allData,
) async* {
for (final data in allData) {
yield await data;
}
}
Future<List<Future<Uint8List>>> calculateAllData() async {
final futures = Iterable.generate(
3,
(i) => 'images/image_list${i + 1}.txt'
.localFileData()
.then((data) => String.fromCharCodes(data)),
);
final result = Future.wait(futures);
final lineSplitter = const LineSplitter();
List<Future<Uint8List>> allData = [];
for (final string in await result) {
final urls = lineSplitter.convert(string);
for (final url in urls) {
allData.add(
NetworkAssetBundle(Uri.parse(url))
.load(url)
.then((byteData) => byteData.buffer.asUint8List()),
);
}
}
return allData;
}
Cancelable APIs in Flutter
import 'dart:developer' as devtools show log;
import 'dart:typed_data' show Uint8List;
import 'package:flutter/services.dart' show NetworkAssetBundle, rootBundle;
import 'package:async/async.dart' show CancelableOperation;
extension Log on Object {
void log() => devtools.log(toString());
}
extension LocalFileData on String {
Future<Uint8List> localFileData() => rootBundle.load(this).then(
(byteData) => byteData.buffer.asUint8List(),
);
}
CancelableOperation<Uint8List> getImageOperation(String url) =>
CancelableOperation.fromFuture(
NetworkAssetBundle(Uri.parse(url))
.load(url)
.then((byteData) => byteData.buffer.asUint8List()),
onCancel: () => 'images/template.png'.localFileData(),
);
void testIt() async {
final operation = getImageOperation('http://127.0.0.1:5500/images/1.png');
final cancelledValue = await operation.cancel();
final result = await operation.valueOrCancellation(cancelledValue);
result?.log();
}
Asset Data in Flutter
import 'dart:typed_data' show Uint8List;
import 'package:flutter/services.dart' show rootBundle;
import 'dart:developer' as devtools show log;
extension Log on Object {
void log() => devtools.log(toString());
}
extension LocalFileData on String {
Future<Uint8List> localFileData() => rootBundle.load(this).then(
(byteData) => byteData.buffer.asUint8List(),
);
}
void testIt() async {
(await 'images/template.png'.localFileData()).log();
}
API Caching in Flutter
import 'dart:typed_data' show Uint8List;
import 'package:flutter/services.dart' show NetworkAssetBundle;
import 'dart:developer' as devtools show log;
import 'package:async/async.dart' show AsyncMemoizer;
extension Log on Object {
void log() => devtools.log(toString());
}
@immutable
class GetImageApi {
final String url;
final _fetch = AsyncMemoizer<Uint8List>();
GetImageApi({required this.url});
Future<Uint8List> fetch() => _fetch.runOnce(
() => NetworkAssetBundle(Uri.parse(url))
.load(url)
.then((byteData) => byteData.buffer.asUint8List()),
);
}
void testIt() async {
final api = GetImageApi(url: 'http://127.0.0.1:5500/images/1.png');
(await api.fetch()).log(); // fetched
(await api.fetch()).log(); // cached
}
FutureGroup
in Dart
mixin FutureConvertible<T> {
Future<T> toFuture();
}
@immutable
class LoginApi with FutureConvertible<bool> {
@override
Future<bool> toFuture() => Future.delayed(
const Duration(seconds: 1),
() => true,
);
}
@immutable
class SignUpApi with FutureConvertible<bool> {
@override
Future<bool> toFuture() => Future.delayed(
const Duration(seconds: 1),
() => true,
);
}
extension Flatten on Iterable<bool> {
bool flatten() => fold(
true,
(lhs, rhs) => lhs && rhs,
);
}
extension Log on Object {
void log() => devtools.log(toString());
}
Future<bool> startup({
required bool shouldLogin,
required bool shouldSignUp,
}) {
final group = FutureGroup<bool>();
if (shouldLogin) {
group.add(LoginApi().toFuture());
}
if (shouldSignUp) {
group.add(SignUpApi().toFuture());
}
group.close();
return group.future.then((bools) => bools.flatten());
}
void testIt() async {
final success = await startup(
shouldLogin: true,
shouldSignUp: false,
);
success.log();
}
Flatten Iterable<bool>
in Dart
extension Flatten on Iterable<bool> {
bool flatten() => fold(
true,
(lhs, rhs) => lhs && rhs,
);
}
void testIt() {
assert([true, false, true].flatten() == false);
assert([true, true, true].flatten() == true);
assert([false, false, false].flatten() == false);
assert([true].flatten() == true);
assert([false].flatten() == false);
}
Caching Temp Files in Flutter
@immutable
class NetworkImageAsset {
final String localPath;
final String url;
NetworkImageAsset({required int index})
: localPath = Directory.systemTemp.path + '/$index.png',
url = 'http://127.0.0.1:5500/images/$index}.png';
Future<bool> downloadAndSave() => NetworkAssetBundle(Uri.parse(url))
.load(url)
.then((byteData) => byteData.buffer.asUint8List())
.then((data) => File(localPath).writeAsBytes(data).then((_) => true))
.catchError((_) => false);
}
void testIt() async {
await Future.forEach(
Iterable.generate(
3,
(i) => NetworkImageAsset(index: i + 1),
),
(NetworkImageAsset asset) => asset.downloadAndSave(),
);
}
Custom Lists in Dart
import 'dart:developer' as devtools show log;
import 'dart:collection' show ListBase;
class LowercaseList extends ListBase<String> {
final List<String> _list = [];
@override
int get length => _list.length;
@override
set length(int newLength) => _list.length = newLength;
@override
String operator [](int index) => _list[index].toUpperCase();
@override
void operator []=(int index, value) => _list[index] = value;
@override
void addAll(Iterable<String> iterable) => _list.addAll(iterable);
@override
void add(String element) => _list.add(element);
}
extension Log on Object {
void log() => devtools.log(toString());
}
void testIt() {
final myList = LowercaseList();
myList.addAll(['foo', 'bar', 'baz']);
myList[0].log(); // FOO
myList[1].log(); // BAR
for (final item in myList) {
item.log(); // FOO, BAR, BAZ
}
}
Optional Chaining in Dart
@immutable
class Address {
final String? firstLine;
final String? secondLine;
const Address(this.firstLine, this.secondLine);
}
@immutable
class Person {
final Person? father;
final Address? address;
const Person(this.father, this.address);
}
extension GetFathersFirstAddressLine on Person {
String? get firstAddressLineOfFather => father?.address?.firstLine;
}
MapList in Flutter
extension MapToList<T> on Iterable<T> {
List<E> mapList<E>(E Function(T) toElement) =>
map(toElement).toList();
}
Future<bool>
in Flutter
Future<bool> uploadImage({
required File file,
required String userId,
}) =>
FirebaseStorage.instance
.ref(userId)
.child(const Uuid().v4())
.putFile(file)
.then((_) => true)
.catchError((_) => false);
Async Bloc Init in Flutter
class App extends StatelessWidget {
const App({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider<AppBloc>(
create: (context) => AppBloc()..add(const AppEventInitialize()),
child: MaterialApp(
title: 'Photo Library',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: BlocConsumer<AppBloc, AppState>(
listener: (context, state) {
// handle loading
if (state.isLoading) {
LoadingScreen().show(
context: context,
text: 'Loading...',
);
} else {
LoadingScreen().hide();
}
... rest of your code goes here
Firebase Auth Errors in Flutter
const authErrorMapping = {
'user-not-found': AuthErrorUserNotFound(),
'project-not-found': AuthErrorProjectNotFound(),
};
@immutable
abstract class AuthError {
factory AuthError.from(FirebaseAuthException exception) =>
authErrorMapping[exception.code.toLowerCase().trim()] ??
const AuthErrorUnknown();
}
@immutable
class AuthErrorUnknown implements AuthError {
const AuthErrorUnknown();
}
@immutable
class AuthErrorUserNotFound implements AuthError {
const AuthErrorUserNotFound();
}
@immutable
class AuthErrorProjectNotFound implements AuthError {
const AuthErrorProjectNotFound();
}
Debug Strings in Flutter
extension IfDebugging on String {
String? get ifDebugging => kDebugMode ? this : null;
}
class LoginView extends HookWidget {
const LoginView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final emailController = useTextEditingController(
text: 'foo@bar.com'.ifDebugging,
);
final passwordController = useTextEditingController(
text: 'foobarbaz'.ifDebugging,
);
// rest of your code would be here ...
Keyboard Appearance in Flutter
class LoginView extends HookWidget {
const LoginView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Log in'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: const [
TextField(
keyboardType: TextInputType.emailAddress,
keyboardAppearance: Brightness.dark,
),
TextField(
obscureText: true,
obscuringCharacter: '◉',
),
],
),
),
);
}
}
Get String
Data in Dart
extension ToList on String {
Uint8List toUint8List() => Uint8List.fromList(codeUnits);
}
final text1Data = 'Foo'.toUint8List();
final text2Data = 'Bar'.toUint8List();
Stream.startWith
in Flutter
import 'package:async/async.dart' show StreamGroup;
import 'dart:developer' as devtools show log;
extension Log on Object {
void log() => devtools.log(toString());
}
extension StartWith<T> on Stream<T> {
Stream<T> startWith(T value) => StreamGroup.merge([
this,
Stream<T>.value(value),
]);
}
void testIt() {
Stream.periodic(const Duration(seconds: 1), (i) => i + 1)
.startWith(0)
.take(4)
.forEach((element) {
element.log();
}); // 0, 1, 2, 3
}
Optional Functions in Dart
typedef AppBlocRandomUrlPicker = String Function(Iterable<String> allUrls);
extension RandomElement<T> on Iterable<T> {
T getRandomElement() => elementAt(
math.Random().nextInt(length),
);
}
class AppBloc extends Bloc<AppEvent, AppState> {
String _pickRandomUrl(Iterable<String> allUrls) => allUrls.getRandomElement();
AppBloc({
required Iterable<String> urls,
AppBlocRandomUrlPicker? urlPicker,
}) : super(const AppState.empty()) {
on<LoadNextUrlEvent>(
(event, emit) {
emit(
const AppState(
isLoading: true,
data: null,
),
);
// pick a random URL to load
final url = (urlPicker ?? _pickRandomUrl)(urls);
HttpClient().getUrl(Uri.parse(url)); // continue here...
},
);
}
}
AnnotatedRegion
in Flutter
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.dark,
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
Expanded(child: Container(color: Colors.blue)),
Expanded(child: Container(color: Colors.yellow)),
],
),
),
);
}
}
Unordered Map
Equality in Dart
import 'package:collection/collection.dart';
import 'dart:developer' as devtools show log;
extension Log on Object {
void log() => devtools.log(toString());
}
extension UnorderedEquality<K, V> on Map<K, V> {
bool isEqualTo(Map<K, V> other) =>
const DeepCollectionEquality.unordered().equals(this, other);
}
void testIt() {
final dict1 = {
'name': 'foo',
'age': 20,
'values': ['foo', 'bar'],
};
final dict2 = {
'age': 20,
'name': 'foo',
'values': ['bar', 'foo'],
};
dict1.isEqualTo(dict2).log(); // true
}
Iterable
to ListView
in Flutter
extension ToListView<T> on Iterable<T> {
Widget toListView() => IterableListView(
iterable: this,
);
}
class IterableListView<T> extends StatelessWidget {
final Iterable<T> iterable;
const IterableListView({
Key? key,
required this.iterable,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: iterable.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
iterable.elementAt(index).toString(),
),
);
},
);
}
}
@immutable
class Person {
final String name;
final int age;
const Person({required this.name, required this.age});
@override
String toString() => '$name, $age years old';
}
const persons = [
Person(name: 'Foo', age: 20),
Person(name: 'Bar', age: 30),
Person(name: 'Baz', age: 40),
];
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home Page'),
),
body: persons.toListView(),
);
}
}
Password Mask in Flutter
class PasswordTextField extends StatelessWidget {
const PasswordTextField({
Key? key,
required this.passwordController,
}) : super(key: key);
final TextEditingController passwordController;
@override
Widget build(BuildContext context) {
return TextField(
controller: passwordController,
obscureText: true,
obscuringCharacter: '◉',
decoration: const InputDecoration(
hintText: 'Enter your password here...',
),
);
}
}
Fast Object.toString()
in Dart
@immutable
class AppState {
final bool isLoading;
final Object? loginError;
final String? loginHandle;
final Iterable<String>? fetchedNotes;
@override
String toString() => {
'isLoading': isLoading,
'loginError': loginError,
'loginHandle': loginHandle,
'fetchedNotes': fetchedNotes
}.toString();
const AppState({
required this.isLoading,
required this.loginError,
required this.loginHandle,
required this.fetchedNotes,
});
}
Copying Bloc State in Flutter
@immutable
class AppState {
final bool isLoading;
final LoginHandle? loginHandle;
final Iterable<Note>? fetchedNotes;
const AppState.empty()
: isLoading = false,
loginHandle = null,
fetchedNotes = null;
const AppState({
required this.isLoading,
required this.loginHandle,
required this.fetchedNotes,
});
AppState copiedWith({
bool? isLoading,
LoginHandle? loginHandle,
Iterable<Note>? fetchedNotes,
}) =>
AppState(
isLoading: isLoading ?? this.isLoading,
loginHandle: loginHandle ?? this.loginHandle,
fetchedNotes: fetchedNotes ?? this.fetchedNotes,
);
}
Iterable
Subscripts in Dart
// Free Flutter Course 💙 https://linktr.ee/vandadnp
// Want to support my work 🤝? https://buymeacoffee.com/vandad
import 'dart:developer' as devtools show log;
extension Log on Object? {
void log() => devtools.log(toString());
}
extension Subscript<T> on Iterable<T> {
T? operator [](int index) => length > index ? elementAt(index) : null;
}
void testIt() {
Iterable.generate(10, (i) => i + 1)[0].log(); // 1
Iterable.generate(1, (i) => i)[2].log(); // null
Iterable.generate(10, (i) => i + 1)[9].log(); // 10
Iterable.generate(0, (i) => i)[0].log(); // null
}
useState
in Flutter Hooks
import 'package:flutter_hooks/flutter_hooks.dart';
import 'dart:math' show min;
@immutable
class VirtualTab {
final Icon icon;
final String text;
const VirtualTab({
required this.icon,
required this.text,
});
}
const tabs = [
VirtualTab(
icon: Icon(Icons.picture_as_pdf),
text: 'All PDF files',
),
VirtualTab(
icon: Icon(Icons.ac_unit_outlined),
text: 'Data page',
),
VirtualTab(
icon: Icon(Icons.person),
text: 'Profile page',
),
];
class HomePage extends HookWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final tabCount = useState(1);
return DefaultTabController(
length: tabCount.value,
initialIndex: tabCount.value - 1,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: tabs
.take(tabCount.value)
.map((tab) => Tab(icon: tab.icon))
.toList(),
),
),
body: CustomTabBarView(tabCount: tabCount),
),
);
}
}
class CustomTabBarView extends StatelessWidget {
const CustomTabBarView({
Key? key,
required this.tabCount,
}) : super(key: key);
final ValueNotifier<int> tabCount;
@override
Widget build(BuildContext context) {
return TabBarView(
children: tabs
.take(tabCount.value)
.map(
(tab) => Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(tab.text),
TextButton(
onPressed: () {
final newLength = min(
tabs.length,
tabCount.value + 1,
);
tabCount.value = newLength;
},
child: const Text('Create next tab'),
)
],
),
),
)
.toList(),
);
}
}
Folding Iterables in Dart
import 'dart:developer' as devtools show log;
extension Log on Object {
void log() => devtools.log(toString());
}
void testIt() {
final values = ['foo', 'bar', 'baz', '1.0'];
values.fold<int>(0, (pe, e) => pe + e.length); // 12
values.fold<String>('', (pe, e) => '$pe$e'); // foobarbaz1.0
values.fold<Map<String, int>>(
{},
(pe, e) => pe..addAll(<String, int>{e: e.length}),
).log(); // {foo: 3, bar: 3, baz: 3, 1.0: 3}
values.fold<double>(
0.0,
(pe, e) => pe + (double.tryParse(e) ?? 0.0),
); // 1.0
}
Custom Iterables in Dart
class Address with IterableMixin {
final String line1;
final String line2;
final String postCode;
Address({
required this.line1,
required this.line2,
required this.postCode,
});
@override
Iterator<String> get iterator => [line1, line2, postCode].iterator;
}
void testIt() {
final address = Address(
line1: 'Foo bar avenue, #10',
line2: 'Baz street',
postCode: '123456',
);
for (final line in address) {
devtools.log(line);
}
}
Class Clusters in Dart
enum AnimalType { dog, cat }
@immutable
abstract class Animal {
const Animal();
factory Animal.fromType(AnimalType type) {
switch (type) {
case AnimalType.dog:
return const Dog();
case AnimalType.cat:
return const Cat();
}
}
void makeNoise();
}
@immutable
class Dog extends Animal {
const Dog();
@override
void makeNoise() => 'Woof'.log();
}
@immutable
class Cat extends Animal {
const Cat();
@override
void makeNoise() => 'Meow'.log();
}
void testIt() {
final cat = Animal.fromType(AnimalType.cat);
cat.makeNoise();
final dog = Animal.fromType(AnimalType.dog);
dog.makeNoise();
}
Iterable
+/- in Dart
extension AddRemoveItems<T> on Iterable<T> {
Iterable<T> operator +(T other) => followedBy([other]);
Iterable<T> operator -(T other) => where((element) => element != other);
}
void testIt() {
final values = ['foo', 'bar']
.map((e) => e.toUpperCase()) + 'BAZ';
values.log(); // (FOO, BAR, BAZ)
(values - 'BAZ').log(); // (FOO, BAR)
}
Periodic Streams in Dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:developer' as devtools show log;
extension Log on Object {
void log() => devtools.log(toString());
}
@immutable
class Person {
final String name;
final int age;
const Person({
required this.name,
required this.age,
});
Person.fromJson(Map<String, dynamic> json)
: name = json["name"] as String,
age = json["age"] as int;
@override
String toString() => 'Person ($name, $age years old)';
}
mixin ListOfThingsAPI<T> {
Future<Iterable<T>> get(String url) => HttpClient()
.getUrl(Uri.parse(url))
.then((req) => req.close())
.then((resp) => resp.transform(utf8.decoder).join())
.then((str) => json.decode(str) as List<dynamic>)
.then((list) => list.cast());
}
class GetPeople with ListOfThingsAPI<Map<String, dynamic>> {
Future<Iterable<Person>> getPeople(url) => get(url).then(
(jsons) => jsons.map(
(json) => Person.fromJson(json),
),
);
}
Stream<dynamic> every(Duration duration) => Stream.periodic(duration);
extension IntToDuration on int {
Duration get seconds => Duration(seconds: this);
}
void testIt() async {
await for (final people in every(3.seconds).asyncExpand(
(_) => GetPeople()
.getPeople('http://127.0.0.1:5500/apis/people1.json')
.asStream(),
)) {
people.log();
}
}
/* people1.json
[
{
"name": "Foo 1",
"age": 20
},
{
"name": "Bar 1",
"age": 30
}
]
*/
EmptyOnError
in Dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:developer' as devtools show log;
extension Log on Object {
void log() => devtools.log(toString());
}
@immutable
class Person {
final String name;
final int age;
const Person({
required this.name,
required this.age,
});
Person.fromJson(Map<String, dynamic> json)
: name = json["name"] as String,
age = json["age"] as int;
@override
String toString() => 'Person ($name, $age years old)';
}
const people1Url = 'http://127.0.0.1:5500/apis/people11.json';
const people2Url = 'http://127.0.0.1:5500/apis/people2.json';
extension EmptyOnError<E> on Future<List<Iterable<E>>> {
Future<List<Iterable<E>>> emptyOnError() => catchError(
(_, __) => List<Iterable<E>>.empty(),
);
}
Future<Iterable<Person>> parseJson(String url) => HttpClient()
.getUrl(Uri.parse(url))
.then((req) => req.close())
.then((resp) => resp.transform(utf8.decoder).join())
.then((str) => json.decode(str) as List<dynamic>)
.then((json) => json.map((e) => Person.fromJson(e)));
void testIt() async {
final persons = await Future.wait([
parseJson(people1Url),
parseJson(people2Url),
]).emptyOnError();
persons.log();
}
Stream<T>
Initial Value in Flutter
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
void main() {
runApp(
MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: const HomePage(),
),
);
}
const url = 'https://bit.ly/3x7J5Qt';
class HomePage extends HookWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
late final StreamController<double> controller;
controller = useStreamController<double>(onListen: () {
controller.sink.add(0.0);
});
return Scaffold(
appBar: AppBar(
title: const Text('Home page'),
),
body: StreamBuilder<double>(
stream: controller.stream,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const CircularProgressIndicator();
} else {
final rotation = snapshot.data ?? 0.0;
return GestureDetector(
onTap: () {
controller.sink.add(rotation + 10.0);
},
child: RotationTransition(
turns: AlwaysStoppedAnimation(rotation / 360.0),
child: Center(
child: Image.network(url),
),
),
);
}
}),
);
}
}
Double.normalize
in Dart
import 'dart:developer' as devtools show log;
extension Normalize on double {
double normalized(
double selfRangeMin,
double selfRangeMax, [
double normalizedRangeMin = 0.0,
double normalizedRangeMax = 1.0,
]) =>
(normalizedRangeMax - normalizedRangeMin) *
((this - selfRangeMin) / (selfRangeMax - selfRangeMin)) +
normalizedRangeMin;
}
extension Log on Object {
void log() => devtools.log(toString());
}
void testIt() async {
2.0.normalized(0, 2.0).log(); // 1.0
4.0.normalized(0, 8.0).log(); // 0.5
5.0.normalized(4.0, 6.0, 10.0, 20.0).log(); // 15
}
Hide Sensitive Information in Flutter
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
void main() {
runApp(
MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: const HomePage(),
),
);
}
class HomePage extends HookWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final state = useAppLifecycleState();
return Scaffold(
appBar: AppBar(
title: const Text('Home Page'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Opacity(
opacity: state == AppLifecycleState.resumed ? 1.0 : 0.0,
child: Container(
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
blurRadius: 10,
color: Colors.black.withAlpha(100),
spreadRadius: 10,
),
],
),
child: Image.asset('assets/card.png'),
),
),
),
);
}
}
Iterable.compactMap
in Dart
import 'dart:developer' as devtools show log;
extension Log on Object {
void log() => devtools.log(toString());
}
extension CompactMap<T> on Iterable<T?> {
Iterable<T> compactMap<E>([
E? Function(T?)? transform,
]) =>
map(transform ?? (e) => e).where((e) => e != null).cast();
}
const list = ['Hello', null, 'World'];
void testIt() {
list.log(); // [Hello, null, World]
list.compactMap().log(); // [Hello, World]
list.compactMap((e) => e?.toUpperCase()).log(); // [HELLO, WORLD]
}
useEffect
in Flutter Hooks
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
void main() {
runApp(
MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: const HomePage(),
),
);
}
class HomePage extends HookWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final controller = useTextEditingController();
final text = useState('');
useEffect(
() {
void listener() {
text.value = controller.text;
}
controller.addListener(listener);
return () => controller.removeListener(listener);
},
[controller],
);
return Scaffold(
body: Column(
children: [
TextField(
controller: controller,
),
Text('You typed ${text.value}')
],
),
);
}
}
Merging Streams in Dart
import 'package:async/async.dart' show StreamGroup;
import 'dart:developer' as devtools show log;
extension Log on Object {
void log() => devtools.log(toString());
}
void testIt() async {
final streams = Iterable.generate(
3,
(i) => Stream.periodic(
const Duration(seconds: 1),
(_) => 'Stream $i: ${DateTime.now().toIso8601String()}',
).take(i + 1),
);
await for (final now in StreamGroup.merge(streams)) {
now.log();
}
}
Isolate
Stream in Dart
Stream<String> getMessages() {
final rp = ReceivePort();
return Isolate.spawn(_getMessages, rp.sendPort)
.asStream()
.asyncExpand((_) => rp)
.takeWhile((element) => element is String)
.cast();
}
void _getMessages(SendPort sp) async {
await for (final now in Stream.periodic(
const Duration(seconds: 1),
(_) => DateTime.now().toIso8601String(),
).take(10)) {
sp.send(now);
}
Isolate.exit(sp);
}
void testIt() async {
await for (final msg in getMessages()) {
msg.log();
}
}
Network Image Retry in Flutter
@immutable
class RetryStrategy {
final bool shouldRetry;
final Duration waitBeforeRetry;
const RetryStrategy({
required this.shouldRetry,
required this.waitBeforeRetry,
});
}
typedef Retrier = RetryStrategy Function(String url, Object error);
class NetworkImageWithRetry extends StatelessWidget {
final Widget loadingWidget;
final Widget errorWidget;
final String url;
final Retrier retrier;
final _controller = StreamController<Uint8List>.broadcast();
NetworkImageWithRetry({
Key? key,
required this.url,
required this.retrier,
required this.loadingWidget,
required this.errorWidget,
}) : super(key: key);
void getData() async {
while (true == true) {
try {
final networkAsset = NetworkAssetBundle(Uri.parse(url));
final loaded = await networkAsset.load(url);
final bytes = loaded.buffer.asUint8List();
_controller.sink.add(bytes);
break;
} catch (e) {
final strategy = retrier(url, e);
if (strategy.shouldRetry) {
await Future.delayed(strategy.waitBeforeRetry);
} else {
_controller.sink.addError(e);
break;
}
}
}
}
@override
Widget build(BuildContext context) {
getData();
return StreamBuilder(
stream: _controller.stream,
builder: (context, AsyncSnapshot<Uint8List> snapshot) {
if (snapshot.hasError) {
return errorWidget;
} else {
final data = snapshot.data;
if (snapshot.hasData && data != null) {
return Image.memory(data);
} else {
return loadingWidget;
}
}
},
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Image Retry'),
),
body: NetworkImageWithRetry(
url: 'https://bit.ly/3qYOtDm',
errorWidget: const Text('Got an error!'),
loadingWidget: const Text('Loading...'),
retrier: (url, error) {
return RetryStrategy(
shouldRetry: error is! FlutterError,
waitBeforeRetry: const Duration(seconds: 1),
);
},
),
);
}
}
Reusable APIs in Flutter
import 'dart:io';
import 'package:flutter/material.dart';
import 'dart:developer' as devtools show log;
import 'dart:convert' show utf8;
import 'package:meta/meta.dart' show useResult;
extension Log on Object {
void log() => devtools.log(toString());
}
extension GetOnUri on Object {
Future<HttpClientResponse> getUrl(
String url,
) =>
HttpClient()
.getUrl(
Uri.parse(
url,
),
)
.then((req) => req.close());
}
mixin CanMakeGetCall {
String get url;
@useResult
Future<String> getString() => getUrl(url).then(
(response) => response
.transform(
utf8.decoder,
)
.join(),
);
}
@immutable
class GetPeople with CanMakeGetCall {
const GetPeople();
@override
String get url => 'http://127.0.0.1:5500/apis/people.json';
}
void testIt() async {
final people = await const GetPeople().getString();
devtools.log(people);
}
ListTile
Shadow in Flutter
enum Currency { dollars }
extension Title on Currency {
String get title {
switch (this) {
case Currency.dollars:
return '\$';
}
}
}
@immutable
class Item {
final IconData icon;
final String name;
final double price;
final Currency currency;
const Item({
required this.icon,
required this.name,
required this.price,
required this.currency,
});
String get description => '$price${currency.title}';
}
const items = [
Item(
icon: Icons.camera_alt,
name: 'Camera',
price: 300,
currency: Currency.dollars,
),
Item(
icon: Icons.house,
name: 'House',
price: 1000000,
currency: Currency.dollars,
),
Item(
icon: Icons.watch,
name: 'Smart Watch',
price: 200,
currency: Currency.dollars,
),
];
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home Page'),
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (_, index) {
return ItemTile(
item: items[index],
);
},
),
);
}
}
class ItemTile extends StatelessWidget {
final Item item;
const ItemTile({Key? key, required this.item}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Stack(
children: [
const TileBackground(),
CustomTile(item: item),
],
),
);
}
}
class CustomTile extends StatelessWidget {
final Item item;
const CustomTile({
Key? key,
required this.item,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 7.0),
child: Container(
decoration: customDecoration(),
child: ListTile(
leading: Icon(
item.icon,
color: Colors.white,
),
title: Text(item.name),
subtitle: Text(item.description),
),
),
);
}
}
BoxDecoration customDecoration() {
return BoxDecoration(
color: const Color.fromARGB(255, 0x7d, 0xcf, 0xff),
borderRadius: BorderRadius.circular(10.0),
border: Border.all(
color: Colors.black,
width: 2.0,
),
);
}
class TileBackground extends StatelessWidget {
const TileBackground({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Positioned.fill(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 6.0),
child: Container(
decoration: BoxDecoration(
color: const Color.fromARGB(255, 202, 255, 127),
borderRadius: BorderRadius.circular(10.0),
border: Border.all(
color: Colors.black,
width: 2.0,
),
),
),
),
);
}
}
Transparent AppBar in Flutter
const images = [
'https://bit.ly/3x7J5Qt',
'https://bit.ly/3ywI8l6',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3qYOtDm',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3yvFg7X',
'https://bit.ly/3ywzOla',
'https://bit.ly/3wnASpW',
'https://bit.ly/3jXSDto',
];
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
appBar: AppBar(
elevation: 0.0,
backgroundColor: Colors.blueAccent.withAlpha(200),
title: const Text('Transparent App Bar in Flutter'),
),
body: const ImagesScrollView(),
);
}
}
class ImagesScrollView extends StatelessWidget {
const ImagesScrollView({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
padding: const EdgeInsets.only(top: 80.0),
child: Padding(
padding: const EdgeInsets.only(
top: 40.0,
left: 10.0,
right: 10.0,
),
child: Column(
children: images
.map((url) => ElevatedNetworkImage(url: url))
.expand(
(img) => [
img,
const SizedBox(height: 30.0),
],
)
.toList(),
),
),
);
}
}
class ElevatedNetworkImage extends StatelessWidget {
final String url;
const ElevatedNetworkImage({Key? key, required this.url}) : super(key: key);
@override
Widget build(BuildContext context) {
return PhysicalShape(
color: Colors.white,
clipper: Clipper(),
elevation: 20.0,
clipBehavior: Clip.none,
shadowColor: Colors.white.withAlpha(200),
child: CutEdges(
child: Image.network(url),
),
);
}
}
class Clipper extends CustomClipper<Path> {
static const variance = 0.2;
static const reverse = 1.0 - variance;
@override
Path getClip(Size size) {
final path = Path();
path.moveTo(0.0, size.height * Clipper.variance);
path.lineTo(size.width * Clipper.variance, 0.0);
path.lineTo(size.width, 0.0);
path.lineTo(size.width, size.height * Clipper.reverse);
path.lineTo(size.width * Clipper.reverse, size.height);
path.lineTo(0.0, size.height);
path.lineTo(0.0, size.height * Clipper.variance);
path.close();
return path;
}
@override
bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false;
}
class CutEdges extends StatelessWidget {
final Widget child;
const CutEdges({Key? key, required this.child}) : super(key: key);
@override
Widget build(BuildContext context) {
return ClipPath(
clipper: Clipper(),
child: child,
);
}
}
Constructors on Abstract Classes in Dart
import 'dart:developer' as devtools show log;
extension Log on Object {
void log() => devtools.log(toString());
}
enum Type { dog, cat }
abstract class CanRun {
final Type type;
const CanRun({required this.type});
}
class Cat extends CanRun {
const Cat() : super(type: Type.cat);
}
class Dog extends CanRun {
const Dog() : super(type: Type.dog);
}
@useResult
in Dart
import 'package:meta/meta.dart' show useResult;
class Person {
final String firstName;
final String lastName;
const Person({
required this.firstName,
required this.lastName,
});
@useResult
String fullName() => '$firstName $lastName';
}
void printFullName() {
const Person(
firstName: 'Foo',
lastName: 'Bar',
).fullName();
}
@mustCallSuper
in Dart
class Animal {
@mustCallSuper
void run() {}
}
class Dog extends Animal {
@override
void run() {}
}
Object.hash
in Dart
class BreadCrumb {
final bool isActive;
final String name;
BreadCrumb({
required this.isActive,
required this.name,
});
BreadCrumb activated() => BreadCrumb(
isActive: true,
name: name,
);
@override
bool operator ==(covariant BreadCrumb other) =>
isActive == other.isActive && name == other.name;
@override
int get hashCode => Object.hash(isActive, name);
}
Expanded Equally in Flutter
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: const HomePage(),
),
);
}
extension ExpandEqually on Iterable<Widget> {
Iterable<Widget> expandedEqually() => map(
(w) => Expanded(
flex: 1,
child: w,
),
);
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home Page'),
),
body: Column(
children: [
Row(
mainAxisSize: MainAxisSize.max,
children: [
Container(
height: 200,
color: Colors.yellow,
),
Container(
height: 200,
color: Colors.blue,
),
].expandedEqually().toList(),
)
],
),
);
}
}
Random Iterable Value in Dart
import 'dart:math' as math show Random;
extension RandomElement<T> on Iterable<T> {
T getRandomElement() => elementAt(
math.Random().nextInt(length),
);
}
final colors = [Colors.blue, Colors.red, Colors.brown];
class HomePage extends StatelessWidget {
final color = ValueNotifier<MaterialColor>(
colors.getRandomElement(),
);
HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('List.Random in Flutter'),
),
body: ColorPickerButton(color: color),
);
}
}
class ColorPickerButton extends StatelessWidget {
final ValueNotifier<MaterialColor> color;
const ColorPickerButton({
Key? key,
required this.color,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<Color>(
valueListenable: color,
builder: (context, value, child) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: CenteredTight(
child: TextButton(
style: TextButton.styleFrom(backgroundColor: value),
onPressed: () {
color.value = colors.getRandomElement();
},
child: const Text(
'Change color',
style: TextStyle(
fontSize: 30,
color: Colors.white,
),
),
),
),
);
},
);
}
}
Hardcoded Strings in Flutter
extension Hardcoded on String {
String get hardcoded => '$this 🧨';
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'My hardcoded string'.hardcoded,
),
),
body: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('String in body'.hardcoded),
],
),
);
}
}
Manually Scroll in List View in Flutter
// Free Flutter Course 💙 https://linktr.ee/vandadnp
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
class HomePage extends StatelessWidget {
final _controller = ItemScrollController();
HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Testing'),
),
body: ScrollablePositionedList.builder(
itemScrollController: _controller,
itemCount: allImages.length + 1,
itemBuilder: (context, index) {
if (index == 0) {
return IndexSelector(
count: allImages.length,
onSelected: (index) {
_controller.scrollTo(
index: index + 1,
duration: const Duration(milliseconds: 370),
);
},
);
} else {
return ImageWithTitle(index: index);
}
},
),
);
}
}
class ImageWithTitle extends StatelessWidget {
final int index;
const ImageWithTitle({
Key? key,
required this.index,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: [
Text(
'Image $index',
style: const TextStyle(fontSize: 30.0),
),
Image.network(allImages.elementAt(index - 1)),
],
);
}
}
typedef OnIndexSelected = void Function(int index);
class IndexSelector extends StatelessWidget {
final int count;
final OnIndexSelected onSelected;
final String prefix;
const IndexSelector({
Key? key,
required this.count,
required this.onSelected,
this.prefix = 'Image',
}) : super(key: key);
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: Iterable.generate(
count,
(index) => TextButton(
onPressed: () {
onSelected(index);
},
child: Text('$prefix ${index + 1}'),
),
).toList(),
),
);
}
}
const imageUrls = [
'https://bit.ly/3ywI8l6',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3qYOtDm',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3yvFg7X',
'https://bit.ly/3ywzOla',
'https://bit.ly/3wnASpW',
'https://bit.ly/3jXSDto',
];
AsyncSnapshot
to Widget
in Flutter
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
void main() {
runApp(
MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const HomePage(),
),
);
}
final future = Future<String>.delayed(
const Duration(seconds: 3),
() => 'Hello world',
);
typedef ResolveToWidget<T> = Widget Function(
ConnectionState connectionState,
AsyncSnapshot<T> snapshot,
);
extension Materialize on AsyncSnapshot {
Widget materialize(ResolveToWidget f) => f(
connectionState,
this,
);
}
class HomePage extends HookWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Hooks'),
),
body: useFuture(future).materialize((connectionState, snapshot) {
switch (connectionState) {
case ConnectionState.done:
return Text(snapshot.data ?? '');
default:
return const CircularProgressIndicator();
}
}),
);
}
}
Breadcrumbs in Flutter
@immutable
class BreadCrumbPath {
final String title;
final bool isActive;
const BreadCrumbPath({
required this.title,
required this.isActive,
});
BreadCrumbPath activated() {
return BreadCrumbPath(
title: title,
isActive: true,
);
}
@override
String toString() => title;
}
class BreatCrumbPathView extends StatelessWidget {
final BreadCrumbPath path;
const BreatCrumbPathView({
Key? key,
required this.path,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final title = path.isActive ? '${path.title} →' : path.title;
return Padding(
padding: const EdgeInsets.all(2.0),
child: Text(
title,
style: TextStyle(
height: 1.0,
fontSize: 20.0,
color: path.isActive ? Colors.blueAccent : Colors.black,
),
),
);
}
}
typedef OnBreadCrumbPathTapped = void Function(BreadCrumbPath path);
class BreadCrumbView extends StatelessWidget {
final OnBreadCrumbPathTapped onTapped;
final Stream<List<BreadCrumbPath>> paths;
const BreadCrumbView({
Key? key,
required this.paths,
required this.onTapped,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return StreamBuilder<List<BreadCrumbPath>>(
stream: paths,
builder: (context, snapshot) {
final List<Widget> views;
switch (snapshot.connectionState) {
case ConnectionState.waiting:
case ConnectionState.active:
final paths = snapshot.data ?? [];
final views = paths
.map(
(path) => GestureDetector(
onTap: () => onTapped(path),
child: BreatCrumbPathView(path: path),
),
)
.toList();
return Wrap(
spacing: 4.0,
children: views,
alignment: WrapAlignment.start,
crossAxisAlignment: WrapCrossAlignment.center,
);
default:
return Wrap();
}
},
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<BreadCrumbPath> _paths = [];
late final TextEditingController _textController;
late final StreamController<List<BreadCrumbPath>> _pathsController;
@override
void initState() {
_pathsController = StreamController<List<BreadCrumbPath>>.broadcast(
onListen: () {
_pathsController.add(_paths);
},
);
_textController = TextEditingController();
super.initState();
}
@override
void dispose() {
_textController.dispose();
_pathsController.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Breadcrumb in Flutter'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
BreadCrumbView(
paths: _pathsController.stream,
onTapped: (path) async {
await showBreadCrumbPathTappedDialog(
context,
path,
);
},
),
TextField(
controller: _textController,
textAlign: TextAlign.center,
decoration: const InputDecoration(
hintText: 'Enter a new path here',
),
),
TextButton(
onPressed: () {
_paths = [
..._paths.map((p) => p.activated()),
BreadCrumbPath(
title: _textController.text,
isActive: false,
),
];
_pathsController.add(_paths);
_textController.clear();
},
child: const Center(
child: Text('Add new path'),
),
),
],
),
),
);
}
}
Future<void> showBreadCrumbPathTappedDialog(
BuildContext context,
BreadCrumbPath path,
) {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text('You tapped on $path'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('OK'),
),
],
);
},
);
}
Unique Map
Values in Dart
import 'dart:developer' as devtools show log;
extension ContainsDuplicateValues on Map {
bool get containsDuplicateValues =>
{...values}.length != values.length;
}
extension Log on Object {
void log() => devtools.log(toString());
}
const people1 = {
1: 'Foo',
2: 'Bar',
};
const people2 = {
1: 'Foo',
2: 'Foo',
};
void testIt() {
people1.containsDuplicateValues.log(); // false
people2.containsDuplicateValues.log(); // true
}
Smart Quotes/Dashes in Flutter
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Smart Quotes/Dashes in Flutter'),
),
body: const Padding(
padding: EdgeInsets.all(16.0),
child: TextField(
smartQuotesType: SmartQuotesType.disabled,
smartDashesType: SmartDashesType.disabled,
maxLines: null,
),
),
);
}
}
Haptic Feedback in Flutter
class CenteredTight extends StatelessWidget {
final Widget child;
const CenteredTight({
Key? key,
required this.child,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [child],
);
}
}
class FullscreenImage extends StatefulWidget {
final String imageUrl;
const FullscreenImage({Key? key, required this.imageUrl}) : super(key: key);
@override
State<FullscreenImage> createState() => _FullscreenImageState();
}
class _FullscreenImageState extends State<FullscreenImage> {
var shouldDisplayAppbar = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: shouldDisplayAppbar ? AppBar(title: const Text('Image')) : null,
body: GestureDetector(
onTap: () {
setState(() => shouldDisplayAppbar = !shouldDisplayAppbar);
},
child: Image.network(
widget.imageUrl,
alignment: Alignment.center,
width: double.infinity,
height: double.infinity,
fit: BoxFit.cover,
),
),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Haptic Feedback in Flutter'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: CenteredTight(
child: FractionallySizedBox(
heightFactor: 0.7,
child: GestureDetector(
onLongPress: () async {
await HapticFeedback.lightImpact();
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const FullscreenImage(
imageUrl: imageUrl,
);
},
),
);
},
child: Image.network(imageUrl),
),
),
),
),
);
}
}
Localization Delegates in Flutter
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: BlocProvider<AuthBloc>(
create: (context) => AuthBloc(FirebaseAuthProvider()),
child: const HomePage(),
),
routes: {
createOrUpdateNoteRoute: (context) => const CreateUpdateNoteView(),
},
),
);
}
Extending Functions in Dart
import 'dart:developer' as devtools show log;
extension ToTextButton on VoidCallback {
TextButton toTextButton(String title) {
return TextButton(
onPressed: this,
child: Text(title),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Extensions in Flutter'),
),
body: () {
devtools.log('I am pressed');
}.toTextButton('Press me'),
);
}
}
Paginated ListView
in Flutter
@immutable
class Season {
final String name;
final String imageUrl;
const Season({required this.name, required this.imageUrl});
const Season.spring()
: name = 'Spring',
imageUrl = 'https://cnn.it/3xu58Ap';
const Season.summer()
: name = 'Summer',
imageUrl = 'https://bit.ly/2VcCSow';
const Season.autumn()
: name = 'Autumn',
imageUrl = 'https://bit.ly/3A3zStC';
const Season.winter()
: name = 'Winter',
imageUrl = 'https://bit.ly/2TNY7wi';
}
const allSeasons = [
Season.spring(),
Season.summer(),
Season.autumn(),
Season.winter()
];
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
final height = width / (16.0 / 9.0);
return Scaffold(
appBar: AppBar(
title: const Text('PageScrollPhysics in Flutter'),
),
body: SizedBox(
width: width,
height: height,
child: ListView(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
physics: const PageScrollPhysics(),
clipBehavior: Clip.antiAlias,
children: allSeasons.map((season) {
return SizedBox(
width: width,
height: height,
child: Image.network(
season.imageUrl,
height: height,
fit: BoxFit.cover,
),
);
}).toList(),
),
),
);
}
}
Immutable Classes in Dart
import 'package:flutter/foundation.dart' show immutable;
@immutable
abstract class Animal {
final String name;
const Animal(this.name);
}
class Cat extends Animal {
const Cat() : super('Cindy Clawford');
}
class Dog extends Animal {
int age;
Dog()
: age = 0,
super('Bark Twain');
}
Card Widget in Flutter
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Card in Flutter'),
),
body: Image.network(
'https://bit.ly/36fNNj9',
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
return Card(
child: child,
clipBehavior: Clip.antiAlias,
);
},
loadingBuilder: (context, child, loadingProgress) {
final totalBytes = loadingProgress?.expectedTotalBytes;
final bytesLoaded = loadingProgress?.cumulativeBytesLoaded;
if (totalBytes != null && bytesLoaded != null) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [CircularProgressIndicator()],
);
} else {
return child;
}
},
),
);
}
}
List Equality Ignoring Ordering in Dart
@immutable
class Person {
final String name;
const Person(this.name);
@override
bool operator ==(covariant Person other) => other.name == name;
@override
int get hashCode => name.hashCode;
@override
String toString() => name;
}
const people1 = [Person('Foo'), Person('Bar'), Person('Baz')];
const people2 = [Person('Foo'), Person('Bar'), Person('Baz')];
const people3 = [Person('Bar'), Person('Bar'), Person('Baz')];
const people4 = [Person('Bar'), Person('Baz')];
extension IsEqualToIgnoringOrdering<T> on List<T> {
bool isEqualToIgnoringOrdering(List<T> other) =>
length == other.length &&
{...this}.intersection({...other}).length == length;
}
void testIt() {
assert(people1.isEqualToIgnoringOrdering(people2));
assert(!people1.isEqualToIgnoringOrdering(people3));
assert(!people2.isEqualToIgnoringOrdering(people3));
assert(!people3.isEqualToIgnoringOrdering(people4));
}
Shorten GitHub URLs in Dart
// Want to support my work 🤝? https://buymeacoffee.com/vandad
import 'dart:developer' as devtools show log;
import 'dart:convert' show utf8;
Future<Uri> shortenGitHubUrl(String longUrl) =>
HttpClient().postUrl(Uri.parse('https://git.io/')).then((req) {
req.add(utf8.encode('url=$longUrl'));
return req.close();
}).then(
(resp) async {
try {
final location = resp.headers[HttpHeaders.locationHeader]?.first;
if (location != null) {
return Uri.parse(location);
} else {
throw 'No location was specified';
}
} catch (e) {
return Uri.parse(longUrl);
}
},
);
void testIt() async {
final uri = await shortenGitHubUrl(
'https://github.com/vandadnp/flutter-tips-and-tricks');
devtools.log(uri.toString());
// logs https://git.io/JS5Fm
}
Time Picker in Flutter
class HomePage extends StatelessWidget {
final timeOfDay = ValueNotifier<TimeOfDay?>(null);
HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: timeOfDay,
builder: (context, value, child) {
final title = timeOfDay.value?.toString() ?? 'Time Picker in Flutter';
return Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(
child: TextButton(
onPressed: () async {
timeOfDay.value = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
initialEntryMode: TimePickerEntryMode.input,
);
},
child: const Text('Please Pick a time'),
),
),
);
},
);
}
}
Throttled Print in Flutter
Stream<String> getStream() => Stream.periodic(
const Duration(milliseconds: 100),
(e) => DateTime.now().toString(),
);
void testIt() async {
await for (final now in getStream()) {
debugPrintThrottled(now);
}
}
Map Equality in Dart
typedef Name = String;
typedef Age = int;
const Map<Name, Age> people1 = {
'foo': 20,
'bar': 30,
'baz': 40,
};
const Map<Name, Age> people2 = {
'baz': 40,
'foo': 20,
'bar': 30,
};
void testIt() {
assert(mapEquals(people1, people2));
}
Unique Maps in Dart
import 'dart:developer' as devtools show log;
typedef Name = String;
typedef Age = int;
const Map<Name, Age> people = {
'foo': 20,
'bar': 30,
'baz': 20,
};
extension Unique<K, V> on Map<K, V> {
Map<K, V> unique() {
Map<K, V> result = {};
for (final value in {...values}) {
final firstKey = keys.firstWhereOrNull((key) => this[key] == value);
if (firstKey != null) {
result[firstKey] = value;
}
}
return result;
}
}
void testIt() {
final uniques = people.unique();
devtools.log(uniques.toString());
// prints: {foo: 20, bar: 30}
}
Raw Auto Complete in Flutter
const emailProviders = [
'gmail.com',
'hotmail.com',
'yahoo.com',
];
const icons = [
'https://bit.ly/3HsvvvB',
'https://bit.ly/3n6GW4L',
'https://bit.ly/3zf2RLy',
];
class EmailTextField extends StatefulWidget {
const EmailTextField({Key? key}) : super(key: key);
@override
State<EmailTextField> createState() => _EmailTextFieldState();
}
class _EmailTextFieldState extends State<EmailTextField> {
late final TextEditingController _controller;
late final FocusNode _focus;
@override
Widget build(BuildContext context) {
return RawAutocomplete<String>(
textEditingController: _controller,
focusNode: _focus,
fieldViewBuilder: (_, controller, focusNode, onSubmitted) {
return TextFormField(
controller: controller,
focusNode: focusNode,
onFieldSubmitted: (value) {
onSubmitted();
},
);
},
optionsBuilder: (textEditingValue) {
final lastChar = textEditingValue.text.characters.last;
if (lastChar == '@') {
return emailProviders;
} else {
return [];
}
},
optionsViewBuilder: (context, onSelected, options) {
return OptionsList(
onSelected: onSelected,
options: options,
controller: _controller,
);
},
);
}
@override
void initState() {
_controller = TextEditingController();
_focus = FocusNode();
super.initState();
}
@override
void dispose() {
_focus.dispose();
_controller.dispose();
super.dispose();
}
}
class OptionsList extends StatelessWidget {
final Iterable<String> options;
final AutocompleteOnSelected<String> onSelected;
final TextEditingController controller;
const OptionsList({
Key? key,
required this.onSelected,
required this.options,
required this.controller,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.topLeft,
child: Material(
child: SizedBox(
height: 150,
child: ListView.builder(
padding: const EdgeInsets.all(0.0),
itemCount: options.length,
itemBuilder: (context, index) {
final option = options.elementAt(index);
return GestureDetector(
onTap: () => onSelected(controller.text + option),
child: ListTile(
horizontalTitleGap: 2.0,
leading: Image.network(
icons[index],
width: 24,
height: 24,
),
title: Text(option),
),
);
},
),
),
),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Raw Auto Complete in Flutter'),
),
body: const Padding(
padding: EdgeInsets.all(16.0),
child: EmailTextField(),
),
);
}
}
Title on Object
in Dart
import 'dart:developer' as devtools show log;
extension CapTitle on Object {
String get capitalizedTitle {
String str;
if (this is Enum) {
str = (this as Enum).name;
} else {
str = toString();
}
return str[0].toUpperCase() + str.substring(1);
}
}
enum EmailProviders { gmail, yahoo, hotmail }
void testIt() {
EmailProviders.values.map((p) => p.capitalizedTitle).forEach(devtools.log);
// prints these:
// Gmail
// Yahoo
// Hotmail
}
Compute in Flutter
import 'dart:developer' as devtools show log;
import 'dart:convert' show utf8, json;
@immutable
class Person {
final String name;
final int age;
const Person(this.name, this.age);
Person.fromJson(Map<String, dynamic> json)
: name = json["name"] as String,
age = json["age"] as int;
}
Future<Iterable<Person>> downloadAndParsePersons(Uri uri) => HttpClient()
.getUrl(uri)
.then((req) => req.close())
.then((response) => response.transform(utf8.decoder).join())
.then((jsonString) => json.decode(jsonString) as List<dynamic>)
.then((json) => json.map((map) => Person.fromJson(map)));
void testIt() async {
final persons = await compute(
downloadAndParsePersons,
Uri.parse('https://bit.ly/3Jjcw8R'),
);
devtools.log(persons.toString());
}
Filter on Map
in Dart
import 'dart:developer' as devtools show log;
typedef Name = String;
typedef Age = int;
extension Filter<K, V> on Map<K, V> {
Iterable<MapEntry<K, V>> filter(
bool Function(MapEntry<K, V> entry) f,
) sync* {
for (final entry in entries) {
if (f(entry)) {
yield entry;
}
}
}
}
const Map<Name, Age> people = {
'foo': 20,
'bar': 31,
'baz': 25,
'qux': 32,
};
void testIt() async {
final peopleOver30 = people.filter((e) => e.value > 30);
devtools.log(peopleOver30.toString());
// ☝🏻 prints (MapEntry(bar: 31), MapEntry(qux: 32))
}
Type Alias in Dart
const Map<String, int> people1 = {
'foo': 20,
'bar': 30,
'baz': 25,
};
typedef Age = int;
const Map<String, Age> people2 = {
'foo': 20,
'bar': 30,
'baz': 25,
};
ValueNotifier
in Flutter
class DynamicToolTipTextField extends StatelessWidget {
final TextInputType? keyboardType;
final ValueNotifier<String?> hint;
final TextEditingController controller;
const DynamicToolTipTextField({
Key? key,
required this.hint,
required this.controller,
this.keyboardType,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: hint,
builder: (context, value, child) {
return TextField(
keyboardType: keyboardType,
controller: controller,
decoration: InputDecoration(
hintText: value as String?,
),
);
},
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
@immutable
abstract class HasText {
String get text;
}
enum Hint { pleaseEnterYourEmail, youForgotToEnterYourEmail }
extension GetText on Hint {
String get text {
switch (this) {
case Hint.pleaseEnterYourEmail:
return 'Please enter your email';
case Hint.youForgotToEnterYourEmail:
return 'You forgot to enter your email';
}
}
}
class _HomePageState extends State<HomePage> {
late final ValueNotifier<String?> _hint;
late final TextEditingController _controller;
@override
void initState() {
_hint = ValueNotifier<String?>(Hint.pleaseEnterYourEmail.text);
_controller = TextEditingController();
super.initState();
}
@override
void dispose() {
_hint.dispose();
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('ValueNotifier in Flutter'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
DynamicToolTipTextField(
hint: _hint,
controller: _controller,
keyboardType: TextInputType.emailAddress,
),
TextButton(
onPressed: () async {
final email = _controller.text;
if (email.trim().isEmpty) {
_hint.value = Hint.youForgotToEnterYourEmail.text;
await Future.delayed(const Duration(seconds: 2));
_hint.value = Hint.pleaseEnterYourEmail.text;
}
},
child: const Text('Log in'),
)
],
),
),
);
}
}
Object to Integer in Dart
enum ToIntStrategy { round, floor, ceil }
typedef ToIntOnErrorHandler = int Function(Object e);
extension ToInt on Object {
int toInteger({
ToIntStrategy strategy = ToIntStrategy.round,
ToIntOnErrorHandler? onError,
}) {
try {
final doubleValue = double.parse(toString());
switch (strategy) {
case ToIntStrategy.round:
return doubleValue.round();
case ToIntStrategy.floor:
return doubleValue.floor();
case ToIntStrategy.ceil:
return doubleValue.ceil();
}
} catch (e) {
if (onError != null) {
return onError(e);
} else {
return -1;
}
}
}
}
void testIt() {
assert('xyz'.toInteger(onError: (_) => 100) == 100);
assert(1.5.toInteger() == 2);
assert(1.6.toInteger() == 2);
assert('1.2'.toInteger(strategy: ToIntStrategy.floor) == 1);
assert('1.2'.toInteger(strategy: ToIntStrategy.ceil) == 2);
assert('1.5'.toInteger(strategy: ToIntStrategy.round) == 2);
}
Image Opacity in Flutter
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _opacity;
@override
void initState() {
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
);
_opacity = Tween(begin: 0.0, end: 1.0).animate(_controller);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Image.network(
'https://bit.ly/3ywI8l6',
opacity: _opacity,
),
Slider(
value: _controller.value,
onChanged: (value) {
setState(() => _controller.value = value);
},
),
],
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
Covariant in Dart
// Want to support my work 🤝? https://buymeacoffee.com/vandad
class Person {
final String name;
const Person(this.name);
@override
bool operator ==(Object other) {
if (other is! Person) throw ArgumentError('Was expecting a person');
return other.name == name;
}
@override
int get hashCode => name.hashCode;
}
class Person {
final String name;
const Person(this.name);
@override
bool operator ==(covariant Person other) => other.name == name;
@override
int get hashCode => name.hashCode;
}
Custom Errors in Streams in Dart
class Either<V, E extends Exception> {
final V? value;
final E? error;
const Either({this.value, this.error}) : assert((value ?? error) != null);
bool get isError => error != null;
bool get isValue => value != null;
@override
String toString() {
if (value != null) {
return "Value: $value";
} else if (error != null) {
return "Error: $error";
} else {
return 'Unknown state';
}
}
}
class DateTimeException implements Exception {
final String reason;
const DateTimeException({required this.reason});
}
Stream<Either<DateTime, DateTimeException>> getDateTime() async* {
var index = 0;
while (true) {
if (index % 2 == 0) {
yield Either(value: DateTime.now());
} else {
yield const Either(
error: DateTimeException(reason: 'Something is wrong!'),
);
}
index += 1;
}
}
void testIt() async {
await for (final value in getDateTime()) {
dev.log(value.toString());
}
}
Shake Animation in Flutter
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
const animationWidth = 10.0;
class _HomePageState extends State<HomePage>
with SingleTickerProviderStateMixin {
late final TextEditingController _textController;
late final AnimationController _animationController;
late final Animation<double> _offsetAnim;
final defaultHintText = 'Please enter your email here 😊';
var _hintText = '';
@override
void initState() {
_hintText = defaultHintText;
_textController = TextEditingController();
_animationController = AnimationController(
duration: const Duration(milliseconds: 370),
vsync: this,
);
_offsetAnim = Tween(
begin: 0.0,
end: animationWidth,
).chain(CurveTween(curve: Curves.elasticIn)).animate(
_animationController,
)..addStatusListener(
(status) {
if (status == AnimationStatus.completed) {
_animationController.reverse();
}
},
);
super.initState();
}
@override
void dispose() {
_textController.dispose();
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Shake Animation in Flutter'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
AnimatedBuilder(
animation: _offsetAnim,
builder: (context, child) {
return Container(
margin: const EdgeInsets.symmetric(
horizontal: animationWidth,
),
padding: EdgeInsets.only(
left: _offsetAnim.value + animationWidth,
right: animationWidth - _offsetAnim.value,
),
child: TextField(
controller: _textController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
hintText: _hintText,
),
),
);
},
),
TextButton(
onPressed: () async {
if (_textController.text.isEmpty) {
setState(() {
_hintText = 'You forgot to enter your email 🥲';
_animationController.forward(from: 0.0);
});
await Future.delayed(const Duration(seconds: 3));
setState(() {
_hintText = defaultHintText;
});
}
},
child: const Text('Login'))
],
),
),
);
}
}
Throw Enums in Dart
import 'dart:developer' as dev show log;
enum Exceptions { invalidUserName, invalidPassword }
void thisMethodThrows() {
throw Exceptions.invalidPassword;
}
void testIt() {
try {
thisMethodThrows();
} on Exceptions catch (e) {
switch (e) {
case (Exceptions.invalidUserName):
dev.log("Invalid user name");
break;
case (Exceptions.invalidPassword):
dev.log("Invalid password");
break;
}
}
}
Future
Error Test in Flutter
import 'dart:developer' as dev show log;
@immutable
abstract class UserException implements Exception {}
class InvalidUserNameException extends UserException {}
class InvalidUserAgeException extends UserException {}
@immutable
class User {
final String name;
final int age;
User({required this.name, required this.age}) {
if (!name.contains(RegExp(r'^[a-z ]+$'))) {
throw InvalidUserNameException();
} else if (age < 0 || age > 130) {
throw InvalidUserAgeException();
}
}
const User.anonymous()
: name = 'Anonymous User',
age = 0;
}
Future<User> getAsyncUser() => Future.delayed(
const Duration(seconds: 1),
() => User(name: 'Foo', age: 20),
);
void testIt() async {
final user = await getAsyncUser()
.catchError(
handleInvalidUsernameException,
test: (e) => e is InvalidUserNameException,
)
.catchError(
handleInvalidAgeException,
test: (e) => e is InvalidUserAgeException,
);
dev.log(user.toString());
}
User handleInvalidUsernameException(Object? e) {
dev.log(e.toString());
return const User.anonymous();
}
User handleInvalidAgeException(Object? e) {
dev.log(e.toString());
return const User.anonymous();
}
Generic URL Retrieval in Dart
import 'dart:developer' as dev show log;
typedef StatusCodeResultBuilder<T> = Future<T> Function(
int statusCode,
HttpClientResponse response,
);
extension Get on Uri {
Future<T?> getBody<T>({
StatusCodeResultBuilder<T>? statusBuilder,
T Function(Object error)? onNetworkError,
}) async {
try {
final apiCall = await HttpClient().getUrl(this);
final response = await apiCall.close();
final builder = statusBuilder;
if (builder == null) {
final data = await response.transform(convert.utf8.decoder).join();
if (data is T) {
return data as T?;
} else {
return null;
}
} else {
final result = await builder(response.statusCode, response);
return result;
}
} catch (e) {
if (onNetworkError != null) {
return onNetworkError(e);
} else {
return null;
}
}
}
}
extension ToUri on String {
Uri toUri() => Uri.parse(this);
}
const url = 'https://bit.ly/3EKWcLa';
void testIt() async {
final json = await url.toUri().getBody<String>(
statusBuilder: (statusCode, response) async {
if (statusCode == 200) {
return await response.transform(convert.utf8.decoder).join();
} else {
return "{'error': 'Unexpected status code $statusCode'}";
}
},
onNetworkError: (error) {
return "{'error': 'Got network error'}";
},
);
if (json != null) {
dev.log(json);
}
}
Custom Error Widget in Flutter
class MyErrorWidget extends StatelessWidget {
final String text;
const MyErrorWidget({Key? key, required this.text}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: SizedBox(
width: MediaQuery.of(context).size.width,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Image.network('https://bit.ly/3gHlTCU'),
Text(
text,
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.red,
),
),
],
),
),
),
);
}
}
void main() {
ErrorWidget.builder = (FlutterErrorDetails details) {
bool isInDebugMode = false;
assert(() {
isInDebugMode = true;
return true;
}());
final message = details.exception.toString();
if (isInDebugMode) {
return MyErrorWidget(text: message);
} else {
return Text(
message,
textAlign: TextAlign.center,
);
}
};
runApp(
const MaterialApp(
home: HomePage(),
debugShowCheckedModeBanner: false,
),
);
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Error Widget in Flutter'),
),
body: Builder(
builder: (context) {
throw Exception(
'Here is an exception that is caught by our custom Error Widget in Flutter');
},
),
);
}
}
Handle Multiple Future
Errors in Dart
import 'dart:developer' as dev show log;
Future<Iterable<T>> waitOn<T>(
Iterable<Future<T>> futures,
Function onError,
) async {
List<T> result = [];
for (final future in futures) {
final value = await future.catchError(onError);
result.add(value);
}
return result;
}
void testIt() async {
final f1 = Future.error('First Error');
final f2 = Future.delayed(const Duration(seconds: 2), () => 10);
final f3 = Future.error('Second error');
final f4 = Future.delayed(const Duration(seconds: 2), () => 'Hello world');
final result = await waitOn([f1, f2, f3, f4], (error) => -1);
dev.log(result.toString()); // [-1, 10, -1, Hello world]
}
Future
Error Handling in Dart
import 'dart:developer' as dev show log;
extension OnError<T> on Future<T> {
Future<T> onErrorJustReturn(T value) => catchError((_) => value);
}
Future<bool> isUserRegistered({required String email}) => HttpClient()
.postUrl(Uri.parse('https://website'))
.then((req) {
req.headers.add('email', email);
return req.close();
})
.then((resp) => resp.statusCode == 200)
.onErrorJustReturn(false);
void testIt() async {
final isFooRegistered = await isUserRegistered(email: 'foo@flutter.com');
dev.log(isFooRegistered.toString());
}
String to Toast in Flutter
extension Toast on String {
Future<void> showAsToast(BuildContext context,
{required Duration duration}) async {
final scaffold = ScaffoldMessenger.of(context);
final controller = scaffold.showSnackBar(
SnackBar(
content: Text(this),
backgroundColor: const Color(0xFF24283b),
behavior: SnackBarBehavior.floating,
elevation: 2.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
await Future.delayed(duration);
controller.close();
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextButton(
onPressed: () => 'Hello, World!'.showAsToast(
context,
duration: const Duration(seconds: 2),
),
child: const Text('Show the snackbar'),
),
),
);
}
}
Waiting in Dart
Future<void> wait(Duration d) async {
await Future.delayed(d);
}
extension Wait on int {
Future<void> get seconds => wait(Duration(seconds: this));
Future<void> get minutes => wait(Duration(minutes: this));
}
void testIt() async {
await 2.seconds;
'After 2 seconds'.log();
await 3.minutes;
'After 3 minutes'.log();
}
extension Log on Object {
void log() {
dev.log(toString());
}
}
Loading Dialog in Flutter
typedef CloseDialog = void Function();
CloseDialog showLoadingScreen({
required BuildContext context,
required String text,
}) {
final dialog = AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 10),
Text(text),
],
),
);
showDialog(
context: context,
barrierDismissible: false,
builder: (_) => dialog,
);
return () => Navigator.of(context).pop();
}
void testIt(BuildContext context) async {
final closeDialog = showLoadingScreen(
context: context,
text: 'Loading data...',
);
await Future.delayed(const Duration(seconds: 2));
closeDialog();
}
Compact Map on Map<K,V>
in Dart
const foo = 'foo';
const bar = 'bar';
const baz = 'baz';
const namesAndAges = {
foo: 20,
bar: 25,
baz: 18,
};
const acceptedNames = [
foo,
bar,
];
void testIt() {
final acceptedAges = namesAndAges.compactMap(
(e) => acceptedNames.contains(e.key) ? e.value : null,
);
acceptedAges.log(); // [20, 25]
}
extension CompactMap<T, E> on Map<T, E> {
Iterable<V> compactMap<V>(V? Function(MapEntry<T, E>) f) sync* {
for (final entry in entries) {
final extracted = f(entry);
if (extracted != null) {
yield extracted;
}
}
}
}
Query Parameters in Dart
import 'dart:developer' as devtools show log;
const host = 'freecurrencyapi.net';
const path = '/api/v2/latest';
const apiKey = 'YOUR_API_KEY';
const baseCurrency = 'sek';
const params = {
'apiKey': apiKey,
'base_currency': 'sek',
};
void insteadOfThis() {
const url = 'https://$host$path?apiKey=$apiKey&base_currency=$baseCurrency';
url.log();
}
void doThis() {
final url = Uri.https(host, path, params);
url.log();
}
extension Log on Object {
void log() {
devtools.log(toString());
}
}
Multiple Gradients in Container in Flutter
typedef GradientContainersBuilder = Map<LinearGradient, Widget?> Function();
class GradientContainers extends StatelessWidget {
final GradientContainersBuilder builder;
const GradientContainers({
Key? key,
required this.builder,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Stack(
children: builder().entries.map((mapEntry) {
final gradient = mapEntry.key;
final widget = mapEntry.value;
return GradientContainer(
gradient: gradient,
child: widget,
);
}).toList(),
);
}
}
class GradientContainer extends StatelessWidget {
final LinearGradient gradient;
final Widget? child;
const GradientContainer({Key? key, required this.gradient, this.child})
: super(key: key);
@override
Widget build(BuildContext context) {
return Positioned.fill(
child: Container(
decoration: BoxDecoration(
gradient: gradient,
),
child: child,
),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: GradientContainers(
builder: () => {
topLeftToBottomRightGradient: null,
rightToLeftGradient: null,
leftToRightGradinet: null,
bottomRightGradient: Image.network('https://bit.ly/3otHHog'),
},
),
);
}
}
const transparent = Color(0x00FFFFFF);
const topLeftToBottomRightGradient = LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xff2ac3de),
transparent,
],
);
const bottomRightGradient = LinearGradient(
begin: Alignment.bottomRight,
end: Alignment.topLeft,
colors: [
Color(0xffbb9af7),
transparent,
],
);
const rightToLeftGradient = LinearGradient(
begin: Alignment.centerRight,
end: Alignment.centerLeft,
colors: [
Color(0xff9ece6a),
transparent,
],
);
const leftToRightGradinet = LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [
Color(0xff7dcfff),
transparent,
],
);
void main() {
runApp(
const MaterialApp(
home: HomePage(),
debugShowCheckedModeBanner: false,
),
);
}
Filter on Stream<List<T>>
in Dart
import 'dart:developer' as devtools show log;
extension Filter<T> on Stream<List<T>> {
Stream<List<T>> filter(bool Function(T) where) =>
map((items) => items.where(where).toList());
}
final Stream<List<int>> allNumbers = Stream.periodic(
const Duration(seconds: 1),
(value) => [for (var i = 0; i < value; i++) i],
);
bool isEven(num value) => value % 2 == 0;
bool isOdd(num value) => value % 2 != 0;
extension EvenOdd<E extends num> on Stream<List<E>> {
Stream<List<E>> get evenNumbers => filter(isEven);
Stream<List<E>> get oddNumbers => filter(isOdd);
}
void readEvenNumbers() async {
await for (final evenNumber in allNumbers.evenNumbers) {
devtools.log('All even numbers: $evenNumber');
}
}
void readOddNumbers() async {
await for (final oddNumber in allNumbers.oddNumbers) {
devtools.log('All odd numbers: $oddNumber');
}
}
Generic Route Arguments in Flutter
extension GetArgument on BuildContext {
T? getArgument<T>() {
final modalRoute = ModalRoute.of(this);
if (modalRoute != null) {
final args = modalRoute.settings.arguments;
if (args != null && args is T) {
return args as T;
}
}
return null;
}
}
Generic Dialog in Flutter
typedef DialogOptionBuilder<T> = Map<String, T> Function();
Future<T?> showGenericDialog<T>({
required BuildContext context,
required String title,
required String content,
required DialogOptionBuilder optionsBuilder,
}) {
final options = optionsBuilder();
return showDialog<T>(
context: context,
builder: (context) {
return AlertDialog(
title: Text(title),
content: Text(content),
actions: options.keys.map(
(optionTitle) {
final T value = options[optionTitle];
return TextButton(
onPressed: () {
Navigator.of(context).pop(value);
},
child: Text(optionTitle),
);
},
).toList(),
);
},
);
}
Future<bool> showLogOutDialog(BuildContext context) {
return showGenericDialog<bool>(
context: context,
title: 'Log out',
content: 'Are you sure you want to log out?',
optionsBuilder: () => {
'Cancel': false,
'Log out': true,
},
).then(
(value) => value ?? false,
);
}
GitHub API in Flutter
import 'dart:io' show HttpHeaders, HttpClient;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:convert' show utf8, json;
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
Future<Iterable<GithubUser>> getGithubFollowers(String accessToken) =>
HttpClient()
.getUrl(Uri.parse('https://api.github.com/user/followers'))
.then((req) {
req.headers
..set(HttpHeaders.authorizationHeader, 'Bearer $accessToken')
..set(HttpHeaders.contentTypeHeader, 'application/json');
return req.close();
})
.then((resp) => resp.transform(utf8.decoder).join())
.then((jsonStr) => json.decode(jsonStr) as List<dynamic>)
.then(
(jsonArray) => jsonArray.compactMap((element) {
if (element is Map<String, dynamic>) {
return element;
} else {
return null;
}
}),
)
.then(
(listOfMaps) => listOfMaps.map(
(map) => GithubUser.fromJson(map),
),
);
class GithubUser {
final String username;
final String avatarUrl;
GithubUser.fromJson(Map<String, dynamic> json)
: username = json['login'] as String,
avatarUrl = json['avatar_url'] as String;
}
extension CompactMap<T> on List<T> {
List<E> compactMap<E>(E? Function(T element) f) {
Iterable<E> imp(E? Function(T element) f) sync* {
for (final value in this) {
final mapped = f(value);
if (mapped != null) {
yield mapped;
}
}
}
return imp(f).toList();
}
}
const token = 'PUT_YOUR_TOKEN_HERE';
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('GitHub API in Flutter'),
),
body: FutureBuilder(
future: getGithubFollowers(token),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
final users = (snapshot.data as Iterable<GithubUser>).toList();
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
final user = users[index];
return ListTile(
title: Text(user.username),
leading: CircularAvatar(url: user.avatarUrl),
);
},
);
default:
return const CircularProgressIndicator();
}
},
),
);
}
}
void main() {
runApp(
const MaterialApp(
home: HomePage(),
debugShowCheckedModeBanner: false,
),
);
}
ChangeNotifier
in Flutter
import 'package:provider/provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
const allImages = [
'https://bit.ly/3ywI8l6',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3qYOtDm',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3yvFg7X',
'https://bit.ly/3ywzOla',
'https://bit.ly/3wnASpW',
'https://bit.ly/3jXSDto',
];
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class ImageData {
final Uint8List imageData;
const ImageData(this.imageData);
}
class Images extends ChangeNotifier {
final List<ImageData> _items = [];
var _isLoading = false;
bool get isLoading => _isLoading;
UnmodifiableListView<ImageData> get items => UnmodifiableListView(_items);
void loadNextImage() async {
if (_items.length < allImages.length) {
// time to load more
_isLoading = true;
notifyListeners();
final imageUrl = allImages[_items.length];
final networkAsset = NetworkAssetBundle(Uri.parse(imageUrl));
final loaded = await networkAsset.load(imageUrl);
final bytes = loaded.buffer.asUint8List();
final imageData = ImageData(bytes);
_items.insert(0, imageData);
_isLoading = false;
notifyListeners();
} else {
if (isLoading) {
_isLoading = false;
notifyListeners();
}
}
}
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('ChangeNotifier in Flutter'),
actions: [
Consumer<Images>(
builder: (context, value, child) {
return IconButton(
onPressed: () {
value.loadNextImage();
},
icon: const Icon(Icons.add_box_outlined),
);
},
)
],
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Consumer<Images>(
builder: (context, value, child) {
final images = value.items;
final isLoading = value.isLoading;
return ListView.builder(
itemBuilder: (context, index) {
if (index == 0 && isLoading) {
return Center(
child: Column(
children: const [
CircularProgressIndicator(),
SizedBox(height: 16.0),
],
),
);
} else {
final imageIndex = isLoading ? index - 1 : index;
final imageData = images[imageIndex].imageData;
return Column(
children: [
RoundedImageWithShadow(imageData: imageData),
const SizedBox(height: 16.0),
],
);
}
},
itemCount: isLoading ? images.length + 1 : images.length,
);
},
),
),
);
}
}
class RoundedImageWithShadow extends StatelessWidget {
final Uint8List imageData;
const RoundedImageWithShadow({Key? key, required this.imageData})
: super(key: key);
@override
Widget build(BuildContext context) {
return Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
blurRadius: 2,
color: Colors.black.withAlpha(40),
spreadRadius: 2,
),
],
),
child: Image.memory(
imageData,
fit: BoxFit.cover,
),
);
}
}
void main() {
runApp(
MaterialApp(
home: ChangeNotifierProvider(
create: (_) => Images(),
child: const HomePage(),
),
debugShowCheckedModeBanner: false,
),
);
}
Refresh Indicator in Flutter
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
const allImages = [
'https://bit.ly/3x7J5Qt',
'https://bit.ly/3ywI8l6',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3qYOtDm',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3yvFg7X',
'https://bit.ly/3ywzOla',
'https://bit.ly/3wnASpW',
'https://bit.ly/3jXSDto',
];
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final _images = [allImages.first];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Refresh Indicator in Flutter'),
),
body: RefreshIndicator(
onRefresh: () async {
final nextIndex = _images.length + 1;
if (nextIndex < allImages.length) {
setState(() {
_images.insert(0, allImages[nextIndex]);
});
}
},
child: ListView.builder(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.all(16),
itemCount: _images.length,
itemBuilder: (context, index) {
final imageUrl = _images[index];
return Column(
children: [
RoundedImageWithShadow(url: imageUrl),
const SizedBox(height: 16),
],
);
},
),
),
);
}
}
class RoundedImageWithShadow extends StatelessWidget {
final String url;
const RoundedImageWithShadow({Key? key, required this.url}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
blurRadius: 2,
color: Colors.black.withAlpha(40),
spreadRadius: 2,
),
],
),
child: Image.network(url),
);
}
}
FlatMap in Dart
extension FlatMap<T> on T? {
E? flatMap<E>(E? Function(T) f) => this != null ? f(this!) : null;
}
AuthUser? get insteadOfThis {
final user = FirebaseAuth.instance.currentUser;
if (user != null) {
return AuthUser.fromFirebase(user);
} else {
return null;
}
}
AuthUser? get doThis =>
FirebaseAuth.instance.currentUser.flatMap((u) => AuthUser.fromFirebase(u));
OrientationBuilder
in Flutter
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class RoundedImageWithShadow extends StatelessWidget {
final String url;
const RoundedImageWithShadow({Key? key, required this.url}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
blurRadius: 2,
color: Colors.black.withAlpha(40),
spreadRadius: 2,
),
],
),
child: Image.network(url),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: OrientationBuilder(
builder: (context, orientation) {
final int count;
switch (orientation) {
case Orientation.portrait:
count = 2;
break;
case Orientation.landscape:
count = 4;
break;
}
return GridView.count(
padding: const EdgeInsets.all(8.0),
crossAxisCount: count,
mainAxisSpacing: 8.0,
crossAxisSpacing: 8.0,
children: images
.map((url) => RoundedImageWithShadow(url: url))
.toList(),
);
},
),
),
);
}
}
final images = [
'https://bit.ly/3qJ2FCf',
'https://bit.ly/3Hs9JsV',
'https://bit.ly/3cfT6Cv',
'https://bit.ly/30wGnIE',
'https://bit.ly/3kJYsum',
'https://bit.ly/3oDoMaJ',
'https://bit.ly/3FndXQM',
'https://bit.ly/3ci4i1f',
];
Linear Gradient in Flutter
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Linear Gradient in Flutter'),
),
body: const ImageWithShadow(url: 'https://bit.ly/3otHHog'),
);
}
}
class ImageWithShadow extends StatelessWidget {
final String url;
const ImageWithShadow({
Key? key,
required this.url,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: Stack(
children: [
Positioned.fill(
child: Container(
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
blurRadius: 10.0,
color: Colors.black.withOpacity(0.5),
offset: const Offset(0.0, 3.0),
)
],
borderRadius: const BorderRadius.all(Radius.circular(20)),
gradient: const LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color.fromARGB(255, 176, 229, 251),
Color.fromARGB(255, 235, 202, 250)
],
),
),
),
),
Image.network(url),
],
),
);
}
}
Bloc Text Editing Controller in Flutter
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
abstract class Event {
const Event();
}
class SearchEvent extends Event {
final String searchString;
const SearchEvent(this.searchString);
}
class ClearSearch extends Event {}
class SearchBloc extends Bloc<Event, List<String>> {
static const names = ['foo', 'bar', 'baz'];
SearchBloc() : super(names) {
on<Event>((event, emit) {
if (event is SearchEvent) {
emit(names
.where((element) => element.contains(event.searchString))
.toList());
} else if (event is ClearSearch) {
emit(names);
}
});
}
}
class BlocTextEditingController extends TextEditingController {
SearchBloc? bloc;
BlocTextEditingController() {
addListener(() {
if (text.isEmpty) {
bloc?.add(ClearSearch());
} else {
bloc?.add(SearchEvent(text));
}
});
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
const largeStyle = TextStyle(fontSize: 30);
class _HomePageState extends State<HomePage> {
late final BlocTextEditingController _controller;
@override
void initState() {
_controller = BlocTextEditingController();
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
_controller.bloc = BlocProvider.of<SearchBloc>(context);
return Scaffold(
appBar: AppBar(
title: Text('Bloc Search in Flutter'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: BlocBuilder<SearchBloc, List<String>>(
builder: (context, state) {
return ListView.builder(
itemBuilder: (context, index) {
if (index == 0) {
// search field
return TextField(
decoration: InputDecoration(
hintText: 'Enter search term here...',
hintStyle: largeStyle,
),
style: largeStyle,
controller: _controller,
);
} else {
final name = state[index - 1];
return ListTile(
title: Text(
name,
style: largeStyle,
),
);
}
},
itemCount: state.length + 1, // +1 for search
);
},
),
),
);
}
}
Blurred TabBar in Flutter
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
const images = [
'https://bit.ly/3x7J5Qt',
'https://bit.ly/3ywI8l6',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3qYOtDm',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3yvFg7X',
'https://bit.ly/3ywzOla',
'https://bit.ly/3wnASpW',
'https://bit.ly/3jXSDto',
];
class CustomTabBar extends StatelessWidget {
final List<IconButton> buttons;
const CustomTabBar({Key? key, required this.buttons}) : super(key: key);
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.bottomCenter,
child: ClipRect(
child: Container(
height: 80,
color: Colors.white.withOpacity(0.4),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 4.0, sigmaY: 4.0),
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.5),
),
child: Padding(
padding: const EdgeInsets.only(bottom: 15),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: buttons,
),
),
),
),
),
),
);
}
}
const summerIcon = Icon(
Icons.surfing,
size: 40.0,
color: Colors.teal,
);
const autumnIcon = Icon(
Icons.nature_outlined,
size: 40.0,
color: Colors.black45,
);
const winterIcon = Icon(
Icons.snowboarding,
size: 40.0,
color: Colors.black45,
);
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Blurred Tab Bar'),
),
body: Stack(
children: [
ListView.builder(
itemCount: images.length,
itemBuilder: (context, index) {
final url = images[index];
return Image.network(url);
},
),
CustomTabBar(
buttons: [
IconButton(
icon: summerIcon,
onPressed: () {
// implement me
},
),
IconButton(
icon: autumnIcon,
onPressed: () {
// implement me
},
),
IconButton(
icon: winterIcon,
onPressed: () {
// implement me
},
)
],
)
],
),
);
}
}
Play YouTube in Flutter
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
const videoIds = [
'BHACKCNDMW8',
'26h9hBZFl7w',
'glENND73k4Q',
'd0tU18Ybcvk',
];
class VideoView extends StatelessWidget {
final String videoId;
final _key = UniqueKey();
VideoView({required this.videoId});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Watch a Video'),
),
body: Center(
child: Container(
height: 232.0,
child: WebView(
key: _key,
initialUrl: 'https://www.youtube.com/embed/$videoId',
javascriptMode: JavascriptMode.unrestricted,
),
),
),
);
}
}
class YouTubeVideoThumbnail extends StatelessWidget {
final String videoId;
final String thumbnailUrl;
const YouTubeVideoThumbnail({Key? key, required this.videoId})
: thumbnailUrl = 'https://img.youtube.com/vi/$videoId/maxresdefault.jpg',
super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => VideoView(videoId: videoId),
),
);
},
child: Container(
height: 256.0,
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
blurRadius: 10.0,
color: Colors.black.withAlpha(50),
spreadRadius: 10.0,
),
],
borderRadius: BorderRadius.circular(20),
image: DecorationImage(
fit: BoxFit.fitHeight,
image: NetworkImage(thumbnailUrl),
),
),
child: Center(
child: Icon(
Icons.play_arrow,
color: Colors.white,
size: 100.0,
),
),
),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('YouTube Videos in Flutter')),
body: ListView.builder(
itemCount: videoIds.length,
itemBuilder: (context, index) {
final videoId = videoIds[index];
return Padding(
padding: const EdgeInsets.all(8.0),
child: YouTubeVideoThumbnail(videoId: videoId),
);
},
),
);
}
}
ListView Background in Flutter
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class ListItem {
const ListItem();
factory ListItem.emptyTile() => EmptyTile();
factory ListItem.tile(
String title,
String subTitle,
) =>
Tile(
title,
subTitle,
);
}
class Tile extends ListItem {
final String title;
final String subTitle;
const Tile(this.title, this.subTitle) : super();
}
class EmptyTile extends ListItem {}
final items = [
for (var i = 1; i <= 6; i++) ListItem.tile('Title $i', 'Sub title $i'),
ListItem.emptyTile(),
for (var i = 7; i <= 12; i++) ListItem.tile('Title $i', 'Sub title $i'),
];
class Background extends StatelessWidget {
final Widget child;
const Background({Key? key, required this.child}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
image: DecorationImage(
fit: BoxFit.fitHeight,
image: NetworkImage('https://bit.ly/3jXSDto'),
),
),
child: child,
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Background(
child: ListView.builder(
padding: EdgeInsets.zero,
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
if (item is Tile) {
return Container(
color: Colors.grey[200],
child: ListTile(
title: Text(item.title),
subtitle: Text(item.subTitle),
),
);
} else if (item is EmptyTile) {
return SizedBox(
height: 450,
);
} else {
throw 'unexpcted item';
}
},
),
),
);
}
}
Integer to Binary in Dart
extension ToBinary on int {
String toBinary(
int len, {
int separateAtLength = 4,
String separator = ',',
}) =>
toRadixString(2)
.padLeft(len, '0')
.splitByLength(separateAtLength)
.join(separator);
}
void testIt() {
assert(1.toBinary(8) == '0000,0001');
assert(2.toBinary(4) == '0010');
assert(3.toBinary(16) == '0000,0000,0000,0011');
assert(255.toBinary(8, separateAtLength: 8) == '11111111');
assert(255.toBinary(8, separateAtLength: 4) == '1111,1111');
}
extension SplitByLength on String {
Iterable<String> splitByLength(int len, {String filler = '0'}) sync* {
final missingFromLength =
length % len == 0 ? 0 : len - (characters.length % len);
final expectedLength = length + missingFromLength;
final src = padLeft(expectedLength, filler);
final chars = src.characters;
for (var i = 0; i < chars.length; i += len) {
yield chars.getRange(i, i + len).toString();
}
}
}
Split String by Length in Dart
void testIt() {
assert('dartlang'
.splitByLength(5, filler: '💙')
.isEqualTo(['💙💙dar', 'tlang']));
assert('0100010'.splitByLength(4).isEqualTo(['0010', '0010']));
assert('foobar'.splitByLength(3).isEqualTo(['foo', 'bar']));
assert('flutter'.splitByLength(4, filler: 'X').isEqualTo(['Xflu', 'tter']));
assert('dart'.splitByLength(5, filler: '').isEqualTo(['dart']));
}
extension SplitByLength on String {
Iterable<String> splitByLength(int len, {String filler = '0'}) sync* {
final missingFromLength =
length % len == 0 ? 0 : len - (characters.length % len);
final expectedLength = length + missingFromLength;
final src = padLeft(expectedLength, filler);
final chars = src.characters;
for (var i = 0; i < chars.length; i += len) {
yield chars.getRange(i, i + len).toString();
}
}
}
Image Tint in Flutter
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
enum OverlayColor { brown, orange, yellow, green, blue }
extension Color on OverlayColor {
MaterialColor get color {
switch (this) {
case OverlayColor.blue:
return Colors.blue;
case OverlayColor.brown:
return Colors.brown;
case OverlayColor.green:
return Colors.green;
case OverlayColor.orange:
return Colors.orange;
case OverlayColor.yellow:
return Colors.yellow;
}
}
}
extension Title on OverlayColor {
String get title => toString().split('.').last;
}
extension ToTextButtonWithValue on OverlayColor {
TextButtonWithValue<OverlayColor> toTextButtonWithValue(
OnTextButtonWithValuePressed onPressed) {
return TextButtonWithValue(
value: this,
onPressed: onPressed,
child: Text(title),
);
}
}
typedef OnTextButtonWithValuePressed<T> = void Function(T value);
class TextButtonWithValue<T> extends StatelessWidget {
final T value;
final OnTextButtonWithValuePressed onPressed;
final Widget child;
const TextButtonWithValue({
Key? key,
required this.value,
required this.onPressed,
required this.child,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () {
onPressed(value);
},
child: child,
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
OverlayColor? _overlayColor;
ColorFilter? getcolorFilter() {
final overlayColor = _overlayColor;
if (overlayColor == null) {
return null;
}
return ColorFilter.mode(
overlayColor.color,
BlendMode.colorBurn,
);
}
Iterable<Widget> overlayColorButtons() {
return OverlayColor.values.map((overlayColor) {
return Expanded(
flex: 1,
child: Container(
child: overlayColor.toTextButtonWithValue(
(value) {
setState(() {
_overlayColor = value;
});
},
),
),
);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Tinting Images in Flutter'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Container(
height: 250.0,
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
image: DecorationImage(
colorFilter: getcolorFilter(),
fit: BoxFit.fitHeight,
image: NetworkImage('https://bit.ly/3jOueGG'),
),
),
),
SizedBox(height: 16.0),
Row(
children: overlayColorButtons().toList(),
)
],
),
),
);
}
}
SlideTransition in Flutter
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
class _HomePageState extends State<HomePage>
with SingleTickerProviderStateMixin {
late final _controller = AnimationController(
duration: Duration(milliseconds: 500),
vsync: this,
);
late final _animation = Tween<Offset>(
begin: Offset(0.0, 0.0),
end: Offset(-0.83, 0.0),
).animate(
CurvedAnimation(
parent: _controller,
curve: Curves.easeInQuint,
),
);
var _isExpanded = false;
@override
void dispose() {
super.dispose();
_controller.dispose();
}
@override
Widget build(BuildContext context) {
_controller.forward();
return Scaffold(
body: SizedBox.expand(
child: Stack(
fit: StackFit.passthrough,
children: [
Image.network(
'https://bit.ly/3BWYDbz',
fit: BoxFit.fitHeight,
),
Positioned(
top: 200.0,
child: SlideTransition(
position: _animation,
child: GestureDetector(
onTap: () {
_isExpanded = !_isExpanded;
if (_isExpanded) {
_controller.reverse();
} else {
_controller.forward();
}
},
child: Box(),
),
),
),
],
),
),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class Box extends StatelessWidget {
const Box({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: Colors.blue[200]?.withAlpha(200),
border: Border.all(
color: Colors.blue,
style: BorderStyle.solid,
width: 1.0,
),
borderRadius: BorderRadius.only(
topRight: Radius.circular(10),
bottomRight: Radius.circular(10),
),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Text(
'By: Jesper Anhede',
style: TextStyle(
fontSize: 18.0,
),
),
SizedBox(width: 10.0),
Icon(
Icons.info,
color: Colors.pink[400],
),
],
),
),
);
}
}
Expansion Panels and Lists in Flutter
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class Event {
final String title;
final String details;
final String imageUrl;
bool isExpanded = false;
Event({
required this.title,
required this.details,
required this.imageUrl,
});
@override
bool operator ==(covariant Event other) => title == other.title;
}
const diwaliDetails =
'''Diwali, or Dipawali, is India's biggest and most important holiday of the year. The festival gets its name from the row (avali) of clay lamps (deepa) that Indians light outside their homes to symbolize the inner light that protects from spiritual darkness. This festival is as important to Hindus as the Christmas holiday is to Christians.''';
const halloweenDetails =
'''Halloween or Hallowe'en, less commonly known as Allhalloween, All Hallows' Eve, or All Saints' Eve, is a celebration observed in many countries on 31 October, the eve of the Western Christian feast of All Hallows' Day.''';
final events = [
Event(
title: 'Diwali',
details: diwaliDetails,
imageUrl: 'https://bit.ly/3mGg8YW',
),
Event(
title: 'Halloween',
details: halloweenDetails,
imageUrl: 'https://bit.ly/3wb1w7j',
),
];
extension ToPanel on Event {
ExpansionPanel toPanel() {
return ExpansionPanel(
headerBuilder: (context, isExpanded) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
title,
style: TextStyle(fontSize: 30.0),
),
);
},
isExpanded: isExpanded,
body: Container(
height: 250,
width: double.infinity,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.fitWidth,
colorFilter: ColorFilter.mode(
Colors.black.withOpacity(0.5),
BlendMode.luminosity,
),
image: NetworkImage(imageUrl),
),
),
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
details,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20, color: Colors.white, shadows: [
Shadow(
blurRadius: 1.0,
offset: Offset.zero,
color: Colors.black,
)
]),
),
),
),
),
);
}
}
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Expansion Panels in Flutter'),
),
body: SingleChildScrollView(
child: ExpansionPanelList(
children: events.map((e) => e.toPanel()).toList(),
expansionCallback: (panelIndex, isExpanded) {
setState(() {
events[panelIndex].isExpanded = !isExpanded;
});
},
),
),
);
}
}
Complete CRUD App in Flutter
//Want to support my work 🤝? https://buymeacoffee.com/vandad
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart'
show getApplicationDocumentsDirectory;
class Person implements Comparable {
final int id;
final String firstName;
final String lastName;
const Person(this.id, this.firstName, this.lastName);
String get fullName => '$firstName $lastName';
Person.fromData(Map<String, Object?> data)
: id = data['ID'] as int,
firstName = data['FIRST_NAME'] as String,
lastName = data['LAST_NAME'] as String;
@override
int compareTo(covariant Person other) => other.id.compareTo(id);
@override
bool operator ==(covariant Person other) => id == other.id;
@override
String toString() =>
'Person, ID = $id, firstName = $firstName, lastName = $lastName';
}
class PersonDB {
final _controller = StreamController<List<Person>>.broadcast();
List<Person> _persons = [];
Database? _db;
final String dbName;
PersonDB({required this.dbName});
Future<bool> close() async {
final db = _db;
if (db == null) {
return false;
}
await db.close();
return true;
}
Future<bool> open() async {
if (_db != null) {
return true;
}
final directory = await getApplicationDocumentsDirectory();
final path = '${directory.path}/$dbName';
try {
final db = await openDatabase(path);
_db = db;
// create the table if it doesn't exist
final create = '''CREATE TABLE IF NOT EXISTS PEOPLE (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
FIRST_NAME STRING NOT NULL,
LAST_NAME STRING NOT NULL
)''';
await db.execute(create);
// if everything went fine, we then read all the objects
// and populate the stream
_persons = await _fetchPeople();
_controller.add(_persons);
return true;
} catch (e) {
print('error = $e');
return false;
}
}
Future<List<Person>> _fetchPeople() async {
final db = _db;
if (db == null) {
return [];
}
try {
// read the existing data if any
final readResult = await db.query(
'PEOPLE',
distinct: true,
columns: ['ID', 'FIRST_NAME', 'LAST_NAME'],
orderBy: 'ID',
);
final people = readResult.map((row) => Person.fromData(row)).toList();
return people;
} catch (e) {
print('error = $e');
return [];
}
}
Future<bool> delete(Person person) async {
final db = _db;
if (db == null) {
return false;
}
try {
final deletedCount = await db.delete(
'PEOPLE',
where: 'ID = ?',
whereArgs: [person.id],
);
// delete it locally as well
if (deletedCount == 1) {
_persons.remove(person);
_controller.add(_persons);
return true;
} else {
return false;
}
} catch (e) {
print('Error inserting $e');
return false;
}
}
Future<bool> create(String firstName, String lastName) async {
final db = _db;
if (db == null) {
return false;
}
try {
final id = await db.insert(
'PEOPLE',
{
'FIRST_NAME': firstName,
'LAST_NAME': lastName,
},
);
final person = Person(id, firstName, lastName);
_persons.add(person);
_controller.add(_persons);
return true;
} catch (e) {
print('Error inserting $e');
return false;
}
}
// uses the person's id to update its first name and last name
Future<bool> update(Person person) async {
final db = _db;
if (db == null) {
return false;
}
try {
final updatedCount = await db.update(
'PEOPLE',
{
'FIRST_NAME': person.firstName,
'LAST_NAME': person.lastName,
},
where: 'ID = ?',
whereArgs: [person.id],
);
if (updatedCount == 1) {
_persons.removeWhere((p) => p.id == person.id);
_persons.add(person);
_controller.add(_persons);
return true;
} else {
return false;
}
} catch (e) {
print('Error inserting $e');
return false;
}
}
Stream<List<Person>> all() =>
_controller.stream.map((event) => event..sort());
}
typedef OnCompose = void Function(String firstName, String lastName);
class ComposeWidget extends StatefulWidget {
final OnCompose onCompose;
const ComposeWidget({Key? key, required this.onCompose}) : super(key: key);
@override
State<ComposeWidget> createState() => _ComposeWidgetState();
}
class _ComposeWidgetState extends State<ComposeWidget> {
final firstNameController = TextEditingController();
final lastNameController = TextEditingController();
@override
void dispose() {
firstNameController.dispose();
lastNameController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(children: [
TextField(
style: TextStyle(fontSize: 24),
decoration: InputDecoration(
hintText: 'Enter first name',
),
controller: firstNameController,
),
TextField(
style: TextStyle(fontSize: 24),
decoration: InputDecoration(
hintText: 'Enter last name',
),
controller: lastNameController,
),
TextButton(
onPressed: () {
final firstName = firstNameController.text;
final lastName = lastNameController.text;
widget.onCompose(firstName, lastName);
},
child: Text(
'Add to list',
style: TextStyle(fontSize: 24),
),
),
]),
);
}
}
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late final PersonDB _crudStorage;
@override
void initState() {
_crudStorage = PersonDB(dbName: 'db.sqlite');
_crudStorage.open();
super.initState();
}
@override
void dispose() {
_crudStorage.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('SQLite in Flutter'),
),
body: StreamBuilder(
stream: _crudStorage.all(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.active:
case ConnectionState.waiting:
if (snapshot.data == null) {
return Center(child: CircularProgressIndicator());
}
final people = snapshot.data as List<Person>;
return Column(
children: [
ComposeWidget(
onCompose: (firstName, lastName) async {
await _crudStorage.create(firstName, lastName);
},
),
Expanded(
child: ListView.builder(
itemCount: people.length,
itemBuilder: (context, index) {
final person = people[index];
return ListTile(
onTap: () async {
final update =
await showUpdateDialog(context, person);
if (update == null) {
return;
}
await _crudStorage.update(update);
},
title: Text(
person.fullName,
style: TextStyle(fontSize: 24),
),
subtitle: Text(
'ID: ${person.id}',
style: TextStyle(fontSize: 18),
),
trailing: TextButton(
onPressed: () async {
final shouldDelete =
await showDeleteDialog(context);
if (shouldDelete) {
await _crudStorage.delete(person);
}
},
child: Icon(
Icons.disabled_by_default_rounded,
color: Colors.red,
),
),
);
},
),
),
],
);
default:
return Center(child: CircularProgressIndicator());
}
},
),
);
}
}
final firstNameController = TextEditingController();
final lastNameController = TextEditingController();
Future<Person?> showUpdateDialog(BuildContext context, Person person) {
firstNameController.text = person.firstName;
lastNameController.text = person.lastName;
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Enter your udpated values here:'),
TextField(controller: firstNameController),
TextField(controller: lastNameController),
],
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(null);
},
child: Text('Cancel'),
),
TextButton(
onPressed: () {
final newPerson = Person(
person.id,
firstNameController.text,
lastNameController.text,
);
Navigator.of(context).pop(newPerson);
},
child: Text('Save'),
),
],
);
},
).then((value) {
if (value is Person) {
return value;
} else {
return null;
}
});
}
Future<bool> showDeleteDialog(BuildContext context) {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text('Are you sure you want to delete this item?'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(false);
},
child: Text('No'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: Text('Delete'),
)
],
);
},
).then(
(value) {
if (value is bool) {
return value;
} else {
return false;
}
},
);
}
SQLite Storage in Flutter
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart'
show getApplicationDocumentsDirectory;
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class Person implements Comparable {
final int id;
final String firstName;
final String lastName;
const Person(this.id, this.firstName, this.lastName);
String get fullName => '$firstName $lastName';
Person.fromData(Map<String, Object?> data)
: id = data['ID'] as int,
firstName = data['FIRST_NAME'] as String,
lastName = data['LAST_NAME'] as String;
@override
int compareTo(covariant Person other) => other.id.compareTo(id);
}
typedef OnCompose = void Function(String firstName, String lastName);
class ComposeWidget extends StatefulWidget {
final OnCompose onCompose;
const ComposeWidget({Key? key, required this.onCompose}) : super(key: key);
@override
State<ComposeWidget> createState() => _ComposeWidgetState();
}
class _ComposeWidgetState extends State<ComposeWidget> {
final firstNameController = TextEditingController();
final lastNameController = TextEditingController();
@override
void dispose() {
firstNameController.dispose();
lastNameController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(children: [
TextField(
style: TextStyle(fontSize: 24),
decoration: InputDecoration(
hintText: 'Enter first name',
),
controller: firstNameController,
),
TextField(
style: TextStyle(fontSize: 24),
decoration: InputDecoration(
hintText: 'Enter last name',
),
controller: lastNameController,
),
TextButton(
onPressed: () {
final firstName = firstNameController.text;
final lastName = lastNameController.text;
widget.onCompose(firstName, lastName);
},
child: Text(
'Add to list',
style: TextStyle(fontSize: 24),
),
),
]),
);
}
}
class _HomePageState extends State<HomePage> {
late final Database db;
bool hasSetUpAlready = false;
Future<bool> setupDatabase() async {
if (hasSetUpAlready == false) {
final directory = await getApplicationDocumentsDirectory();
final path = '${directory.path}/db.sqlite';
try {
db = await openDatabase(path);
// create the table if it doesn't exist
final create = '''CREATE TABLE IF NOT EXISTS PEOPLE (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
FIRST_NAME STRING NOT NULL,
LAST_NAME STRING NOT NULL
)''';
await db.execute(create);
hasSetUpAlready = true;
return true;
} catch (e) {
print('error = $e');
hasSetUpAlready = false;
return false;
}
} else {
return true;
}
}
Future<List<Person>> fetchPersons() async {
if (!await setupDatabase()) {
return [];
}
try {
// read the existing data if any
final readResult = await db.query(
'PEOPLE',
distinct: true,
columns: ['ID', 'FIRST_NAME', 'LAST_NAME'],
orderBy: 'ID',
);
final people = readResult.map((row) => Person.fromData(row)).toList()
..sort();
return people;
} catch (e) {
print('error = $e');
return [];
}
}
Future<bool> addPerson(String firstName, String lastName) async {
try {
await db.insert(
'PEOPLE',
{
'FIRST_NAME': firstName,
'LAST_NAME': lastName,
},
);
return true;
} catch (e) {
print('Error inserting $e');
return false;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('SQLite in Flutter'),
),
body: FutureBuilder(
future: fetchPersons(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
final people = snapshot.data as List<Person>;
return Column(
children: [
ComposeWidget(
onCompose: (firstName, lastName) async {
await addPerson(firstName, lastName);
setState(() {});
},
),
Expanded(
child: ListView.builder(
itemCount: people.length,
itemBuilder: (context, index) {
final person = people[index];
return ListTile(
title: Text(
person.fullName,
style: TextStyle(fontSize: 24),
),
subtitle: Text(
'ID: ${person.id}',
style: TextStyle(fontSize: 18),
),
);
},
),
),
],
);
default:
return CircularProgressIndicator();
}
},
),
);
}
}
Circular Progress with Percentage in Flutter
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class SizedCircularProgressIndicator extends StatelessWidget {
final double progress;
final double width;
final double height;
final TextStyle? textStyle;
const SizedCircularProgressIndicator({
Key? key,
this.textStyle,
required this.progress,
required this.width,
required this.height,
}) : super(key: key);
TextStyle get style => textStyle ?? TextStyle(fontSize: 30.0);
int get _progress => (progress * 100.0).toInt();
@override
Widget build(BuildContext context) {
return Stack(
alignment: Alignment.center,
children: [
Text('$_progress%', style: style),
SizedBox(
width: width,
height: height,
child: CircularProgressIndicator(
backgroundColor: Colors.white70,
value: progress,
color: Colors.blueAccent,
strokeWidth: 3.0,
),
),
],
);
}
}
const images = [
'https://bit.ly/3x7J5Qt',
'https://bit.ly/3ywI8l6',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3qYOtDm',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3yvFg7X',
'https://bit.ly/3ywzOla',
'https://bit.ly/3wnASpW',
'https://bit.ly/3jXSDto',
];
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageView.builder(
scrollDirection: Axis.horizontal,
itemCount: images.length,
itemBuilder: (context, index) {
return WithBlurredBackground(imageUrl: images[index]);
},
),
);
}
}
class WithBlurredBackground extends StatelessWidget {
final String imageUrl;
const WithBlurredBackground({Key? key, required this.imageUrl})
: super(key: key);
@override
Widget build(BuildContext context) {
return SizedBox.expand(
child: Stack(
alignment: Alignment.center,
fit: StackFit.passthrough,
children: [
SizedBox.expand(
child: ClipRect(
child: ImageFiltered(
imageFilter: ImageFilter.blur(
sigmaX: 10.0,
sigmaY: 10.0,
),
child: Image.network(
imageUrl,
fit: BoxFit.fitHeight,
),
),
),
),
NetworkImageWithProgress(url: imageUrl),
],
),
);
}
}
class NetworkImageWithProgress extends StatelessWidget {
final String url;
const NetworkImageWithProgress({Key? key, required this.url})
: super(key: key);
@override
Widget build(BuildContext context) {
return Image.network(
url,
loadingBuilder: (context, child, loadingProgress) {
final totalBytes = loadingProgress?.expectedTotalBytes;
final bytesLoaded = loadingProgress?.cumulativeBytesLoaded;
if (totalBytes != null && bytesLoaded != null) {
return SizedCircularProgressIndicator(
height: 100,
width: 100,
progress: bytesLoaded / totalBytes,
);
} else {
return child;
}
},
errorBuilder: (context, error, stackTrace) {
return Text('Error!');
},
);
}
}
Opening URLs in Flutter
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
class Person {
final String profileUrl;
final String name;
final String email;
final String phoneNumber;
final String websiteUrl;
const Person({
Key? key,
required this.profileUrl,
required this.name,
required this.email,
required this.phoneNumber,
required this.websiteUrl,
});
Person.vandad()
: profileUrl = 'https://bit.ly/3jwusS0',
name = 'Vandad Nahavandipoor',
email = 'vandad.np@gmail.com',
phoneNumber = '071234567',
websiteUrl = 'https://pixolity.se';
}
void open(String url) async {
if (await canLaunch(url)) {
await launch(url);
}
}
class PersonNameView extends StatelessWidget {
final Person person;
const PersonNameView(this.person, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(
person.name,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.black,
),
);
}
}
class PersonEmailView extends StatelessWidget {
final Person person;
const PersonEmailView(this.person, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () {
open('mailto:${person.email}');
},
child: Text(
'💌 Email me',
style: TextStyle(fontSize: 20.0),
),
);
}
}
class PersonPhoneView extends StatelessWidget {
final Person person;
const PersonPhoneView(this.person, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () {
open('tel://${person.phoneNumber}');
},
child: Text(
'🤙🏻 Call me',
style: TextStyle(fontSize: 20.0),
),
);
}
}
class PersonWebsiteView extends StatelessWidget {
final Person person;
const PersonWebsiteView(this.person, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () {
open(person.websiteUrl);
},
child: Text(
'🌍 Visit my website',
style: TextStyle(fontSize: 20.0),
),
);
}
}
const bigText = TextStyle(fontSize: 20.0);
class PersonView extends StatelessWidget {
final Person person;
const PersonView({Key? key, required this.person}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: Colors.blue[50],
borderRadius: BorderRadius.circular(16.0),
border: Border.all(color: Colors.white, width: 3.0),
boxShadow: [
BoxShadow(
blurRadius: 30.0,
color: Colors.black.withAlpha(50),
spreadRadius: 20.0,
),
]),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircleAvatar(
radius: 100.0,
backgroundImage: NetworkImage(person.profileUrl),
),
SizedBox(height: 10),
PersonNameView(person),
PersonEmailView(person),
PersonPhoneView(person),
PersonWebsiteView(person)
],
),
),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SingleChildScrollView(
child: PersonView(
person: Person.vandad(),
),
),
),
);
}
}
Commodore 64 Screen in Flutter
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
const textColor = Color.fromRGBO(156, 156, 247, 1);
class BoxPainter extends CustomPainter {
final bool isBlinking;
BoxPainter({required this.isBlinking});
@override
void paint(Canvas canvas, Size size) {
if (isBlinking) {
final rect = Rect.fromLTWH(
size.width / 20.0,
size.height / 2.8,
size.width / 24.0,
size.height / 13.0,
);
final paint = Paint()..color = textColor;
canvas.drawRect(rect, paint);
}
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
class ReadyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final textStyle = TextStyle(
color: textColor,
fontSize: size.width / 45.0,
fontFamily: 'C64',
);
final span = TextSpan(
text: 'READY',
style: textStyle,
);
final painter = TextPainter(
text: span,
textDirection: TextDirection.ltr,
);
painter.layout(
minWidth: 0,
maxWidth: size.width,
);
final offset = Offset(
painter.width / 2.0,
painter.height * 8.0,
);
painter.paint(canvas, offset);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
class SubTitlePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final textStyle = TextStyle(
color: textColor,
fontSize: size.width / 45.0,
fontFamily: 'C64',
);
final span = TextSpan(
text: '64K RAM SYSTEM 38911 BASIC BYTES FREE',
style: textStyle,
);
final painter = TextPainter(
text: span,
textDirection: TextDirection.ltr,
);
painter.layout(
minWidth: 0,
maxWidth: size.width,
);
final offset = Offset(
size.width - painter.width - (size.width / 11),
painter.height * 6.0,
);
painter.paint(canvas, offset);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
class TitlePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final textStyle = TextStyle(
color: textColor,
fontSize: size.width / 40.0,
fontFamily: 'C64',
);
final span = TextSpan(
text: '**** COMMODORE 64 BASIC V2 ****',
style: textStyle,
);
final painter = TextPainter(
text: span,
textDirection: TextDirection.ltr,
);
painter.layout(
minWidth: 0,
maxWidth: size.width,
);
final offset = Offset(
size.width - painter.width - (size.width / 9),
size.height / 6,
);
painter.paint(canvas, offset);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
class BackgroundPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final border = size.width / 20.0;
final color = Color.fromRGBO(
58,
57,
213,
1,
);
final paint = Paint()..color = color;
final rect = Rect.fromLTWH(
border,
border,
size.width - (border * 2.0),
size.height - (border * 2.0),
);
canvas.drawRect(rect, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
class BorderPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()..color = textColor;
final rect = Rect.fromLTWH(
0.0,
0.0,
size.width,
size.height,
);
canvas.drawRect(rect, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
class Commodore64Painter extends CustomPainter {
final bool isBlinking;
late final List<CustomPainter> painters;
Commodore64Painter({required this.isBlinking}) {
painters = [
BorderPainter(),
BackgroundPainter(),
TitlePainter(),
SubTitlePainter(),
ReadyPainter(),
BoxPainter(isBlinking: isBlinking)
];
}
@override
void paint(Canvas canvas, Size size) {
painters.forEach(
(p) => p.paint(
canvas,
size,
),
);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => painters
.map((p) => p.shouldRepaint(oldDelegate))
.reduce((p1, p2) => p1 || p2);
}
class Commodore64 extends StatefulWidget {
const Commodore64({Key? key}) : super(key: key);
@override
State<Commodore64> createState() => _Commodore64State();
}
class _Commodore64State extends State<Commodore64> {
bool _isBlinking = false;
final timer = Stream.periodic(Duration(seconds: 1), (value) => value);
void _triggerRedraw() async {
await for (final _ in timer) {
setState(() {
_isBlinking = !_isBlinking;
});
}
}
@override
void initState() {
super.initState();
_triggerRedraw();
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraints) {
return Container(
width: constraints.maxWidth,
height: constraints.maxWidth / (16.0 / 9.0),
child: CustomPaint(
painter: Commodore64Painter(isBlinking: _isBlinking),
),
);
});
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Commodore64(),
),
);
}
}
Animated Lists in Flutter
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class NetworkImage extends StatelessWidget {
final String url;
const NetworkImage({
Key? key,
required this.url,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Image.network(
url,
loadingBuilder: (context, child, loadingProgress) {
final totalBytes = loadingProgress?.expectedTotalBytes;
final bytesLoaded = loadingProgress?.cumulativeBytesLoaded;
if (totalBytes != null && bytesLoaded != null) {
return LinearProgressIndicator(
value: bytesLoaded / totalBytes,
);
} else {
return child;
}
},
errorBuilder: (context, error, stackTrace) {
return Text('Error!');
},
);
}
}
class NetworkImageCard extends StatelessWidget {
final String url;
const NetworkImageCard({
Key? key,
required this.url,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
),
child: NetworkImage(
url: url,
),
),
);
}
}
const imageUrls = [
'https://bit.ly/3x7J5Qt',
'https://bit.ly/3ywI8l6',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3qYOtDm',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3yvFg7X',
'https://bit.ly/3ywzOla',
'https://bit.ly/3wnASpW',
'https://bit.ly/3jXSDto',
];
Stream<String> images() => Stream.periodic(
Duration(seconds: 3),
(index) => index % imageUrls.length,
).map((index) => imageUrls[index]);
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final GlobalKey<AnimatedListState> _key = GlobalKey();
List<String> imageUrls = [];
void populateList() async {
await for (final url in images()) {
imageUrls.insert(0, url);
_key.currentState?.insertItem(
0,
duration: Duration(milliseconds: 400),
);
}
}
@override
Widget build(BuildContext context) {
populateList();
return Scaffold(
appBar: AppBar(
title: Text('Animated Lists in Flutter'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: AnimatedList(
key: _key,
initialItemCount: imageUrls.length,
itemBuilder: (context, index, animation) {
final imageUrl = imageUrls[index];
return SizeTransition(
sizeFactor: animation.drive(
CurveTween(curve: Curves.elasticInOut),
),
child: Column(
children: [
NetworkImageCard(url: imageUrl),
SizedBox(height: 10.0),
],
),
);
},
),
),
);
}
}
CheckboxListTile
in Flutter
import 'package:flutter/material.dart';
enum Item { umbrella, coat, boots }
extension Info on Item {
String get title {
switch (this) {
case Item.umbrella:
return 'Umbrella';
case Item.boots:
return 'Boots';
case Item.coat:
return 'Jacket';
}
}
String get icon {
switch (this) {
case Item.umbrella:
return '☂️';
case Item.boots:
return '🥾';
case Item.coat:
return '🧥';
}
}
}
typedef OnChecked = void Function(bool);
class Tile extends StatelessWidget {
final Item item;
final bool isChecked;
final OnChecked onChecked;
const Tile({
Key? key,
required this.item,
required this.isChecked,
required this.onChecked,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ConstrainedBox(
constraints: BoxConstraints(minHeight: 100.0),
child: Center(
child: CheckboxListTile(
shape: ContinuousRectangleBorder(),
value: isChecked,
secondary: Text(
item.icon,
style: TextStyle(fontSize: 30.0),
),
title: Text(
item.title,
style: TextStyle(fontSize: 40.0),
),
onChanged: (value) {
onChecked(value ?? false);
},
),
),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final Set<Item> _enabledItems = {};
Widget get listView {
return ListView.builder(
shrinkWrap: true,
itemBuilder: (context, index) {
final item = Item.values[index];
final isChecked = _enabledItems.contains(item);
return Tile(
isChecked: isChecked,
item: item,
onChecked: (isChecked) {
setState(() {
if (isChecked) {
_enabledItems.add(item);
} else {
_enabledItems.remove(item);
}
});
},
);
},
itemCount: Item.values.length,
);
}
Widget get title {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Remember to pick all items! It's going to be rainy today!",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 40),
),
);
}
Widget get readyButton {
final onPressed = () async {
// program this
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text('You seem to be ready for a rainy day! ✅'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('OK'),
)
],
);
},
);
};
final isEnabled = _enabledItems.containsAll(Item.values);
return FractionallySizedBox(
widthFactor: 0.8,
child: ElevatedButton(
onPressed: isEnabled ? onPressed : null,
child: Text('Ready!'),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Checkbox List Tile in Flutter'),
),
body: SingleChildScrollView(
child: Column(
children: [
title,
listView,
SizedBox(height: 50.0),
readyButton,
],
),
),
);
}
}
-
Operator on String
in Dart
extension Minus on String {
String operator -(String rhs) => replaceAll(rhs, '');
}
void testIt() {
assert('foo bar' - 'foo ' == 'bar');
assert('foo bar foo' - 'foo' == ' bar ');
assert('bar' - 'foo' == 'bar');
assert('BAR' - 'bar' == 'BAR');
assert('foo' - 'FOO' == 'foo');
assert('foobarbaz' - 'bar' == 'foobaz');
}
Dart Progress for Future<T>
import 'dart:io' show stdout;
import 'dart:async' show Future, Stream;
const loadingSequence = ['⢿', '⣻', '⣽', '⣾', '⣷', '⣯', '⣟', '⡿'];
const escape = '\x1B[38;5;';
const color = '${escape}1m';
const textColor = '${escape}6m';
String progress({required int value, required String text}) {
final progress = '$color${loadingSequence[value % loadingSequence.length]}';
final coloredText = '$textColor$text';
return '$progress\t$coloredText';
}
Future<T> performWithProgress<T>({
required Future<T> task,
required String progressText,
}) {
final stream = Stream<String>.periodic(
Duration(milliseconds: 100),
(value) => progress(
value: value,
text: progressText,
),
);
final subscription = stream.listen(
(event) {
stdout.write('\r $event');
},
);
task.whenComplete(() {
stdout.write('\r ✅\t$progressText');
stdout.write('\n');
subscription.cancel();
});
return task;
}
final task1 = Future.delayed(Duration(seconds: 1), () => 'Result 1');
final task2 = Future.delayed(Duration(seconds: 2), () => 'Result 2');
final task3 = Future.delayed(Duration(seconds: 3), () => 'Result 3');
void main(List<String> args) async {
var result = await performWithProgress(
task: task1,
progressText: 'Loading task 1',
);
print('\tTask 1 result: $result');
result = await performWithProgress(
task: task2,
progressText: 'Loading task 2',
);
print('\tTask 2 result: $result');
result = await performWithProgress(
task: task3,
progressText: 'Loading task 3',
);
print('\tTask 3 result: $result');
}
Move Widget Shadows with Animation
import 'package:flutter/material.dart';
class ImageTransition extends AnimatedWidget {
final String imageUrl;
Animation<double> get shadowXOffset => listenable as Animation<double>;
const ImageTransition(this.imageUrl, {shadowXOffset})
: super(listenable: shadowXOffset);
@override
Widget build(BuildContext context) {
return Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
boxShadow: [
BoxShadow(
blurRadius: 10,
offset: Offset(shadowXOffset.value, 20.0),
color: Colors.black.withAlpha(100),
spreadRadius: -10,
)
],
),
child: Image.network(imageUrl),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class CustomCurve extends CurveTween {
CustomCurve() : super(curve: Curves.easeInOutSine);
@override
double transform(double t) {
return (super.transform(t) - 0.5) * 25.0;
}
}
class _HomePageState extends State<HomePage>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _animation;
@override
void initState() {
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 1),
);
_animation = CustomCurve().animate(_controller);
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
_controller.repeat(reverse: true);
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: ImageTransition(
'https://bit.ly/3x7J5Qt',
shadowXOffset: _animation,
),
),
),
);
}
}
Gallery with Blurred Backgrounds in Flutter
import 'package:flutter/material.dart';
const images = [
'https://bit.ly/3x7J5Qt',
'https://bit.ly/3ywI8l6',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3qYOtDm',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3yvFg7X',
'https://bit.ly/3ywzOla',
'https://bit.ly/3wnASpW',
'https://bit.ly/3jXSDto',
];
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageView.builder(
scrollDirection: Axis.horizontal,
itemCount: images.length,
itemBuilder: (context, index) {
return WithBlurredBackground(imageUrl: images[index]);
},
),
);
}
}
class WithBlurredBackground extends StatelessWidget {
final String imageUrl;
const WithBlurredBackground({Key? key, required this.imageUrl})
: super(key: key);
@override
Widget build(BuildContext context) {
return SizedBox.expand(
child: Stack(
alignment: Alignment.center,
fit: StackFit.passthrough,
children: [
SizedBox.expand(
child: ClipRect(
child: ImageFiltered(
imageFilter: ImageFilter.blur(
sigmaX: 10.0,
sigmaY: 10.0,
),
child: Image.network(
imageUrl,
fit: BoxFit.fitHeight,
),
),
),
),
Image.network(imageUrl),
],
),
);
}
}
Custom Path Clippers in Flutter
import 'package:flutter/material.dart';
const images = [
'https://bit.ly/3x7J5Qt',
'https://bit.ly/3ywI8l6',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3qYOtDm',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3yvFg7X',
'https://bit.ly/3ywzOla',
'https://bit.ly/3wnASpW',
'https://bit.ly/3jXSDto',
];
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.only(
top: 40.0,
left: 10.0,
right: 10.0,
),
child: Column(
children: images
.map((url) => ElevatedNetworkImage(url: url))
.expand(
(img) => [
img,
SizedBox(height: 30.0),
],
)
.toList(),
),
),
),
);
}
}
class ElevatedNetworkImage extends StatelessWidget {
final String url;
const ElevatedNetworkImage({Key? key, required this.url}) : super(key: key);
@override
Widget build(BuildContext context) {
return PhysicalShape(
color: Colors.white,
clipper: Clipper(),
elevation: 20.0,
clipBehavior: Clip.none,
shadowColor: Colors.white.withAlpha(200),
child: CutEdges(
child: Image.network(url),
),
);
}
}
class Clipper extends CustomClipper<Path> {
static const variance = 0.2;
static const reverse = 1.0 - variance;
@override
Path getClip(Size size) {
final path = Path();
path.moveTo(0.0, size.height * Clipper.variance);
path.lineTo(size.width * Clipper.variance, 0.0);
path.lineTo(size.width, 0.0);
path.lineTo(size.width, size.height * Clipper.reverse);
path.lineTo(size.width * Clipper.reverse, size.height);
path.lineTo(0.0, size.height);
path.lineTo(0.0, size.height * Clipper.variance);
path.close;
return path;
}
@override
bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false;
}
class CutEdges extends StatelessWidget {
final Widget child;
const CutEdges({Key? key, required this.child}) : super(key: key);
@override
Widget build(BuildContext context) {
return ClipPath(
clipper: Clipper(),
child: child,
);
}
}
Frost Effect on Images in Flutter
import 'package:flutter/material.dart';
const images = [
'https://bit.ly/3x7J5Qt',
'https://bit.ly/3ywI8l6',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3qYOtDm',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3yvFg7X',
'https://bit.ly/3ywzOla',
'https://bit.ly/3wnASpW',
'https://bit.ly/3jXSDto',
];
final loremIpsum =
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: const EdgeInsets.fromLTRB(
8.0,
0.0,
8.0,
0.0,
),
child: SingleChildScrollView(
child: Column(
children: images
.map(
(url) => GlossyNetworkImageWithProgress(
url: url,
title: 'Image title',
description: loremIpsum,
),
)
.expand(
(image) => [
image,
SizedBox(height: 16.0),
],
)
.toList(),
),
),
),
),
);
}
}
class GlossyNetworkImageWithProgress extends StatefulWidget {
final String url;
final String title;
final String description;
const GlossyNetworkImageWithProgress(
{Key? key,
required this.url,
required this.title,
required this.description})
: super(key: key);
@override
_GlossyNetworkImageWithProgressState createState() =>
_GlossyNetworkImageWithProgressState();
}
class _GlossyNetworkImageWithProgressState
extends State<GlossyNetworkImageWithProgress>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 1),
);
_animation = Tween(
begin: 0.0,
end: 1.0,
).animate(_controller);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final networkImage = Image.network(
widget.url,
fit: BoxFit.fitHeight,
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
_controller.reset();
_controller.forward();
return FadeTransition(
opacity: _animation,
child: CustomBox(
child: child,
),
);
},
loadingBuilder: (context, child, loadingProgress) {
final totalBytes = loadingProgress?.expectedTotalBytes;
final bytesLoaded = loadingProgress?.cumulativeBytesLoaded;
if (totalBytes != null && bytesLoaded != null) {
return CustomBox(
child: CircularProgressIndicator(
backgroundColor: Colors.white70,
value: bytesLoaded / totalBytes,
color: Colors.blue[900],
strokeWidth: 5.0,
),
);
} else {
return child;
}
},
errorBuilder: (context, error, stackTrace) {
return Text('Error!');
},
);
return BottomGloss(
networkImage: networkImage,
title: widget.title,
description: widget.description,
);
}
}
class BottomGloss extends StatelessWidget {
final String title;
final String description;
const BottomGloss(
{Key? key,
required this.networkImage,
required this.title,
required this.description})
: super(key: key);
final Image networkImage;
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
child: Stack(
fit: StackFit.passthrough,
children: [
networkImage,
Container(
height: 300.0,
alignment: Alignment.bottomCenter,
child: ClipRect(
child: FractionallySizedBox(
heightFactor: 0.5,
child: BackdropFilter(
filter: ImageFilter.blur(
sigmaX: 10.0,
sigmaY: 10.0,
),
child: BottomContents(
title: title,
description: description,
),
),
),
),
),
],
),
);
}
}
class BottomContents extends StatelessWidget {
final String title;
final String description;
const BottomContents({
Key? key,
required this.title,
required this.description,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white.withOpacity(0.4),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TitleText(text: title),
SizedBox(height: 8.0),
SubTitleText(text: description),
],
),
),
),
);
}
}
class SubTitleText extends StatelessWidget {
final String text;
const SubTitleText({Key? key, required this.text}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(
text,
style: TextStyle(
color: Colors.black,
fontSize: 20.0,
),
);
}
}
class TitleText extends StatelessWidget {
final String text;
const TitleText({Key? key, required this.text}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(
text,
style: TextStyle(
color: Colors.white,
fontSize: 30.0,
),
);
}
}
class CustomBox extends StatelessWidget {
final Widget child;
const CustomBox({Key? key, required this.child}) : super(key: key);
@override
Widget build(BuildContext context) {
return SizedBox(
height: 300.0,
width: MediaQuery.of(context).size.width,
child: child is ProgressIndicator ? Center(child: child) : child,
);
}
}
Custom Clippers in Flutter
import 'package:flutter/material.dart';
import 'dart:math' show min;
const gridImages = [
'https://bit.ly/3x7J5Qt',
'https://bit.ly/3ywI8l6',
'https://bit.ly/3jRSRCu',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3qYOtDm',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3yvFg7X',
'https://bit.ly/3ywzOla',
'https://bit.ly/3wnASpW',
'https://bit.ly/3jXSDto',
];
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: GridView.count(
padding: const EdgeInsets.fromLTRB(8.0, 48.0, 8.0, 48.0),
crossAxisCount: 2,
mainAxisSpacing: 8.0,
crossAxisSpacing: 8.0,
children: gridImages
.map((url) => NetworkImageWithProgress(url: url))
.toList(),
),
);
}
}
class CircularClipper extends CustomClipper<Rect> {
@override
Rect getClip(Size size) {
final center = Offset(
size.width / 2.0,
size.height / 2.0,
);
final minWidthorHeight = min(size.width, size.height);
return Rect.fromCenter(
center: center,
width: minWidthorHeight,
height: minWidthorHeight,
);
}
@override
bool shouldReclip(covariant CustomClipper<Rect> oldClipper) => false;
}
class Circular extends StatelessWidget {
final Widget child;
const Circular({Key? key, required this.child}) : super(key: key);
@override
Widget build(BuildContext context) {
return ClipOval(
clipper: CircularClipper(),
child: child,
);
}
}
class CustomBox extends StatelessWidget {
final Widget child;
const CustomBox({Key? key, required this.child}) : super(key: key);
@override
Widget build(BuildContext context) {
return SizedBox(
height: 220.0,
width: MediaQuery.of(context).size.width,
child: child is ProgressIndicator
? Center(child: child)
: Circular(child: child),
);
}
}
class NetworkImageWithProgress extends StatefulWidget {
final String url;
const NetworkImageWithProgress({Key? key, required this.url})
: super(key: key);
@override
_NetworkImageWithProgressState createState() =>
_NetworkImageWithProgressState();
}
class _NetworkImageWithProgressState extends State<NetworkImageWithProgress>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 1),
);
_animation = Tween(
begin: 0.0,
end: 1.0,
).animate(_controller);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Image.network(
widget.url,
fit: BoxFit.fitHeight,
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
_controller.reset();
_controller.forward();
return FadeTransition(
opacity: _animation,
child: CustomBox(
child: child,
),
);
},
loadingBuilder: (context, child, loadingProgress) {
final totalBytes = loadingProgress?.expectedTotalBytes;
final bytesLoaded = loadingProgress?.cumulativeBytesLoaded;
if (totalBytes != null && bytesLoaded != null) {
return CustomBox(
child: CircularProgressIndicator(
backgroundColor: Colors.white70,
value: bytesLoaded / totalBytes,
color: Colors.blue[900],
strokeWidth: 5.0,
),
);
} else {
return child;
}
},
errorBuilder: (context, error, stackTrace) {
return Text('Error!');
},
);
}
}
Check if Website is Up or Down in Dart
class UpStatus {
final bool isUp;
final DateTime timestamp;
const UpStatus(this.isUp, this.timestamp);
}
class Pling {
final String url;
final Duration interval;
const Pling({
required this.url,
required this.interval,
});
Stream<UpStatus> checkIfUp() =>
Stream.periodic(interval, (_) => DateTime.now()).asyncExpand(
(now) => HttpClient()
.headUrl(Uri.parse(url))
.then((req) => req..followRedirects = false)
.then((req) => req.close())
.then((resp) => resp.statusCode)
.then((statusCode) => statusCode == 200)
.onError((error, stackTrace) => false)
.then((isUp) => UpStatus(isUp, now))
.asStream(),
);
}
const oneSecond = Duration(seconds: 1);
const url = 'https://dart.dev';
extension IsOrIsNot on bool {
String get isOrIsNot => this ? 'is' : 'is not';
}
void testIt() async {
final pling = Pling(
url: url,
interval: oneSecond,
);
await for (final upStatus in pling.checkIfUp()) {
final timestamp = upStatus.timestamp;
final isUpStr = upStatus.isUp.isOrIsNot;
print('$url $isUpStr up at $timestamp');
}
}
Section Titles on ListView in Flutter
import 'package:flutter/material.dart';
final List<Section> allSections = [
Section(
'Spring',
[
'https://cnn.it/3xu58Ap',
'https://bit.ly/3ueqqC1',
],
),
Section(
'Summer',
[
'https://bit.ly/3ojNhLc',
'https://bit.ly/2VcCSow',
],
),
Section(
'Autumn',
[
'https://bit.ly/3ib1TJk',
'https://bit.ly/2XSpjvq',
],
),
Section(
'Winter',
[
'https://bit.ly/3iaQNE7',
'https://bit.ly/3AY8YE4',
],
),
];
class Section {
final String title;
final List<String> urls;
const Section(this.title, this.urls);
}
extension ToWidgets on Section {
Iterable<Widget> toNetworkImageCards() {
return [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
title,
style: TextStyle(
fontSize: 40,
),
),
),
...urls.expand(
(url) => [
NetworkImageCard(url: url),
SizedBox(height: 10),
],
),
];
}
}
class NetworkImageCard extends StatelessWidget {
final String url;
const NetworkImageCard({
Key? key,
required this.url,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Container(
child: NetworkImageWithProgress(
url: url,
),
),
);
}
}
class NetworkImageWithProgress extends StatefulWidget {
final String url;
const NetworkImageWithProgress({Key? key, required this.url})
: super(key: key);
@override
_NetworkImageWithProgressState createState() =>
_NetworkImageWithProgressState();
}
class _NetworkImageWithProgressState extends State<NetworkImageWithProgress>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 1),
);
_animation = Tween(
begin: 0.0,
end: 1.0,
).animate(_controller);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Image.network(
widget.url,
fit: BoxFit.fitWidth,
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
_controller.reset();
_controller.forward();
return FadeTransition(
opacity: _animation,
child: CustomBox(
child: child,
),
);
},
loadingBuilder: (context, child, loadingProgress) {
final totalBytes = loadingProgress?.expectedTotalBytes;
final bytesLoaded = loadingProgress?.cumulativeBytesLoaded;
if (totalBytes != null && bytesLoaded != null) {
return CustomBox(
child: CircularProgressIndicator(
backgroundColor: Colors.white70,
value: bytesLoaded / totalBytes,
color: Colors.blue[900],
strokeWidth: 5.0,
),
);
} else {
return child;
}
},
errorBuilder: (context, error, stackTrace) {
return Text('Error!');
},
);
}
}
class CustomBox extends StatelessWidget {
final Widget child;
const CustomBox({Key? key, required this.child}) : super(key: key);
@override
Widget build(BuildContext context) {
return SizedBox(
height: 220.0,
width: MediaQuery.of(context).size.width,
child: child is ProgressIndicator ? Center(child: child) : child,
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemBuilder: (context, index) {
final section = allSections[index];
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: section.toNetworkImageCards().toList(),
);
},
itemCount: allSections.length,
),
);
}
}
Circular Progress in Flutter
import 'package:flutter/material.dart';
class CustomBox extends StatelessWidget {
final Widget child;
const CustomBox({Key? key, required this.child}) : super(key: key);
@override
Widget build(BuildContext context) {
return SizedBox(
height: 220.0,
width: MediaQuery.of(context).size.width,
child: Center(child: child),
);
}
}
class NetworkImageWithProgress extends StatefulWidget {
final String url;
const NetworkImageWithProgress({Key? key, required this.url})
: super(key: key);
@override
_NetworkImageWithProgressState createState() =>
_NetworkImageWithProgressState();
}
class _NetworkImageWithProgressState extends State<NetworkImageWithProgress>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 1),
);
_animation = Tween(
begin: 0.0,
end: 1.0,
).animate(_controller);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Image.network(
widget.url,
fit: BoxFit.fitWidth,
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
_controller.reset();
_controller.forward();
return FadeTransition(
opacity: _animation,
child: CustomBox(
child: child,
),
);
},
loadingBuilder: (context, child, loadingProgress) {
final totalBytes = loadingProgress?.expectedTotalBytes;
final bytesLoaded = loadingProgress?.cumulativeBytesLoaded;
if (totalBytes != null && bytesLoaded != null) {
return CustomBox(
child: CircularProgressIndicator(
backgroundColor: Colors.white70,
value: bytesLoaded / totalBytes,
color: Colors.blue[900],
strokeWidth: 5.0,
),
);
} else {
return child;
}
},
errorBuilder: (context, error, stackTrace) {
return Text('Error!');
},
);
}
}
final images = [
'https://bit.ly/3x7J5Qt',
'https://bit.ly/3ywI8l6',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3ywzOla',
].map((url) => NetworkImageWithProgress(url: url)).expand(
(element) => [
element,
SizedBox(
height: 10.0,
)
],
);
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: images.toList(),
),
),
);
}
}
Displaying Scroll Wheels in Flutter
import 'package:flutter/material.dart';
class FadingNetworkImage extends StatefulWidget {
final String url;
const FadingNetworkImage({Key? key, required this.url}) : super(key: key);
@override
_FadingNetworkImageState createState() => _FadingNetworkImageState();
}
class _FadingNetworkImageState extends State<FadingNetworkImage>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _animation;
@override
void initState() {
super.initState();
_controller =
AnimationController(vsync: this, duration: Duration(seconds: 1));
_animation = Tween(begin: 0.0, end: 1.0).animate(_controller);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Image.network(
widget.url,
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
_controller.reset();
_controller.forward();
return FadeTransition(
opacity: _animation,
child: child,
);
},
loadingBuilder: (context, child, loadingProgress) {
final totalBytes = loadingProgress?.expectedTotalBytes;
final bytesLoaded = loadingProgress?.cumulativeBytesLoaded;
if (totalBytes != null && bytesLoaded != null) {
return LinearProgressIndicator(
value: bytesLoaded / totalBytes,
);
} else {
return child;
}
},
errorBuilder: (context, error, stackTrace) {
return Text('Error!');
},
);
}
}
final images = [
'https://bit.ly/3x7J5Qt',
'https://bit.ly/3ywI8l6',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3ywzOla',
].map((i) => NetworkImageCard(url: i));
class NetworkImageCard extends StatelessWidget {
final String url;
const NetworkImageCard({
Key? key,
required this.url,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
boxShadow: [
BoxShadow(
blurRadius: 5,
offset: Offset(0, 0),
color: Colors.black.withAlpha(40),
spreadRadius: 5,
)
],
),
child: FadingNetworkImage(
url: url,
),
),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListWheelScrollView(
itemExtent: 164.0,
squeeze: 0.9,
perspective: 0.003,
children: images.toList(),
),
);
}
}
Post Messages to Slack with Dart
import 'dart:convert' show utf8;
import 'dart:convert' show json;
class SlackMessage {
final String? inChannel;
final String? userName;
final String message;
final String? iconEmoji;
const SlackMessage({
required this.inChannel,
required this.userName,
required this.message,
required this.iconEmoji,
});
Future<bool> send(String webhookUrl) async {
final payload = {
'text': message,
if (inChannel != null) 'channel': inChannel!,
if (userName != null) 'username': userName!,
if (iconEmoji != null) 'icon_emoji': iconEmoji!
};
final request = await HttpClient().postUrl(Uri.parse(webhookUrl));
final payloadData = utf8.encode(json.encode(payload));
request.add(payloadData);
final response = await request.close();
return response.statusCode == 200;
}
}
const webhookUrl = 'put your webhook url here';
void testIt() async {
final message = SlackMessage(
inChannel: 'dart',
userName: 'Flutter',
message: 'Hello from Dart in Terminal',
iconEmoji: 'blue_heart:',
);
if (await message.send(webhookUrl)) {
print('Successfully sent the message');
} else {
print('Could not send the message');
}
}
Unwrap List<T?>?
in Dart
extension Unwrap<T> on List<T?>? {
List<T> unwrap() => (this ?? []).whereType<T>().toList();
}
void testOptionalListOfOptionals() {
final List<int?>? optionalListOfOptionals = [1, 2, null, 3, null];
final unwrapped = optionalListOfOptionals.unwrap(); // List<int>
print(unwrapped); // prints [1, 2, 3]
}
void testListOfOptionals() {
final listOfOptionals = [20, 30, null, 40]; // List<int?>
final unwrapped = listOfOptionals.unwrap(); // List<int>
print(unwrapped); // prints [20, 30, 40]
}
void testNormalList() {
final list = [50, 60, 70]; // List<int>
final unwrapped = list.unwrap(); // List<int>
print(unwrapped); // prints [50, 60, 70]
}
Avoiding UI Jitters When Switching Widgets in Flutter
const imageUrls = [
'https://cnn.it/3xu58Ap', // spring
'https://bit.ly/2VcCSow', // summer
'https://bit.ly/3A3zStC', // autumn
'https://bit.ly/2TNY7wi' // winter
];
extension ToNetworkImage<T extends String> on List<T> {
List<Widget> toNetworkImages() => map((s) => Image.network(s)).toList();
}
class HomePage extends StatefulWidget {
@override
State createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var _currentIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Indexed Stack')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IndexedStack(
index: _currentIndex,
children: imageUrls.toNetworkImages(),
),
TextButton(
onPressed: () {
setState(
() {
_currentIndex++;
if (_currentIndex >= imageUrls.length) {
_currentIndex = 0;
}
},
);
},
child: Text('Go to next season'),
)
],
),
),
);
}
}
Detect Redirects in Dart
Future<bool> doesRedirect(String url) => HttpClient()
.headUrl(Uri.parse(url))
.then((req) => req..followRedirects = false)
.then((req) => req.close())
.then((resp) => resp.statusCode)
.then((statusCode) => [301, 302, 303, 307, 308].contains(statusCode));
void testIt() async {
final test1 = await doesRedirect('https://cnn.it/3xu58Ap');
assert(test1 == true);
final test2 = await doesRedirect('https://dart.dev');
assert(test2 == false);
final test3 = await doesRedirect('https://bit.ly/2VcCSow');
assert(test3 == true);
}
Proportional Constraints in Flutter
class ProportionalWidthNetworkImage extends StatelessWidget {
final String url;
final double widthProportion;
const ProportionalWidthNetworkImage(
{Key? key, required this.url, required this.widthProportion})
: super(key: key);
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
return Image.network(
url,
loadingBuilder: (context, child, loadingProgress) {
final widget =
loadingProgress == null ? child : LinearProgressIndicator();
return Container(
width: constraints.maxWidth * widthProportion,
child: widget,
);
},
);
},
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ProportionalWidthNetworkImage(
url: 'https://cnn.it/3xu58Ap',
widthProportion: 0.8,
),
),
);
}
}
Displaying Cupertino Action Sheets in Flutter
import 'package:flutter/cupertino.dart';
enum Season { spring, summer, autumn, winter }
extension Title on Season {
String get title => describeEnum(this).capitalized;
}
extension Caps on String {
String get capitalized => this[0].toUpperCase() + substring(1);
}
extension ToWidget on Season {
Widget toWidget() {
switch (this) {
case Season.spring:
return Image.network('https://cnn.it/3xu58Ap');
case Season.summer:
return Image.network('https://bit.ly/2VcCSow');
case Season.autumn:
return Image.network('https://bit.ly/3A3zStC');
case Season.winter:
return Image.network('https://bit.ly/2TNY7wi');
}
}
}
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
Future<Season> _chooseSeason(
BuildContext context,
Season currentSeason,
) async {
CupertinoActionSheet actionSheet(BuildContext context) {
return CupertinoActionSheet(
title: Text('Choose your favorite season:'),
actions: Season.values
.map(
(season) => CupertinoActionSheetAction(
onPressed: () {
Navigator.of(context).pop(season);
},
child: Text(season.title),
),
)
.toList(),
cancelButton: CupertinoActionSheetAction(
onPressed: () {
Navigator.of(context).pop(currentSeason);
},
child: Text('Cancel'),
),
);
}
return await showCupertinoModalPopup(
context: context,
builder: (context) => actionSheet(context),
);
}
class _HomePageState extends State<HomePage> {
var _season = Season.spring;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_season.title),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_season.toWidget(),
TextButton(
onPressed: () async {
_season = await _chooseSeason(
context,
_season,
);
setState(() {});
},
child: Text('Choose a season'),
),
],
),
);
}
}
Rotating List<T>
in Dart
extension Rotate<T> on List<T> {
int _rotationTimes(int places) {
if (isEmpty) {
return 0;
}
if (places == 0) {
throw ArgumentError('places should be more than 0');
}
return places % length;
}
List<T> rotatedRight(int places) {
final times = _rotationTimes(places);
if (times == 0) {
return this;
} else {
final cutOff = length - times;
return sublist(cutOff)..addAll(sublist(0, cutOff));
}
}
List<T> rotatedLeft(int places) {
final times = _rotationTimes(places);
if (times == 0) {
return this;
} else {
return sublist(times)..addAll(sublist(0, times));
}
}
}
extension Equality<T extends Comparable> on List<T> {
bool isEqualTo(List<T> other) {
if (other.length != length) {
return false;
}
for (var i = 0; i < length; i++) {
if (other[i] != this[i]) {
return false;
}
}
return true;
}
}
const arr = [1, 2, 3];
void testIt() {
assert(arr.rotatedRight(1).isEqualTo([3, 1, 2]));
assert(arr.rotatedRight(2).isEqualTo([2, 3, 1]));
assert(arr.rotatedRight(3).isEqualTo([1, 2, 3]));
assert(arr.rotatedRight(4).isEqualTo([3, 1, 2]));
assert(arr.rotatedLeft(1).isEqualTo([2, 3, 1]));
assert(arr.rotatedLeft(2).isEqualTo([3, 1, 2]));
assert(arr.rotatedLeft(3).isEqualTo([1, 2, 3]));
assert(arr.rotatedLeft(4).isEqualTo([2, 3, 1]));
}
Displaying SnackBars in Flutter
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Hello world'),
),
body: Center(
child: TextButton(
onPressed: () {
final now = DateFormat('kk:mm:ss').format(DateTime.now());
ScaffoldMessenger.of(context).removeCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
behavior: SnackBarBehavior.floating,
elevation: 5.0,
backgroundColor:
Colors.blue[600]!.withOpacity(0.8).withAlpha(200),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
side: BorderSide(
color: Colors.black.withOpacity(0.4),
width: 3.0,
),
),
content: Text('Some text $now'),
),
);
},
child: Text('Show toast'),
),
),
);
}
}
Custom Tab Bar Using ToggleButtons in Flutter
class TabBarButton extends StatelessWidget {
final IconData icon;
final double size;
const TabBarButton({Key? key, required this.icon, this.size = 60.0})
: super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(
icon,
size: size,
),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Toggle Buttons'),
),
body: Column(
children: [
CustomTabBar(),
],
),
);
}
}
class CustomTabBar extends StatefulWidget {
const CustomTabBar({Key? key}) : super(key: key);
@override
_CustomTabBarState createState() => _CustomTabBarState();
}
class _CustomTabBarState extends State<CustomTabBar> {
var _selection = [false, false, false];
@override
Widget build(BuildContext context) {
return Expanded(
child: Align(
alignment: FractionalOffset.bottomCenter,
child: SafeArea(
child: ToggleButtons(
isSelected: _selection,
onPressed: (index) {
setState(() {
_selection = List.generate(
_selection.length,
(i) => index == i ? true : false,
);
});
},
selectedColor: Colors.white,
fillColor: Colors.blue,
borderRadius: BorderRadius.circular(10.0),
borderWidth: 4.0,
borderColor: Colors.blue[400],
selectedBorderColor: Colors.blue,
highlightColor: Colors.blue.withOpacity(0.2),
children: [
TabBarButton(icon: Icons.settings),
TabBarButton(icon: Icons.add),
TabBarButton(icon: Icons.settings_remote)
],
),
),
),
);
}
}
Hashable Mixins in Dart
enum PetType { cat, dog }
mixin Pet {
String get name;
int get age;
PetType get type;
@override
String toString() => 'Pet ($type), name = $name, age = $age';
@override
int get hashCode => hashValues(name, age, type);
@override
bool operator ==(covariant Pet o) => o.hashCode == hashCode;
}
class Cat with Pet {
@override
final String name;
@override
final int age;
@override
final PetType type;
const Cat({required this.name, required this.age}) : type = PetType.cat;
}
void testIt() {
final cats = <Cat>{
Cat(name: 'Kitty 1', age: 2),
Cat(name: 'Kitty 2', age: 3),
Cat(name: 'Kitty 1', age: 2),
};
cats.forEach(print);
/* 👆🏻 prints the following:
Pet (PetType.cat), name = Kitty 1, age = 2
Pet (PetType.cat), name = Kitty 2, age = 3
*/
}
Flutter Tips and Tricks in Terminal
import 'dart:convert' show utf8;
import 'dart:io' show HttpClient, exit, Process, stderr;
import 'dart:math' show Random;
const rawBlobRoot =
'https://raw.githubusercontent.com/vandadnp/flutter-tips-and-tricks/main/';
void main(List<String> args) async {
final url = Uri.https('bit.ly', '/2V1GKsC');
try {
final client = HttpClient();
final images = await client
.getUrl(url)
.then((req) => req.close())
.then((resp) => resp.transform(utf8.decoder).join())
.then((body) => body.split('\n').map((e) => e.trim()))
.then((iter) => iter.toList())
.then((list) => list..retainWhere((s) => s.endsWith('.jpg)')))
.then((imageList) => imageList.map((e) => e.replaceAll('))
.then((imageList) => imageList.map((e) => e.replaceAll(')', '')))
.then((iter) => iter.toList());
final found = images[Random().nextInt(images.length)];
final result = '$rawBlobRoot$found';
await Process.run('open', [result]);
exit(0);
} catch (e) {
stderr.writeln('Could not proceed due to $e');
exit(1);
}
}
Searching List<List<T>>
in Dart
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [7, 8, 9];
const arr = [arr1, arr2, arr3];
extension FlattenFind<T extends Comparable> on Iterable<Iterable<T>> {
bool containsElement(T value) {
for (final arr in this) {
if (arr.contains(value)) {
return true;
}
}
return false;
}
}
void testIt() {
assert(arr.containsElement(2));
assert(arr.containsElement(8));
assert(!arr.containsElement(10));
assert(!arr.containsElement(10));
}
Cloning Objects in Dart
class Person {
final Map<String, Object> _values;
static const FIRST_NAME_KEY = 'FIRST_NAME';
static const LAST_NAME_KEY = 'LAST_NAME';
Person.from(Map<String, Object> props) : _values = props;
Person({
required String firstName,
required String lastName,
Map<String, Object>? props,
}) : _values = {
FIRST_NAME_KEY: firstName,
LAST_NAME_KEY: lastName,
};
@override
bool operator ==(covariant Person other) =>
other.firstName == firstName && other.lastName == lastName;
@override
String toString() => _values.toString();
}
extension Properties on Person {
String get firstName => _values[Person.FIRST_NAME_KEY].toString();
set firstName(String newValue) => _values[Person.FIRST_NAME_KEY] = newValue;
String get lastName => _values[Person.LAST_NAME_KEY].toString();
set lastName(String newValue) => _values[Person.LAST_NAME_KEY] = newValue;
}
extension Clone on Person {
Person clone([Map<String, Object>? additionalProps]) =>
Person.from(Map.from(_values)..addAll(additionalProps ?? {}));
}
extension Subscripts on Person {
Object? operator [](String key) => _values[key];
operator []=(String key, Object value) => _values[key] = value;
}
void testIt() {
final foo = Person(
firstName: 'Foo Firstname',
lastName: 'Foo Lastname',
);
print(foo); // {FIRST_NAME: Foo Firstname, LAST_NAME: Foo Lastname}
final copyOfFoo = foo.clone();
print(copyOfFoo); // {FIRST_NAME: Foo Firstname, LAST_NAME: Foo Lastname}
final bar = foo.clone({'age': 30});
print(bar); // {FIRST_NAME: Foo Firstname, LAST_NAME: Foo Lastname, age: 30}
assert(foo == copyOfFoo);
assert(foo == bar);
assert(foo['age'] == null);
assert(copyOfFoo['age'] == null);
assert(bar['age'] == 30);
}
Color Filters in Flutter
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var sliderValue = 0.0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Color Filters in Flutter!'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ColorFiltered(
colorFilter: ColorFilter.mode(
Colors.orange.withOpacity(sliderValue),
BlendMode.colorBurn,
),
child: Image.network('https://tinyurl.com/4vtvh35h'),
),
Slider(
value: sliderValue,
onChanged: (value) {
setState(() {
sliderValue = value;
});
},
)
],
),
);
}
}
Flattening Lists in Dart
class Person {
final String name;
const Person(this.name);
@override
String toString() => 'Person: $name';
}
class House {
final List<Person>? tennants;
final List<Person> builders;
const House({
required this.tennants,
required this.builders,
});
}
const houses = [
House(tennants: null, builders: [
Person('Builder 1'),
]),
House(tennants: [
Person('Tennant 1'),
Person('Tennant 2'),
], builders: [
Person('Builder 3')
]),
];
extension OptionalFlattend<T> on Iterable<List<T>?> {
Iterable<T> flattened() => expand((e) => e ?? []);
}
void testOptionalFlatten() {
final allTennants = houses.map((h) => h.tennants).flattened();
print(allTennants); // Person: Tennant 1, Person: Tennant 2
}
extension Flattend<T> on Iterable<List<T>> {
Iterable<T> flattened() => expand((e) => e);
}
void testNonOptionalFlatten() {
final allBuilders = houses.map((h) => h.builders).flattened();
print(allBuilders); // Person: Builder 1, Person: Builder 2
}
void testIt() {
testOptionalFlatten();
testNonOptionalFlatten();
}
Managing Duplicates in List<T>
in Dart
extension Duplicates<T> on List<T> {
void addAllByAvoidingDuplicates(Iterable<T> values) =>
replaceRange(0, length, {
...([...this] + [...values])
});
int get numberOfDuplicates => length - {...this}.length;
bool get containsDuplicates => numberOfDuplicates > 0;
List<T> get uniques => [
...{...this}
];
void removeDuplicates() => replaceRange(
0,
length,
uniques,
);
List<T> get duplicates => [
for (var i = 0; i < length; i++)
[...this].skip(i + 1).contains(this[i]) ? this[i] : null
].whereType<T>().toList();
}
void testIt() {
final values = [3, 2, 10, 30, 40, 30, 100, 10];
assert(values.numberOfDuplicates == 2);
assert(values.containsDuplicates == true);
assert(values.uniques.length == values.length - 2);
print(values.uniques); // [3, 2, 10, 30, 40, 100]
values.removeDuplicates();
print(values); // [3, 2, 10, 30, 40, 100]
assert(values.numberOfDuplicates == 0);
assert(!values.containsDuplicates);
assert(values.duplicates.isEmpty);
values.addAllByAvoidingDuplicates([3, 2, 10, 200]);
print(values); // [3, 2, 10, 30, 40, 100, 200]
assert(values.containsDuplicates == false);
}
FlatMap and CompactMap in Dart
extension CompactMap<T> on List<T> {
List<E> compactMap<E>(E? Function(T element) f) {
Iterable<E> imp(E? Function(T element) f) sync* {
for (final value in this) {
final mapped = f(value);
if (mapped != null) {
yield mapped;
}
}
}
return imp(f).toList();
}
}
extension FlatMap<T> on T? {
E? flatMap<E>(E? Function(T value) f) {
if (this != null) {
return f(this!);
} else {
return null;
}
}
}
void testIt() {
final foo = [1, 2, null, 3, null, 4];
final bar = foo.compactMap((element) => element.flatMap((e) => e * 2));
print(bar); // prints 2, 4, 6, 8
}
Equality of List<T>
in Dart
extension Equality<T extends Comparable> on List<T> {
bool isEqualTo(List<T> other) {
if (other.length != length) {
return false;
}
for (var i = 0; i < length; i++) {
if (other[i] != this[i]) {
return false;
}
}
return true;
}
}
int ascendingComparator<T extends Comparable>(T lhs, T rhs) =>
lhs.compareTo(rhs);
int descendingComparator<T extends Comparable>(T lhs, T rhs) =>
rhs.compareTo(lhs);
extension Sorted<T extends Comparable> on List<T> {
List<T> sorted({bool descending = false}) => descending
? ([...this]..sort(descendingComparator))
: ([...this]..sort(ascendingComparator));
}
void testIt() {
assert([1, 2, 3].isEqualTo([1, 2, 3]));
assert(![1, 2, 3].isEqualTo([1, 2, 2]));
assert([3, 1, 2].sorted().isEqualTo([1, 2, 3]));
assert(![3, 1, 2].sorted().isEqualTo([3, 1, 2]));
assert(['Foo', 'Bar', 'Baz'].isEqualTo(['Foo', 'Bar', 'Baz']));
assert(!['Foo', 'Bar', 'Baz'].isEqualTo(['foo', 'Bar', 'Baz']));
}
Constants in Dart
class Person {
final String name;
final int age;
const Person({required this.name, required this.age});
}
const foo = Person(name: 'Foo', age: 20);
const foo2 = Person(name: 'Foo', age: 20);
const bar = Person(name: 'Bar', age: 20);
void assert_eq(Object lhs, Object rhs) {
assert(lhs == rhs);
}
void assert_ne(Object lhs, Object rhs) {
assert(lhs != rhs);
}
void testIt() {
assert_eq(foo, foo2);
assert_ne(foo, bar);
assert_ne(foo2, bar);
}
Displaying Scrollable Bottom Sheets in Flutter
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Scrollable Sheet')),
body: DraggableScrollableSheet(
initialChildSize: 0.2,
minChildSize: 0.2,
maxChildSize: 0.8,
builder: (context, scrollController) {
return Container(
decoration: decoration(),
clipBehavior: Clip.antiAlias,
child: SingleChildScrollView(
controller: scrollController,
child: column(),
),
);
},
),
);
}
}
const urls = [
'https://tinyurl.com/4vtvh35h',
'https://tinyurl.com/pujhs55w',
'https://tinyurl.com/u5k7zueh',
];
List<Widget> imageWithLoremIpsum(String uri) => [
Image.network(uri),
SizedBox(height: 10),
loremIpsum(),
SizedBox(height: 10),
];
Column column() => Column(
children: imageWithLoremIpsum(urls[0]) +
imageWithLoremIpsum(urls[1]) +
imageWithLoremIpsum(urls[2]),
);
Text loremIpsum() => Text(
'Lorem ipsum ' * 10,
textAlign: TextAlign.center,
);
BoxDecoration decoration() => BoxDecoration(
border: Border.all(color: Colors.white),
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
),
color: Colors.white70,
);
YouTube Ad Remover in Dart
import 'dart:io' show stdout, stderr, exitCode;
import 'package:collection/collection.dart' show IterableExtension;
// example argument: https://www.youtube.com/watch?v=mtETXtSP0pA
void main(List<String> args) async {
if (args.isEmpty) {
stdout.writeln('usage: dart youtube.dart "https://..."');
return;
}
final link =
args.firstWhereOrNull((element) => Uri.tryParse(element) != null);
if (link == null) {
stderr.writeln('No YouTube url found');
exitCode = 1;
return;
}
try {
final uri = Uri.parse(link);
if (uri.scheme.toLowerCase() != 'https' ||
uri.host.toLowerCase() != 'www.youtube.com' ||
uri.queryParameters['v'] == null) {
throw FormatException();
} else {
final videoId = uri.queryParameters['v'];
final embedUri = Uri.parse('${uri.scheme}://${uri.host}/embed/$videoId');
stdout.writeln(embedUri);
exitCode = 0;
}
} on FormatException catch (e) {
stderr.writeln('Invalid Uri, try again! err = $e');
exitCode = 1;
return;
}
}
Fade Between Widgets in Flutter
const urls = [
'https://bit.ly/3qYOtDm',
'https://bit.ly/3wt11Ec',
];
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var isShowingFirstImage = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('AnimatedCrossFade in Flutter'),
),
body: Center(
child: AnimatedCrossFade(
layoutBuilder: (topChild, topChildKey, bottomChild, bottomChildKey) {
return GestureDetector(
onTap: () {
setState(() {
isShowingFirstImage = !isShowingFirstImage;
});
},
child: AnimatedCrossFade.defaultLayoutBuilder(
topChild, topChildKey, bottomChild, bottomChildKey),
);
},
firstChild: Image.network(urls[0]),
secondChild: Image.network(urls[1]),
crossFadeState: isShowingFirstImage
? CrossFadeState.showFirst
: CrossFadeState.showSecond,
duration: Duration(milliseconds: 400),
),
),
);
}
}
Sort Descriptors in Dart
int ascendingComparator<T extends Comparable>(T lhs, T rhs) =>
lhs.compareTo(rhs);
int descendingComparator<T extends Comparable>(T lhs, T rhs) =>
rhs.compareTo(lhs);
extension Sorted<T extends Comparable> on List<T> {
List<T> sorted({bool descending = false}) => descending
? (this..sort(descendingComparator))
: (this..sort(ascendingComparator));
}
class Person implements Comparable {
final int age;
final String name;
const Person({required this.age, required this.name});
@override
int compareTo(covariant Person other) => age.compareTo(other.age);
@override
String toString() => 'Person, name = $name ($age)';
}
void testIt() {
final people = [
Person(age: 39, name: 'Father Foo'),
Person(age: 40, name: 'Mother Bar'),
Person(age: 13, name: 'Son Baz'),
];
print('ascending sort');
people.sorted().forEach(print);
// prints Son Baz (13), Father Foo (39), Mother Bar (40)
print('descending sort');
people.sorted(descending: true).forEach(print);
// prints Mother Bar (40), Father Foo (39), Son Baz (13)
}
User Sortable Columns and Tables in Flutter
class Language {
final String name;
final Image image;
const Language(this.name, this.image);
Language.dart()
: name = 'Dart',
image = Image.network('https://bit.ly/3yH1Ivj');
Language.rust()
: name = 'Rust',
image = Image.network('https://bit.ly/3lPTqhb');
Language.python()
: name = 'Python',
image = Image.network('https://bit.ly/3iCFCEP');
Language.java()
: name = 'Java',
image = Image.network('https://bit.ly/3CCapJH');
static List<Language> all = [
Language.dart(),
Language.rust(),
Language.python(),
Language.java(),
];
}
extension Sort on List<Language> {
void sortByName(bool ascending) => sort((lhs, rhs) =>
ascending ? lhs.name.compareTo(rhs.name) : rhs.name.compareTo(lhs.name));
}
List<DataRow> rows(List<Language> langs) => langs
.map(
(l) => DataRow(
cells: [
DataCell(
Padding(
padding: const EdgeInsets.all(8.0),
child: l.image,
),
),
DataCell(Text(l.name)),
],
),
)
.toList();
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final List<Language> _langs = Language.all..sortByName(true);
int sortedColumnIndex = 1;
var isSortedAscending = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('WhatsApp')),
body: DataTable(
sortAscending: isSortedAscending,
sortColumnIndex: sortedColumnIndex,
columns: [
DataColumn(label: Text('Image')),
DataColumn(
label: Text('Name'),
onSort: (columnIndex, ascending) {
setState(() {
sortedColumnIndex = columnIndex;
isSortedAscending = ascending;
_langs.sortByName(ascending);
});
},
),
],
rows: rows(_langs),
),
);
}
}
Content-Length of List<Uri>
in Dart
Recursive Dot Notation on Maps in Dart
final person = {
'firstName': 'Foo',
'lastName': 'Bar',
'age': 30,
'address': {
'street': {
'name': 'Baz street',
'numberOfHouses': 20,
},
'houseNumber': '#20',
'city': 'Stockholm',
'country': 'Sweden'
},
};
extension KeyPath on Map {
Object? valueFor({required String keyPath}) {
final keysSplit = keyPath.split('.');
final thisKey = keysSplit.removeAt(0);
final thisValue = this[thisKey];
if (keysSplit.isEmpty) {
return thisValue;
} else if (thisValue is Map) {
return thisValue.valueFor(keyPath: keysSplit.join('.'));
}
}
}
void testIt() {
assert(person.valueFor(keyPath: 'firstName') == 'Foo');
assert(person.valueFor(keyPath: 'age') == 30);
assert(person.valueFor(keyPath: 'address.street.name') == 'Baz street');
assert(person.valueFor(keyPath: 'address.houseNumber') == '#20');
}
Allow User Selection of Text in Flutter
const text = 'Flutter is an open-source UI software development'
' kit created by Google. It is used to develop cross platform applications'
' for Android, iOS, Linux, Mac, Windows, Google Fuchsia, '
'and the web from a single codebase.';
const imageUrl = 'https://bit.ly/3gT5Qk2';
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Selectable Text in Flutter'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.network(imageUrl),
SizedBox(height: 10.0),
Padding(
padding: const EdgeInsets.all(8.0),
child: SelectableText(
text,
textAlign: TextAlign.center,
showCursor: true,
cursorColor: Colors.blue,
toolbarOptions: ToolbarOptions(
copy: true,
selectAll: true,
),
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w300,
),
),
),
],
),
);
}
}
Placing Constraints on Widgets in Flutter
const dashes = [
'https://bit.ly/3gHlTCU',
'https://bit.ly/3wOLO1c',
'https://bit.ly/3cXWD9j',
'https://bit.ly/3gT5Qk2',
];
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ConstrainedBox in Flutter'),
),
body: InteractiveViewer(
minScale: 1.0,
maxScale: 2.0,
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Table(
defaultVerticalAlignment: TableCellVerticalAlignment.middle,
children: dashes
.map(
(dash) => TableRow(
children: [
ConstrainedBox(
constraints: BoxConstraints(
minHeight: 300,
),
child: Image.network(dash),
),
],
),
)
.toList(),
),
),
),
);
}
}
Animating Position Changes in Flutter
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var isMovedUp = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('AnimatedPositioned in Flutter')),
body: Center(
child: GestureDetector(
onTap: () => setState(() => isMovedUp = !isMovedUp),
child: Stack(
clipBehavior: Clip.none,
alignment: Alignment.center,
children: [
Image.network('https://bit.ly/2VcCSow'),
Text(
'Summer 😎',
style: TextStyle(
fontSize: 30,
color: Colors.black,
),
),
AnimatedPositioned(
duration: Duration(seconds: 1),
bottom: isMovedUp ? 140 : 10.0,
curve: Curves.elasticInOut,
child: CircleAvatar(
radius: 100,
backgroundImage: NetworkImage('https://bit.ly/3cXWD9j'),
backgroundColor: Colors.orange[300],
),
),
],
),
),
),
);
}
}
Transitioning Between Widgets in Flutter
enum Season { spring, summer, autumn, winter }
extension Caps on String {
String get capitalized => this[0].toUpperCase() + substring(1);
}
extension Title on Season {
String get title => describeEnum(this).capitalized;
}
class TitledImage {
final String title;
final Uri uri;
final ValueKey key;
const TitledImage(this.title, this.uri, this.key);
TitledImage.spring()
: title = Season.spring.title,
uri = Uri.https('cnn.it', '/3xu58Ap'),
key = ValueKey(1);
TitledImage.summer()
: title = Season.summer.title,
uri = Uri.https('bit.ly', '/2VcCSow'),
key = ValueKey(2);
TitledImage.autumn()
: title = Season.autumn.title,
uri = Uri.https('bit.ly', '/3A3zStC'),
key = ValueKey(3);
TitledImage.winter()
: title = Season.winter.title,
uri = Uri.https('bit.ly', '/2TNY7wi'),
key = ValueKey(4);
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var _img = TitledImage.summer();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(_img.title)),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedSwitcher(
switchInCurve: Curves.easeIn,
switchOutCurve: Curves.easeOut,
duration: Duration(milliseconds: 300),
transitionBuilder: (child, animation) {
return FadeTransition(opacity: animation, child: child);
},
child: Image.network(
_img.uri.toString(),
key: _img.key,
),
),
getButtons(),
],
),
);
}
Widget getButtons() {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextButton(
onPressed: () => setState(() => _img = TitledImage.spring()),
child: Text(Season.spring.title),
),
TextButton(
onPressed: () => setState(() => _img = TitledImage.summer()),
child: Text(Season.summer.title),
),
TextButton(
onPressed: () => setState(() => _img = TitledImage.autumn()),
child: Text(Season.autumn.title),
),
TextButton(
onPressed: () => setState(() => _img = TitledImage.winter()),
child: Text(Season.winter.title),
),
],
);
}
}
Doubly Linked Lists in Dart
class Person extends LinkedListEntry<Person> {
final String name;
final int age;
Person({
required this.name,
required this.age,
});
@override
String toString() => 'Person name = $name, age = $age';
}
void testIt() {
final persons = LinkedList<Person>();
final dad = Person(name: 'Father Foo', age: 47);
final mom = Person(name: 'Mother Bar', age: 47);
final daughter = Person(name: 'Daughter Baz', age: 22);
persons.addAll([dad, mom, daughter]);
print(persons.first.previous); // null
print(persons.first); // Person name = Father Foo, age = 47
print(persons.first.next); // Person name = Mother Bar, age = 47
print(persons.last.previous); // Person name = Mother Bar, age = 47
print(persons.first.next?.next); // Person name = Daughter Baz, age = 22
print(persons.last.next); // null
}
Reordering Items Inside List Views in Flutter
class Item {
final Color color;
final String text;
final UniqueKey uniqueKey;
Item(this.color, this.text) : uniqueKey = UniqueKey();
}
extension ToListItem on Item {
Widget toListItem() => LimitedBox(
key: uniqueKey,
maxHeight: 200,
child: Container(
color: color,
child: Padding(
padding: const EdgeInsets.all(20),
child: Text(
text,
style: TextStyle(
color: Colors.white,
fontSize: 100,
),
),
),
),
);
}
class _HomePageState extends State<HomePage> {
var items = [
Item(Colors.deepPurple, 'Foo'),
Item(Colors.blueGrey, 'Bar'),
Item(Colors.lightGreen, 'Baz')
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Reordered List View in Flutter'),
),
body: ReorderableListView(
onReorder: (oldIndex, newIndex) {
setState(() {
final item = items.removeAt(oldIndex);
items.insert(newIndex, item);
});
},
children: items.map((i) => i.toListItem()).toList(),
),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
Custom Stream Transformers in Dart
in this example we have created our own string transformer that
can trim a Stream<String> by trimming whitespace from both
beginning and end of the string
*/
import 'dart:convert' show utf8;
class StringTrimmer extends StreamTransformerBase<String, String> {
const StringTrimmer();
@override
Stream<String> bind(Stream<String> stream) =>
Stream.fromFuture(stream.join(' ')).map((str) => str.trim());
}
final string =
''' A long line of text with spaces in the beginning and the end,
divided into three lines just for the purpose of this demonstration ''';
void testIt() async {
final bytes = utf8.encode(string);
final result = await Stream.value(bytes)
.transform(utf8.decoder)
.transform(LineSplitter())
.transform(StringTrimmer())
.join();
print(result);
}
Expanding Stream Elements in Dart
/*
in this example we expand every element inside our Stream<int> to
a stream that in turn contains n+1 elements where n is the index generated
by our main stream, that's to say, 0, 1, 2, 3, 4, etc
*/
Stream<int> nestedEvents(int count) {
return Stream.periodic(
Duration(seconds: 1),
(e) => e,
).take(count).asyncExpand(
(i) => Stream.fromIterable(
Iterable.generate(i + 1),
),
);
}
void testIt() async {
/*
prints the followings in this order
0, 1
0, 1, 2
0, 1, 2, 3
0, 1, 2, 3, 4
*/
await for (final value in nestedEvents(5)) {
print('Value is $value');
}
}
Consume Streams for a Duration in Dart
extension TakeFor<T> on Stream<T> {
Stream<T> takeFor(Duration duration) {
final upTo = DateTime.now().add(duration);
return takeWhile((_) {
final now = DateTime.now();
return now.isBefore(upTo) | now.isAtSameMomentAs(upTo);
});
}
}
Stream<DateTime> source() => Stream.periodic(
Duration(milliseconds: 500),
(_) => DateTime.now(),
);
void testIt() async {
await for (final dateTime in source().takeFor(
Duration(seconds: 4),
)) {
print('date time is $dateTime');
}
}
Shortening URLs in Dart
import 'dart:convert' show json;
Future<Uri> shortenUri(Uri uri, String bitlyToken) async {
final client = HttpClient();
final endpoint = Uri.https('api-ssl.bitly.com', '/v4/shorten');
final response = await client.postUrl(endpoint).then(
(req) {
req.headers
..set(HttpHeaders.contentTypeHeader, 'application/json')
..set(HttpHeaders.authorizationHeader, 'Bearer $bitlyToken');
final body = {
'long_url': uri.toString(),
'domain': 'bit.ly',
};
final bodyBytes = utf8.encode(json.encode(body));
req.add(bodyBytes);
return req.close();
},
);
final responseBody = await response.transform(utf8.decoder).join();
final responseJson = json.decode(responseBody) as Map<String, dynamic>;
return Uri.parse(responseJson['link']);
}
void testIt() async {
print(await shortenUri(
Uri.parse('https://pixolity.se'),
'XXX',
));
}
LimitedBox Widget as ListView Items in Flutter
const images = [
'https://bit.ly/3x7J5Qt',
'https://bit.ly/3ywI8l6',
'https://bit.ly/3jRSRCu',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3qYOtDm',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3yvFg7X',
'https://bit.ly/3ywzOla',
'https://bit.ly/3wnASpW',
'https://bit.ly/3jXSDto',
];
extension ToListItemImage on String {
Widget toListItemImage() {
return LimitedBox(
maxHeight: 150.0,
child: Image.network(
this,
fit: BoxFit.fitWidth,
),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Limited Box in Flutter')),
body: ListView(
children: images.map((str) => str.toListItemImage()).toList(),
),
);
}
}
Generically Convert Anything to Int in Dart
extension ToInt on Object {
int toInt() {
final list = [
if (this is Iterable<Object>)
...(List.of(this as Iterable<Object>))
else if (this is int)
[this as int]
else
(double.tryParse(toString()) ?? 0.0).round()
];
return list
.map((e) => (double.tryParse(e.toString()) ?? 0.0).round())
.reduce((lhs, rhs) => lhs + rhs);
}
}
void testIt() {
assert(1.toInt() == 1);
assert((2.2).toInt() == 2);
assert((2.0).toInt() == 2);
assert('3'.toInt() == 3);
assert(['4', '5'].toInt() == 9);
assert([4, 5].toInt() == 9);
assert(['2.4', '3.5'].toInt() == 6);
assert(['2', '3.5'].toInt() == 6);
assert({'2', 3, '4.2'}.toInt() == 9);
assert(['2', 3, '4.2', 5.3].toInt() == 14);
}
Validating URL Certificates in Dart
import 'dart:io' show HttpClient;
Future<bool> isSecuredWithValidCert(String uriString) async {
final uri = Uri.parse(uriString);
final client = HttpClient();
try {
await client.headUrl(uri).then((r) => r.close());
return true;
} on HandshakeException {
return false;
}
}
void testIt() async {
await isSecuredWithValidCert('https://expired.badssl.com');
await isSecuredWithValidCert('https://wrong.host.badssl.com');
await isSecuredWithValidCert('https://self-signed.badssl.com');
await isSecuredWithValidCert('https://untrusted-root.badssl.com');
await isSecuredWithValidCert('https://revoked.badssl.com');
}
Displaying Popup Menus in Flutter
enum ImageAction { copy }
PopupMenuItem<ImageAction> copyButton({VoidCallback? onPressed}) =>
PopupMenuItem<ImageAction>(
value: ImageAction.copy,
child: TextButton.icon(
icon: Icon(Icons.copy),
label: Text('Copy'),
onPressed: onPressed,
),
);
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter'),
),
body: Center(
child: PopupMenuButton<ImageAction>(
elevation: 10,
offset: Offset(0, 50),
itemBuilder: (_) => [
copyButton(
onPressed: () {
print('Copy the image...');
},
),
],
child: Image.network('https://bit.ly/3ywI8l6'),
),
),
);
}
}
Implementing Drag and Drop in Flutter
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String? _imageUrl;
bool shouldAccept(String? value) => Uri.tryParse(value ?? '') != null;
Widget dragTargetBuilder(
BuildContext context,
List<String?> incoming,
dynamic rejected,
) {
final emptyContainer = Container(
color: Colors.grey[200],
height: 200,
child: Center(
child: Text('Drag an image here'),
),
);
if (incoming.isNotEmpty) {
_imageUrl = incoming.first;
}
if (_imageUrl == null) {
return emptyContainer;
}
try {
final uri = Uri.parse(_imageUrl ?? '');
return Container(
color: Colors.grey[200],
height: 200,
child: Center(
child: Image.network(uri.toString()),
),
);
} on FormatException {
return emptyContainer;
}
}
static final firstImageUrl = 'https://bit.ly/3xnoJTm';
static final secondImageUrl = 'https://bit.ly/3hIuC78';
final firstImage = Image.network(firstImageUrl);
final secondImage = Image.network(secondImageUrl);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Tooltips in Flutter')),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
DragTarget<String>(
onWillAccept: shouldAccept,
builder: dragTargetBuilder,
),
SizedBox(height: 10.0),
DraggableImage(
imageWidget: firstImage,
imageUrl: firstImageUrl,
),
SizedBox(height: 10.0),
DraggableImage(
imageWidget: secondImage,
imageUrl: secondImageUrl,
),
],
),
),
);
}
}
class DraggableImage extends StatelessWidget {
const DraggableImage({
Key? key,
required this.imageWidget,
required this.imageUrl,
}) : super(key: key);
final Image imageWidget;
final String imageUrl;
@override
Widget build(BuildContext context) {
return Draggable<String>(
data: imageUrl,
feedback: Container(
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
blurRadius: 30,
color: Colors.black,
spreadRadius: 10,
),
],
),
child: imageWidget,
),
child: imageWidget,
);
}
}
Dismissing List Items in Flutter
const gridImages = [
'https://bit.ly/3x7J5Qt',
'https://bit.ly/3dLJNeD',
'https://bit.ly/3ywI8l6',
'https://bit.ly/3jRSRCu',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3qYOtDm',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3yvFg7X',
'https://bit.ly/3ywzOla',
'https://bit.ly/3wnASpW',
'https://bit.ly/3jXSDto',
];
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(),
CustomGridView(),
CustomListView(
imageUrls: gridImages,
),
],
),
);
}
}
class _CustomListViewState extends State<CustomListView> {
@override
Widget build(BuildContext context) {
return SliverPadding(
padding: EdgeInsets.all(8.0),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final url = widget.imageUrls[index];
return Dismissible(
key: ValueKey(url),
onDismissed: (_) {
widget.imageUrls.remove(url);
},
background: Container(
color: Colors.red,
child: FittedBox(
alignment: Alignment.centerRight,
fit: BoxFit.fitHeight,
child: Icon(Icons.delete, color: Colors.white),
),
),
child: Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: Image.network(url),
),
);
},
childCount: widget.imageUrls.length,
),
),
);
}
}
class CustomListView extends StatefulWidget {
final List<String> imageUrls;
const CustomListView({
Key? key,
required this.imageUrls,
}) : super(key: key);
@override
_CustomListViewState createState() => _CustomListViewState();
}
class CustomGridView extends StatelessWidget {
const CustomGridView({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return SliverPadding(
padding: EdgeInsets.all(8.0),
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
childAspectRatio: 1.0,
),
delegate: SliverChildBuilderDelegate(
(context, index) {
return Container(
width: 100,
height: 100,
child: Image.network(gridImages[index]),
);
},
childCount: gridImages.length,
),
),
);
}
}
class CustomAppBar extends StatelessWidget {
const CustomAppBar({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return SliverAppBar(
backgroundColor: Colors.orange[300],
forceElevated: true,
pinned: false,
snap: false,
floating: true,
expandedHeight: 172,
flexibleSpace: FlexibleSpaceBar(
title: Text(
'Flutter',
style: TextStyle(
fontSize: 30,
color: Colors.white,
decoration: TextDecoration.underline,
),
),
collapseMode: CollapseMode.parallax,
background: Image.network('https://bit.ly/3x7J5Qt'),
),
);
}
}
Animating Widgets with Ease in Flutter
class Ball extends StatefulWidget {
const Ball({Key? key}) : super(key: key);
@override
_BallState createState() => _BallState();
}
class _BallState extends State<Ball> with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 4),
reverseDuration: Duration(seconds: 4),
);
_animation = Tween(begin: 0.0, end: 2 * pi).animate(_controller);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
_controller.repeat();
return AnimatedBuilder(
animation: _animation,
builder: (context, image) {
return Transform.rotate(
angle: _animation.value,
child: image,
);
},
child: Image.network('https://bit.ly/3xspdrp'),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Animated Builder in Flutter'),
),
body: Center(
child: Ball(),
),
);
}
}
Displaying Tool Tips in Flutter
const imagesAndInfo = [
['https://bit.ly/3xnoJTm', 'Stockholm, Sweden'],
['https://bit.ly/3hIuC78', 'Dalarna, Sweden'],
['https://bit.ly/3wi9mdG', 'Brighton, UK'],
['https://bit.ly/3dSSMuy', 'Hove, UK'],
['https://bit.ly/3xoWCmV', 'Kerala, India'],
['https://bit.ly/3hGmjZC', 'Salvador da Bahia, Brazil']
];
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Tooltips in Flutter')),
body: ListView.builder(
itemCount: imagesAndInfo.length,
itemBuilder: (_, index) {
return Padding(
padding: const EdgeInsets.only(top: 8.0, left: 8.0, right: 8.0),
child: Tooltip(
decoration: BoxDecoration(
color: Colors.black,
boxShadow: [
BoxShadow(
color: Colors.white.withAlpha(180),
offset: Offset.zero,
spreadRadius: 30.0,
blurRadius: 30.0,
),
],
borderRadius: BorderRadius.all(Radius.circular(8.0)),
),
textStyle: TextStyle(fontSize: 20, color: Colors.white),
message: imagesAndInfo[index][1],
child: Image.network(
imagesAndInfo[index][0],
),
),
);
},
),
);
}
}
Displaying Assorted Widgets Inside TableView in Flutter
const natureUrls = [
'https://bit.ly/3dAtFwy',
'https://bit.ly/36cHehe',
'https://bit.ly/365uqt1',
'https://bit.ly/3x7J5Qt',
'https://bit.ly/3jBvJYU',
'https://bit.ly/3yhbHHi'
];
extension ToImage on String {
Widget toPaddedNetworkImage() => Padding(
padding: const EdgeInsets.all(8.0),
child: Image.network(this),
);
}
extension ToImages on List<String> {
List<Widget> toPaddedNetworkImages() =>
map((str) => str.toPaddedNetworkImage()).toList();
}
extension ToTableRow on List<Widget> {
TableRow toTableRow() => TableRow(children: this);
}
class ListPaginator<T> extends Iterable {
final List<List<T>> list;
ListPaginator({required List<T> input, required int itemsPerPage})
: list = [
for (var i = 0; i < input.length; i += itemsPerPage)
input.getRange(i, min(input.length, i + itemsPerPage)).toList(),
];
@override
Iterator get iterator => list.iterator;
}
class HomePage extends StatelessWidget {
final provider = ListPaginator<String>(
input: natureUrls,
itemsPerPage: 3,
);
HomePage({Key? key}) : super(key: key);
Iterable<TableRow> getRows() sync* {
for (final List<String> urlBatch in provider) {
final networkImages = urlBatch.toPaddedNetworkImages();
yield TableRow(children: networkImages);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('TableView in Flutter'),
),
body: SingleChildScrollView(
child: Table(
defaultVerticalAlignment: TableCellVerticalAlignment.bottom,
children: getRows().toList(),
),
),
);
}
}
Page Indicator with Page View in Flutter
const dashes = [
'https://bit.ly/3gHlTCU',
'https://bit.ly/3wOLO1c',
'https://bit.ly/3cXWD9j',
'https://bit.ly/3gT5Qk2',
];
class PageText extends StatelessWidget {
final int current;
final int total;
const PageText({
Key? key,
required this.current,
required this.total,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(
'Page ${current + 1} of $total',
style: TextStyle(fontSize: 30.0, shadows: [
Shadow(
offset: Offset(0.0, 1.0),
blurRadius: 20.0,
color: Colors.black.withAlpha(140),
)
]),
);
}
}
class _HomePageState extends State<HomePage> {
var _index = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Page Indicator')),
body: SafeArea(
child: Column(
children: [
Expanded(
child: PageView.builder(
onPageChanged: (pageIndex) {
setState(() => _index = pageIndex);
},
scrollDirection: Axis.horizontal,
itemCount: dashes.length,
itemBuilder: (context, index) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.network(dashes[index]),
Text('Dash #${index + 1}'),
],
);
},
),
),
PageText(current: _index, total: dashes.length)
],
),
),
);
}
}
Animating and Moving a Floating Action Button in Flutter
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
const List<FloatingActionButtonLocation> locations = [
FloatingActionButtonLocation.centerDocked,
FloatingActionButtonLocation.startDocked,
FloatingActionButtonLocation.startFloat,
FloatingActionButtonLocation.centerFloat,
FloatingActionButtonLocation.endFloat,
FloatingActionButtonLocation.endDocked
];
extension GoAround<T> on List<T> {
T elementByGoingAround(int index) {
final finalIndex = index >= length ? index.remainder(length) : index;
return this[finalIndex];
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var _locationIndex = 0;
FloatingActionButtonLocation get location =>
locations.elementByGoingAround(_locationIndex);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Floating Action Button'),
),
floatingActionButtonLocation: location,
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() => _locationIndex += 1);
},
child: Icon(Icons.add),
),
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.yellow[600],
selectedItemColor: Colors.black,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.bedtime),
label: 'Item 1',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarms),
label: 'Item 2',
)
],
currentIndex: 0,
),
);
}
}
Fading Network Image Widget in Flutter
class FadingNetworkImage extends StatefulWidget {
final String url;
const FadingNetworkImage({Key? key, required this.url}) : super(key: key);
@override
_FadingNetworkImageState createState() => _FadingNetworkImageState();
}
class _FadingNetworkImageState extends State<FadingNetworkImage>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _animation;
@override
void initState() {
super.initState();
_controller =
AnimationController(vsync: this, duration: Duration(seconds: 1));
_animation = Tween(begin: 0.0, end: 1.0).animate(_controller);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Image.network(
widget.url,
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
_controller.reset();
_controller.forward();
return FadeTransition(opacity: _animation, child: child);
},
loadingBuilder: (context, child, loadingProgress) {
final totalBytes = loadingProgress?.expectedTotalBytes;
final bytesLoaded = loadingProgress?.cumulativeBytesLoaded;
if (totalBytes != null && bytesLoaded != null) {
return LinearProgressIndicator(
value: bytesLoaded / totalBytes,
);
} else {
return child;
}
},
errorBuilder: (context, error, stackTrace) {
return Text('Error!');
},
);
}
}
const dashes = [
'https://bit.ly/3gHlTCU',
'https://bit.ly/3wOLO1c',
'https://bit.ly/3cXWD9j',
'https://bit.ly/3gT5Qk2',
];
extension GoAround<T> on List<T> {
T elementByGoingAround(int index) {
final finalIndex = index >= length ? index.remainder(length) : index;
return this[finalIndex];
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _index = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Faded Image'),
),
body: Center(
child: Column(
children: [
FadingNetworkImage(
url: dashes.elementByGoingAround(_index),
),
TextButton(
onPressed: () {
setState(() => _index += 1);
},
child: Text('Load next Dash'),
),
],
)),
);
}
}
Transparent Alert Dialogs in Flutter
TextStyle get whiteTextStyle => TextStyle(color: Colors.white);
Future<void> showTextDialog({
required BuildContext context,
required String text,
}) {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(10),
),
side: BorderSide(
color: Colors.white,
style: BorderStyle.solid,
width: 2,
),
),
backgroundColor: Colors.black.withAlpha(150),
titleTextStyle: whiteTextStyle,
contentTextStyle: whiteTextStyle,
content: Text(text),
actions: [
TextButton(
style: TextButton.styleFrom(primary: Colors.white),
onPressed: () {
Navigator.of(context).pop();
},
child: Text('OK'),
)
],
);
},
);
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'Rounded Corder Dialog',
),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.network('https://bit.ly/3ywI8l6'),
TextButton(
onPressed: () async {
await showTextDialog(
context: context,
text: 'Hello world',
);
},
child: Text('Show dialog'),
),
],
),
);
}
}
Network Image Size in Dart
import 'dart:ui' as ui;
Future<Size> getImageSize(String uri) {
final image = Image.network('https://bit.ly/3dAtFwy');
final comp = Completer<ui.Image>();
image.image
.resolve(
ImageConfiguration.empty,
)
.addListener(
ImageStreamListener(
(ImageInfo info, _) => comp.complete(info.image),
),
);
return comp.future.then(
(image) => Size(
image.width.toDouble(),
image.height.toDouble(),
),
);
}
void testIt() async {
final imageSize = await getImageSize('https://bit.ly/3dAtFwy');
print(imageSize);
assert(imageSize.width == 2048.0);
assert(imageSize.height == 1365.0);
print(imageSize.aspectRatio);
}
Animated Icons in Flutter
class _HomePageState extends State<HomePage>
with SingleTickerProviderStateMixin {
late final Animation<double> _animation;
late final AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 1),
);
_animation = Tween(
begin: 0.0,
end: 1.0,
).animate(_controller);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
_controller.repeat(reverse: true);
return Scaffold(
appBar: AppBar(
title: Text('Animated Icons in Fluter'),
),
body: Center(
child: AnimatedIcon(
color: Colors.green[300],
size: MediaQuery.of(context).size.width,
icon: AnimatedIcons.search_ellipsis,
progress: _animation,
),
),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
Custom Scroll Views in Flutter
const gridImages = [
'https://bit.ly/3x7J5Qt',
'https://bit.ly/3dLJNeD',
'https://bit.ly/3ywI8l6',
'https://bit.ly/3jRSRCu',
'https://bit.ly/36fNNj9',
'https://bit.ly/3jOueGG',
'https://bit.ly/3qYOtDm',
'https://bit.ly/3wt11Ec',
'https://bit.ly/3yvFg7X',
'https://bit.ly/3ywzOla',
'https://bit.ly/3wnASpW',
'https://bit.ly/3jXSDto',
];
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(),
CustomGridView(),
CustomListView(),
],
),
);
}
}
class CustomListView extends StatelessWidget {
const CustomListView({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return SliverPadding(
padding: EdgeInsets.all(8.0),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
return Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: Image.network(gridImages[index]),
);
},
childCount: gridImages.length,
),
),
);
}
}
class CustomGridView extends StatelessWidget {
const CustomGridView({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return SliverPadding(
padding: EdgeInsets.all(8.0),
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
childAspectRatio: 1.0,
),
delegate: SliverChildBuilderDelegate(
(context, index) {
return Container(
width: 100,
height: 100,
child: Image.network(gridImages[index]),
);
},
childCount: gridImages.length,
),
),
);
}
}
class CustomAppBar extends StatelessWidget {
const CustomAppBar({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return SliverAppBar(
backgroundColor: Colors.orange[300],
forceElevated: true,
pinned: false,
snap: false,
floating: true,
expandedHeight: 172,
flexibleSpace: FlexibleSpaceBar(
title: Text(
'Flutter',
style: TextStyle(
fontSize: 30,
color: Colors.white,
decoration: TextDecoration.underline,
),
),
collapseMode: CollapseMode.parallax,
background: Image.network('https://bit.ly/3x7J5Qt'),
),
);
}
}
Parallax App Bar in Flutter
JSON HTTP Requests in Dart
URL Timeouts in Dart
Detecting URL File Types in Dart
Paginated Lists in Dart
Requesting DELETE on APIs in Dart
Animated Containers in Flutter
Hiding Widgets in Flutter
Simple Opacity Animation in Flutter
Vignette Widget in Flutter
Drop Down Button Configuration and Usage in Flutter
Expandable List Items in Flutter
Infinite Scrolling in Flutter
Infinite Arrays in Dart
Custom Color Picker Component in Flutter
Displaying and Reacting to Switches in Flutter
Displaying Bottom Bars in Flutter
Displaying Buttons on AppBar in Flutter
Displaying Bottom Sheets in Flutter
Converting Enums to Radio Buttons in Flutter
Check Existence of Websites in Flutter
Images inside AlertDialog in Flutter
Returning Values from AlertDialog in Flutter
Simple Grid View in Flutter
Rendering Bullet Points in Flutter
Retrying Futures in Flutter
Containers as ClipOvals in Flutter
Rich Texts in Flutter
Wrapping Widgets in Flutter
Sweep Gradients in Flutter
Stream
and StreamBuilder
in Flutter
Blur Effect in Flutter
Convert Enums to Strings in Dart
Replacing Text in TextField in Flutter
Aspect Ratio in Flutter
Zoom and Pan in Flutter
Resizing Images in Flutter to Fit Screen Height
Validating URLs in Flutter
FrameBuilder for Network Images in Flutter
Adding Shadow to Icons in Flutter
Calculating Median of Lists in Dart
Generic Functions with Reduce in Dart
Passing Back Data From a Screen to the Previous One in Flutter
Flinging an Animation in Flutter
Fade Animations in Flutter
Throttling User Input in Flutter
Censoring TextFields in Flutter
Customizing TextButton in Flutter
Multiline TextFields in Flutter
Filtering TextField Input in Flutter
Focusing Manually on TextFields in Flutter
Data Streams Over HTTP/HTTPs in Dart
Catching Nonexistent Accessors or Methods in Dart
Using Expando in Dart
Implementing Custom Maps in Dart
Dynamically Calling Functions in Dart
Factory Constructors in Dart
Calculating the Sum of List Items in Dart
Removing Duplicate Strings in Lists in Dart (Case-Insensitive)
Implementing Range in Dart
Converting Lists to Maps in Dart
Implementing Hashable in Dart
Random Name Generator in Dart
Capturing Stack Traces in Dart Exceptions
Removing Duplicates from Lists in Dart
Optional Spread Operator in Dart
Calling Optional Functions in Dart
Odd-Even Sort in Dart
Implementing Zip and Tuples in Dart
Swapping Values in Lists with XOR in Dart
Waiting for Multiple Futures in Dart
Using Queues as Stacks in Dart
Custom Iterators in Dart
Iterables as Ranges and Transform in Dart
Errors vs Exceptions in Dart
Custom Annotations in Dart
Classes as Enums in Dart
Spread Operator in Collection Literals in Dart
StreamBuilder
and StreamController
in Dart
Almost Equal in Dart
Enum Associated Values in Dart
Implementing Comparable
in Dart
Implementing Custom Integer Types in Dart
Custom Subscripts in Dart
Dart List Enumeration with Index
Applying Mixins to Other Mixins in Dart
Parameter Types in Dart
Custom Exceptions in Dart
rethrow
ing Exceptions in Dart
mixin
s and JSON Parsing in Dart
mixin
s vs abstract class
es in Dart
Drawing Shapes in Flutter with LayoutBuilder
, CustomPaint
and CustomPainter
Generic Type Aliases in Dart
Callable Classes in Dart
Synchronous Generators in Dart
Implicit Interfaces in Dart
Did you know that in #Dart, every #class implicitly exports an #interface that can be #implemented (as opposed to #extended) by other classes? This is called "implicit interface".
Do you know how "const" constructors work in #Dart?
Did you know that in #Dart, it is actually preferred to use #async and #await over using raw #Futures?
In #Dart, you can use a combination of #Initializer #List plus default values for your class #member #fields to create elegant and handy convenience initializers
Did you know that in #Dart, you can extract elements of a certain type from your Lists using the #whereType #generic #function instead of calculating the #equality yourselves?
Do you know about #Type #Promotion in Dart?
"address" is an optional field of the "Person" class. If you look at the "doThis()" function you see that I'm saving the value of address in a local variable and then comparing it with null and then returning if it's null. The Dart compiler is intelligent enough to understand that after the if-statement, "address" is NOT null anymore since you've already compared it with null and returned from the function.
If you look at the "insteadOfThis" function, the first one, the Dart compiler cannot make the same assumption if you don't first store the value of address in a local variable. In that first function the Dart compiler, even after the if-statement, needs you to refer to address as an optional, using "address?" syntax.
The mechanism the Dart compiler uses in the "doThis()" function is called Type Promotion.
4 lines of #Dart code that include the #spread operator, #cascade #operator, #generics, #extensions, #private prefix and #getters
Functions as First Class Citizens in Dart
Download Details:
Author: vandadnp
Source Code: https://github.com/vandadnp/flutter-tips-and-tricks
#flutter #dart #programming #developer
1673055535
dart-vim-plugin provides filetype detection, syntax highlighting, and indentation for Dart code in Vim.
Looking for auto-complete, diagnostics as you type, jump to definition and other intellisense features? Try a vim plugin for the Language Server Protocol such as vim-lsc configured to start the Dart analysis server with the --lsp
flag.
Looking for an IDE experience? See the Dart Tools page.
Install as a typical vim plugin using your favorite approach. If you don't have a preference vim-plug is a good place to start. Below are examples for common choices, be sure to read the docs for each option.
call plug#begin()
"... <snip other plugins>
Plug 'dart-lang/dart-vim-plugin'
call plug#end()
Then invoke :PlugInstall
to install the plugin.
Clone the repository into your pathogen directory.
mkdir -p ~/.vim/bundle && cd ~/.vim/bundle && \
git clone https://github.com/dart-lang/dart-vim-plugin
Ensure your .vimrc
contains the line execute pathogen#infect()
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
"... <snip other plugins>
Plugin 'dart-lang/dart-vim-plugin'
call vundle#end()
Enable HTML syntax highlighting inside Dart strings with let dart_html_in_string=v:true
(default false).
Highlighting for specific syntax groups can be disabled by defining custom highlight group links. See :help dart-syntax
Enable Dart style guide syntax (like 2-space indentation) with let g:dart_style_guide = 2
Enable DartFmt execution on buffer save with let g:dart_format_on_save = 1
Configure DartFmt options with let g:dartfmt_options
(discover formatter options with dartfmt -h
)
dart format
?The indentation capabilities within vim are limited and it's not easy to fully express the indentation behavior of dart format
. The major area where this plugin differs from dart format
is indentation of function arguments when using a trailing comma in the argument list. When using a trailing comma (as is common in flutter widget code) dart format
uses 2 space indent for argument parameters. In all other indentation following an open parenthesis (argument lists without a trailing comma, multi-line assert statements, etc) dart format
uses 4 space indent. This plugin uses 4 space indent indent by default. To use 2 space indent by default, let g:dart_trailing_comma_indent = v:true
.
The Dart SDK comes with an analysis server that can be run in LSP mode. The server ships with the SDK. Assuming the bin
directory of the SDK is at $DART_SDK
the full command to run the analysis server in LSP mode is $DART_SDK/dart $DART_SDK/snapshots/analysis_server.dart.snapshot --lsp
. If you'll be opening files outside of the rootUri
sent by your LSP client (usually cwd
) you may want to pass onlyAnalyzeProjectsWithOpenFiles: true
in the initializationOptions
. See the documentation for your LSP client for how to configure initialization options. If you are using the vim-lsc plugin there is an additional plugin which can configure everything for you at vim-lsc-dart. A minimal config for a good default experience using vim-plug would look like:
call plug#begin()
Plug 'dart-lang/dart-vim-plugin'
Plug 'natebosch/vim-lsc'
Plug 'natebosch/vim-lsc-dart'
call plug#end()
let g:lsc_auto_map = v:true
Author: dart-lang
Source code: https://github.com/dart-lang/dart-vim-plugin
License: BSD-3-Clause license
1622722796
WordPress needs no introduction. It has been in the world for quite a long time. And up till now, it has given a tough fight to leading web development technology. The main reason behind its remarkable success is, it is highly customizable and also SEO-friendly. Other benefits include open-source technology, security, user-friendliness, and the thousands of free plugins it offers.
Talking of WordPress plugins, are a piece of software that enables you to add more features to the website. They are easy to integrate into your website and don’t hamper the performance of the site. WordPress, as a leading technology, has to offer many out-of-the-box plugins.
However, not always the WordPress would be able to meet your all needs. Hence you have to customize the WordPress plugin to provide you the functionality you wished. WordPress Plugins are easy to install and customize. You don’t have to build the solution from scratch and that’s one of the reasons why small and medium-sized businesses love it. It doesn’t need a hefty investment or the hiring of an in-house development team. You can use the core functionality of the plugin and expand it as your like.
In this blog, we would be talking in-depth about plugins and how to customize WordPress plugins to improve the functionality of your web applications.
What Is The Working Of The WordPress Plugins?
Developing your own plugin requires you to have some knowledge of the way they work. It ensures the better functioning of the customized plugins and avoids any mistakes that can hamper the experience on your site.
1. Hooks
Plugins operate primarily using hooks. As a hook attaches you to something, the same way a feature or functionality is hooked to your website. The piece of code interacts with the other components present on the website. There are two types of hooks: a. Action and b. Filter.
A. Action
If you want something to happen at a particular time, you need to use a WordPress “action” hook. With actions, you can add, change and improve the functionality of your plugin. It allows you to attach a new action that can be triggered by your users on the website.
There are several predefined actions available on WordPress, custom WordPress plugin development also allows you to develop your own action. This way you can make your plugin function as your want. It also allows you to set values for which the hook function. The add_ action function will then connect that function to a specific action.
B. Filters
They are the type of hooks that are accepted to a single variable or a series of variables. It sends them back after they have modified it. It allows you to change the content displayed to the user.
You can add the filter on your website with the apply_filter function, then you can define the filter under the function. To add a filter hook on the website, you have to add the $tag (the filter name) and $value (the filtered value or variable), this allows the hook to work. Also, you can add extra function values under $var.
Once you have made your filter, you can execute it with the add_filter function. This will activate your filter and would work when a specific function is triggered. You can also manipulate the variable and return it.
2. Shortcodes
Shortcodes are a good way to create and display the custom functionality of your website to visitors. They are client-side bits of code. They can be placed in the posts and pages like in the menu and widgets, etc.
There are many plugins that use shortcodes. By creating your very own shortcode, you too can customize the WordPress plugin. You can create your own shortcode with the add_shortcode function. The name of the shortcode that you use would be the first variable and the second variable would be the output of it when it is triggered. The output can be – attributes, content, and name.
3. Widgets
Other than the hooks and shortcodes, you can use the widgets to add functionality to the site. WordPress Widgets are a good way to create a widget by extending the WP_Widget class. They render a user-friendly experience, as they have an object-oriented design approach and the functions and values are stored in a single entity.
How To Customize WordPress Plugins?
There are various methods to customize the WordPress plugins. Depending on your need, and the degree of customization you wish to make in the plugin, choose the right option for you. Also, don’t forget to keep in mind that it requires a little bit of technical knowledge too. So find an expert WordPress plugin development company in case you lack the knowledge to do it by yourself.
1. Hire A Plugin Developer3
One of the best ways to customize a WordPress plugin is by hiring a plugin developer. There are many plugin developers listed in the WordPress directory. You can contact them and collaborate with world-class WordPress developers. It is quite easy to find a WordPress plugin developer.
Since it is not much work and doesn’t pay well or for the long term a lot of developers would be unwilling to collaborate but, you will eventually find people.
2. Creating A Supporting Plugin
If you are looking for added functionality in an already existing plugin go for this option. It is a cheap way to meet your needs and creating a supporting plugin takes very little time as it has very limited needs. Furthermore, you can extend a plugin to a current feature set without altering its base code.
However, to do so, you have to hire a WordPress developer as it also requires some technical knowledge.
3. Use Custom Hooks
Use the WordPress hooks to integrate some other feature into an existing plugin. You can add an action or a filter as per your need and improve the functionality of the website.
If the plugin you want to customize has the hook, you don’t have to do much to customize it. You can write your own plugin that works with these hooks. This way you don’t have to build a WordPress plugin right from scratch. If the hook is not present in the plugin code, you can contact a WordPress developer or write the code yourself. It may take some time, but it works.
Once the hook is added, you just have to manually patch each one upon the release of the new plugin update.
4. Override Callbacks
The last way to customize WordPress plugins is by override callbacks. You can alter the core functionality of the WordPress plugin with this method. You can completely change the way it functions with your website. It is a way to completely transform the plugin. By adding your own custom callbacks, you can create the exact functionality you desire.
We suggest you go for a web developer proficient in WordPress as this requires a good amount of technical knowledge and the working of a plugin.
#customize wordpress plugins #how to customize plugins in wordpress #how to customize wordpress plugins #how to edit plugins in wordpress #how to edit wordpress plugins #wordpress plugin customization
1605176204
In this video, I’ll be showing you why I think it’s good to know Vim as a Developer.
#vim #vim editor #text editor #what is vim #speed,2x dev #vim for node.js
1650093900
YouCompleteMe: a code-completion engine for Vim
Looking for help, advice or support? Having problems getting YCM to work?
First carefully read the installation instructions for your OS. We recommend you use the supplied install.py
- the "full" installation guide is for rare, advanced use cases and most users should use install.py
.
If the server isn't starting and you're getting a "YouCompleteMe unavailable" error, check the Troubleshooting guide.
Next check the User Guide section on the semantic completer that you are using. For C/C++/Objective-C/Objective-C++/CUDA, you must read this section.
Finally, check the FAQ.
If, after reading the installation and user guides, and checking the FAQ, you're still having trouble, check the contacts section below for how to get in touch.
Please do NOT go to #vim on Freenode for support. Please contact the YouCompleteMe maintainers directly using the contact details below.
YouCompleteMe is a fast, as-you-type, fuzzy-search code completion, comprehension and refactoring engine for Vim.
It has several completion engines built in and supports any protocol-compliant Language Server, so can work with practically any language. YouCompleteMe contains:
Here's an explanation of what happens in the last GIF demo above.
First, realize that no keyboard shortcuts had to be pressed to get the list of completion candidates at any point in the demo. The user just types and the suggestions pop up by themselves. If the user doesn't find the completion suggestions relevant and/or just wants to type, they can do so; the completion engine will not interfere.
When the user sees a useful completion string being offered, they press the TAB key to accept it. This inserts the completion string. Repeated presses of the TAB key cycle through the offered completions.
If the offered completions are not relevant enough, the user can continue typing to further filter out unwanted completions.
A critical thing to notice is that the completion filtering is NOT based on the input being a string prefix of the completion (but that works too). The input needs to be a subsequence match of a completion. This is a fancy way of saying that any input characters need to be present in a completion string in the order in which they appear in the input. So abc
is a subsequence of xaybgc
, but not of xbyxaxxc
. After the filter, a complicated sorting system ranks the completion strings so that the most relevant ones rise to the top of the menu (so you usually need to press TAB just once).
All of the above works with any programming language because of the identifier-based completion engine. It collects all of the identifiers in the current file and other files you visit (and your tags files) and searches them when you type (identifiers are put into per-filetype groups).
The demo also shows the semantic engine in use. When the user presses .
, ->
or ::
while typing in insert mode (for C++; different triggers are used for other languages), the semantic engine is triggered (it can also be triggered with a keyboard shortcut; see the rest of the docs).
The last thing that you can see in the demo is YCM's diagnostic display features (the little red X that shows up in the left gutter; inspired by Syntastic) if you are editing a C-family file. As the completer engine compiles your file and detects warnings or errors, they will be presented in various ways. You don't need to save your file or press any keyboard shortcut to trigger this, it "just happens" in the background.
And that's not all...
YCM might be the only vim completion engine with the correct Unicode support. Though we do assume UTF-8 everywhere.
YCM also provides semantic IDE-like features in a number of languages, including:
For example, here's a demo of signature help:
Below we can see YCM being able to do a few things:
auto
in C++FixIt
GoToImplementation
and GoToType
for servers that support it.And here's some documentation being shown in a hover popup, automatically and manually:
Features vary by file type, so make sure to check out the file type feature summary and the full list of completer subcommands to find out what's available for your favourite languages.
You'll also find that YCM has filepath completers (try typing ./
in a file) and a completer that integrates with UltiSnips.
Our policy is to support the Vim version that's in the latest LTS of Ubuntu. That's currently Ubuntu 20.04 which contains vim-nox
at v8.1.2269
.
Vim must have a working Python 3.6 runtime, compiled with --enable-shared
(or --enable-framework
). You can check with :py3 import sys; print( sys.version )
.
For Neovim users, our policy is to require the latest released version. Currently, Neovim 0.5.0 is required. Please note that some features are not available in Neovim, and Neovim is not officially supported.
In order to provide the best possible performance and stability, ycmd has updated its code to C++17. This requires a version bump of the minimum supported compilers. The new requirements are:
Compiler | Current Min |
---|---|
GCC | 8 |
Clang | 7 |
MSVC | 15.7 (VS 2017) |
YCM requires CMake 3.13 or greater. If your CMake is too old, you may be able to simply pip install --user cmake
to get a really new version.
When enabling language support for a particular language, there may be runtime requirements, such as needing Java Development Kit for Java support. In general, YCM is not in control of the required versions for the downstream compilers, though we do our best to signal where we know them.
$ brew install cmake python go nodejs
Install mono from Mono Project (NOTE: on Intel Macs you can also brew install mono
. On arm Macs, you may require Rosetta)
For java support you must install a JDK, one way to do this is with Homebrew:
$ brew install java
$ sudo ln -sfn $(brew --prefix java)/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk
Pre-installed macOS system Vim does not support Python 3. So you need to install either a Vim that supports Python 3 OR MacVim with Homebrew:
brew install vim
brew install macvim
Compile YCM.
For Intel and arm64 Macs, the bundled libclang/clangd work:
cd ~/.vim/bundle/YouCompleteMe
python3 install.py --all
If you have troubles with finding system frameworks or C++ standard library, try using the homebrew llvm:
brew install llvm
cd ~/.vim/bundle/YouCompleteMe
python3 install.py --system-libclang --all
And edit your vimrc to add the following line to use the Homebrew llvm's clangd:
" Use homebrew's clangd
let g:ycm_clangd_binary_path = trim(system('brew --prefix llvm')).'/bin/clangd'
For using an arbitrary LSP server, check the relevant section
These instructions (using install.py
) are the quickest way to install YouCompleteMe, however they may not work for everyone. If the following instructions don't work for you, check out the full installation guide.
A supported Vim version with Python 3 is required. MacVim is a good option, even if you only use the terminal. YCM won't work with the pre-installed Vim from Apple as its Python support is broken. If you don't already use a Vim that supports Python 3 or MacVim, install it with Homebrew. Install CMake as well:
brew install vim cmake
OR
brew install macvim cmake
Install YouCompleteMe with Vundle.
Remember: YCM is a plugin with a compiled component. If you update YCM using Vundle and the ycm_core
library APIs have changed (happens rarely), YCM will notify you to recompile it. You should then rerun the install process.
NOTE: If you want C-family completion, you MUST have the latest Xcode installed along with the latest Command Line Tools (they are installed automatically when you run clang
for the first time, or manually by running xcode-select --install
)
Compiling YCM with semantic support for C-family languages through clangd:
cd ~/.vim/bundle/YouCompleteMe
./install.py --clangd-completer
Compiling YCM without semantic support for C-family languages:
cd ~/.vim/bundle/YouCompleteMe
./install.py
The following additional language support options are available:
--cs-completer
when calling install.py
.--go-completer
when calling install.py
.--ts-completer
when calling install.py
.--rust-completer
when calling install.py
.--java-completer
when calling install.py
.To simply compile with everything enabled, there's a --all
flag. So, to install with all language features, ensure xbuild
, go
, node
and npm
tools are installed and in your PATH
, then simply run:
cd ~/.vim/bundle/YouCompleteMe
./install.py --all
That's it. You're done. Refer to the User Guide section on how to use YCM. Don't forget that if you want the C-family semantic completion engine to work, you will need to provide the compilation flags for your project to YCM. It's all in the User Guide.
YCM comes with sane defaults for its options, but you still may want to take a look at what's available for configuration. There are a few interesting options that are conservatively turned off by default that you may want to turn on.
The following assume you're using Ubuntu 20.04.
apt install build-essential cmake vim-nox python3-dev
apt install mono-complete golang nodejs default-jdk npm
cd ~/.vim/bundle/YouCompleteMe
python3 install.py --all
These instructions (using install.py
) are the quickest way to install YouCompleteMe, however they may not work for everyone. If the following instructions don't work for you, check out the full installation guide.
Make sure you have a supported version of Vim with Python 3 support, and a supported compiler. The latest LTS of Ubuntu is the minimum platform for simple installation. For earlier releases or other distributions, you may have to do some work to acquire the dependencies.
If your vim version is too old, you may need to compile Vim from source (don't worry, it's easy).
Install YouCompleteMe with Vundle.
Remember: YCM is a plugin with a compiled component. If you update YCM using Vundle and the ycm_core
library APIs have changed (happens rarely), YCM will notify you to recompile it. You should then rerun the install process.
Install development tools, CMake, and Python headers:
sudo dnf install cmake gcc-c++ make python3-devel
sudo apt install build-essential cmake3 python3-dev
Compiling YCM with semantic support for C-family languages through clangd:
cd ~/.vim/bundle/YouCompleteMe
python3 install.py --clangd-completer
Compiling YCM without semantic support for C-family languages:
cd ~/.vim/bundle/YouCompleteMe
python3 install.py
The following additional language support options are available:
--cs-completer
when calling install.py
.--go-completer
when calling install.py
.--ts-completer
when calling install.py
.--rust-completer
when calling install.py
.--java-completer
when calling install.py
.To simply compile with everything enabled, there's a --all
flag. So, to install with all language features, ensure xbuild
, go
, node
and npm
tools are installed and in your PATH
, then simply run:
cd ~/.vim/bundle/YouCompleteMe
python3 install.py --all
That's it. You're done. Refer to the User Guide section on how to use YCM. Don't forget that if you want the C-family semantic completion engine to work, you will need to provide the compilation flags for your project to YCM. It's all in the User Guide.
YCM comes with sane defaults for its options, but you still may want to take a look at what's available for configuration. There are a few interesting options that are conservatively turned off by default that you may want to turn on.
cd YouCompleteMe
python3 install.py --all
set encoding=utf-8
to your vimrcThese instructions (using install.py
) are the quickest way to install YouCompleteMe, however they may not work for everyone. If the following instructions don't work for you, check out the full installation guide.
Important: we assume that you are using the cmd.exe
command prompt and that you know how to add an executable to the PATH environment variable.
Make sure you have a supported Vim version with Python 3 support. You can check the version and which Python is supported by typing :version
inside Vim. Look at the features included: +python3/dyn
for Python 3. Take note of the Vim architecture, i.e. 32 or 64-bit. It will be important when choosing the Python installer. We recommend using a 64-bit client. Daily updated installers of 32-bit and 64-bit Vim with Python 3 support are available.
Add the following line to your vimrc if not already present.:
set encoding=utf-8
This option is required by YCM. Note that it does not prevent you from editing a file in another encoding than UTF-8. You can do that by specifying the ++enc
argument to the :e
command.
Install YouCompleteMe with Vundle.
Remember: YCM is a plugin with a compiled component. If you update YCM using Vundle and the ycm_core
library APIs have changed (happens rarely), YCM will notify you to recompile it. You should then rerun the install process.
Download and install the following software:
:version
and look at the bottom of the page at the list of compiler flags. Look for flags that look similar to -DDYNAMIC_PYTHON3_DLL=\"python36.dll\"
. This indicates that Vim is looking for Python 3.6. You'll need one or the other installed, matching the version number exactly.Compiling YCM with semantic support for C-family languages through clangd:
cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe
python install.py --clangd-completer
Compiling YCM without semantic support for C-family languages:
cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe
python install.py
The following additional language support options are available:
--cs-completer
when calling install.py
. Be sure that the build utility msbuild
is in your PATH.--go-completer
when calling install.py
.--ts-completer
when calling install.py
.--rust-completer
when calling install.py
.--java-completer
when calling install.py
.To simply compile with everything enabled, there's a --all
flag. So, to install with all language features, ensure msbuild
, go
, node
and npm
tools are installed and in your PATH
, then simply run:
cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe
python install.py --all
You can specify the Microsoft Visual C++ (MSVC) version using the --msvc
option. YCM officially supports MSVC 15 (2017), MSVC 16 (Visual Studio 2019) and MSVC 17 (Visual Studio 17 2022).
That's it. You're done. Refer to the User Guide section on how to use YCM. Don't forget that if you want the C-family semantic completion engine to work, you will need to provide the compilation flags for your project to YCM. It's all in the User Guide.
YCM comes with sane defaults for its options, but you still may want to take a look at what's available for configuration. There are a few interesting options that are conservatively turned off by default that you may want to turn on.
pkg install cmake
cd ~/.vim/bundle/YouCompleteMe
python3 install.py --all
These instructions (using install.py
) are the quickest way to install YouCompleteMe, however they may not work for everyone. If the following instructions don't work for you, check out the full installation guide.
NOTE: OpenBSD / FreeBSD are not officially supported platforms by YCM.
Make sure you have a supported Vim version with Python 3 support, and a supported compiler and CMake, perhaps:
pkg install cmake
Install YouCompleteMe with Vundle.
Remember: YCM is a plugin with a compiled component. If you update YCM using Vundle and the ycm_core
library APIs have changed (happens rarely), YCM will notify you to recompile it. You should then rerun the install process.
Compiling YCM with semantic support for C-family languages through clangd:
cd ~/.vim/bundle/YouCompleteMe
./install.py --clangd-completer
Compiling YCM without semantic support for C-family languages:
cd ~/.vim/bundle/YouCompleteMe
./install.py
If the python
executable is not present, or the default python
is not the one that should be compiled against, specify the python interpreter explicitly:
python3 install.py --clangd-completer
The following additional language support options are available:
--cs-completer
when calling ./install.py
.--go-completer
when calling ./install.py
.--ts-completer
when calling install.py
.--rust-completer
when calling ./install.py
.--java-completer
when calling ./install.py
.To simply compile with everything enabled, there's a --all
flag. So, to install with all language features, ensure xbuild
, go
, node
and npm
tools are installed and in your PATH
, then simply run:
cd ~/.vim/bundle/YouCompleteMe
./install.py --all
That's it. You're done. Refer to the User Guide section on how to use YCM. Don't forget that if you want the C-family semantic completion engine to work, you will need to provide the compilation flags for your project to YCM. It's all in the User Guide.
YCM comes with sane defaults for its options, but you still may want to take a look at what's available for configuration. There are a few interesting options that are conservatively turned off by default that you may want to turn on.
The full installation guide has been moved to the wiki.
GoTo
, etc.)GoToSymbol
), with interactive searchGoToDocumentOutline
), with interactive searchGetDoc
)GetType
)FixIt
)GoToReferences
)RefactorRename <new name>
)Format
)GoTo
, etc.)GoToImplementation
)GoToSymbol
), with interactive searchGetDoc
)GetType
)FixIt
)RefactorRename <new name>
)Format
)GoTo
)GoToSymbol
), with interactive searchGoToReferences
)GetDoc
)GetType
)RefactorRename <new name>
)GoTo
, etc.)GoToType
)GoToImplementation
)GoToDocumentOutline
), with interactive searchFixIt
)GetDoc
)GetType
)Format
)gopls
server instanceGoTo
, GoToDefinition
, and GoToDeclaration
are identical)GoToType
)GoToImplementation
)GoToSymbol
), with interactive searchGoToReferences
)GetDoc
)GetType
)FixIt
)RefactorRename <new name>
)Format
)OrganizeImports
)TSServer
server instanceGoTo
, etc.)GoToImplementation
)GoToReferences
)GoToDocumentOutline
), with interactive searchGetDoc
)FixIt
)GetType
)RefactorRename <new name>
)Format
)rust-analyzer
server instanceGoTo
, GoToDefinition
, and GoToDeclaration
are identical)GoToType
)GoToImplementation
)GoToSymbol
), with interactive searchGoToReferences
)GoToDocumentOutline
), with interactive searchGetDoc
)GetType
)FixIt
)RefactorRename <new name>
)Format
)OrganizeImports
)ExecuteCommand <args>
)jdt.ls
server instanceIf the offered completions are too broad, keep typing characters; YCM will continue refining the offered completions based on your input.
Filtering is "smart-case" and "smart-diacritic" sensitive; if you are typing only lowercase letters, then it's case-insensitive. If your input contains uppercase letters, then the uppercase letters in your query must match uppercase letters in the completion strings (the lowercase letters still match both). On top of that, a letter with no diacritic marks will match that letter with or without marks:
matches | foo | fôo | fOo | fÔo |
---|---|---|---|---|
foo | ✔️ | ✔️ | ✔️ | ✔️ |
fôo | ❌ | ✔️ | ❌ | ✔️ |
fOo | ❌ | ❌ | ✔️ | ✔️ |
fÔo | ❌ | ❌ | ❌ | ✔️ |
Use the TAB key to accept a completion and continue pressing TAB to cycle through the completions. Use Shift-TAB to cycle backwards. Note that if you're using console Vim (that is, not gvim or MacVim) then it's likely that the Shift-TAB binding will not work because the console will not pass it to Vim. You can remap the keys; see the Options section below.
Knowing a little bit about how YCM works internally will prevent confusion. YCM has several completion engines: an identifier-based completer that collects all of the identifiers in the current file and other files you visit (and your tags files) and searches them when you type (identifiers are put into per-filetype groups).
There are also several semantic engines in YCM. There are libclang-based and clangd-based completers that provide semantic completion for C-family languages. There's a Jedi-based completer for semantic completion for Python. There's also an omnifunc-based completer that uses data from Vim's omnicomplete system to provide semantic completions when no native completer exists for that language in YCM.
There are also other completion engines, like the UltiSnips completer and the filepath completer.
YCM automatically detects which completion engine would be the best in any situation. On occasion, it queries several of them at once, merges the outputs and presents the results to you.
YCM has a client-server architecture; the Vim part of YCM is only a thin client that talks to the ycmd HTTP+JSON server that has the vast majority of YCM logic and functionality. The server is started and stopped automatically as you start and stop Vim.
The subsequence filter removes any completions that do not match the input, but then the sorting system kicks in. It's actually very complicated and uses lots of factors, but suffice it to say that "word boundary" (WB) subsequence character matches are "worth" more than non-WB matches. In effect, this means given an input of "gua", the completion "getUserAccount" would be ranked higher in the list than the "Fooguxa" completion (both of which are subsequence matches). A word-boundary character are all capital characters, characters preceded by an underscore and the first letter character in the completion string.
Valid signatures are displayed in a second popup menu and the current signature is highlighted along with the current argument.
Signature help is triggered in insert mode automatically when g:ycm_auto_trigger
is enabled and is not supported when it is not enabled.
The signatures popup is hidden when there are no matching signatures or when you leave insert mode. There is no key binding to clear the popup.
For more details on this feature and a few demos, check out the PR that proposed it.
The signature help popup sometimes gets in the way. You can toggle its visibility with a mapping. YCM provides the "Plug" mapping <Plug>(YCMToggleSignatureHelp)
for this.
For example, to hide/show the signature help popup by pressing Ctrl+l in insert mode: imap <silent> <C-l> <Plug>(YCMToggleSignatureHelp)
.
NOTE: No default mapping is provided because insert mappings are very difficult to create without breaking or overriding some existing functionality. Ctrl-l is not a suggestion, just an example.
You can use Ctrl+Space to trigger the completion suggestions anywhere, even without a string prefix. This is useful to see which top-level functions are available for use.
NOTE: YCM originally used the libclang
based engine for C-family, but users should migrate to clangd, as it provides more features and better performance. Users who rely on override_filename
in their .ycm_extra_conf.py
will need to stay on the old libclang
engine. Instructions on how to stay on the old engine are available on the wiki.
Some of the features of clangd:
#include
insertions for those items.On supported architectures, the install.py
script will download a suitable clangd (--clangd-completer
) or libclang (--clang-completer
) for you. Supported architectures are:
clangd:
Typically, clangd is installed by the YCM installer (either with --all
or with --clangd-completer
). This downloads a pre-built clangd
binary for your architecture. If your OS or architecture is not supported or too old, you can install a compatible clangd
and use g:ycm_clangd_binary_path
to point to it.
libclang:
libclang
can be enabled also with --all
or --clang-completer
. As with clangd
, YCM will try and download a version of libclang
that is suitable for your environment, but again if your environment can't be supported, you can build or acquire libclang
for yourself and specify it when building, as:
$ EXTRA_CMAKE_ARGS='-DPATH_TO_LLVM_ROOT=/path/to/your/llvm' ./install.py --clang-compelter --system-libclang
Please note that if using custom clangd
or libclang
it must match the version that YCM requires. Currently YCM requires clang 13.0.0.
In order to perform semantic analysis such as code completion, GoTo
and diagnostics, YouCompleteMe uses clangd
, which makes use of clang compiler, sometimes also referred to as LLVM. Like any compiler, clang also requires a set of compile flags in order to parse your code. Simply put: If clang can't parse your code, YouCompleteMe can't provide semantic analysis.
There are 2 methods which can be used to provide compile flags to clang:
The easiest way to get YCM to compile your code is to use a compilation database. A compilation database is usually generated by your build system (e.g. CMake
) and contains the compiler invocation for each compilation unit in your project.
For information on how to generate a compilation database, see the clang documentation. In short:
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON
when configuring (or add set( CMAKE_EXPORT_COMPILE_COMMANDS ON )
to CMakeLists.txt
) and copy or symlink the generated database to the root of your project.compdb
tool (-t compdb
) in its docs..ycm_extra_conf.py
below.If no .ycm_extra_conf.py
is found, YouCompleteMe automatically tries to load a compilation database if there is one.
YCM looks for a file named compile_commands.json
in the directory of the opened file or in any directory above it in the hierarchy (recursively); when the file is found before a local .ycm_extra_conf.py
, YouCompleteMe stops searching the directories and lets clangd take over and handle the flags.
If you don't have a compilation database, or aren't able to generate one, you have to tell YouCompleteMe how to compile your code some other way.
Every C-family project is different. It is not possible for YCM to guess what compiler flags to supply for your project. Fortunately, YCM provides a mechanism for you to generate the flags for a particular file with arbitrary complexity. This is achieved by requiring you to provide a Python module which implements a trivial function which, given the file name as argument, returns a list of compiler flags to use to compile that file.
YCM looks for a .ycm_extra_conf.py
file in the directory of the opened file or in any directory above it in the hierarchy (recursively); when the file is found, it is loaded (only once!) as a Python module. YCM calls a Settings
method in that module which should provide it with the information necessary to compile the current file. You can also provide a path to a global configuration file with the g:ycm_global_ycm_extra_conf
option, which will be used as a fallback. To prevent the execution of malicious code from a file you didn't write YCM will ask you once per .ycm_extra_conf.py
if it is safe to load. This can be disabled and you can white-/blacklist files. See the g:ycm_confirm_extra_conf
and g:ycm_extra_conf_globlist
options respectively.
This system was designed this way so that the user can perform any arbitrary sequence of operations to produce a list of compilation flags YCM should hand to Clang.
NOTE: It is highly recommended to include -x <language>
flag to libclang. This is so that the correct language is detected, particularly for header files. Common values are -x c
for C, -x c++
for C++, -x objc
for Objective-C, and -x cuda
for CUDA.
To give you an impression, if your C++ project is trivial, and your usual compilation command is: g++ -Wall -Wextra -Werror -o FILE.o FILE.cc
, then the following .ycm_extra_conf.py
is enough to get semantic analysis from YouCompleteMe:
def Settings( **kwargs ):
return {
'flags': [ '-x', 'c++', '-Wall', '-Wextra', '-Werror' ],
}
As you can see from the trivial example, YCM calls the Settings
method which returns a dictionary with a single element 'flags'
. This element is a list
of compiler flags to pass to libclang for the current file. The absolute path of that file is accessible under the filename
key of the kwargs
dictionary. That's it! This is actually enough for most projects, but for complex projects it is not uncommon to integrate directly with an existing build system using the full power of the Python language.
For a more elaborate example, see ycmd's own .ycm_extra_conf.py
. You should be able to use it as a starting point. Don't just copy/paste that file somewhere and expect things to magically work; your project needs different flags. Hint: just replace the strings in the flags
variable with compilation flags necessary for your project. That should be enough for 99% of projects.
You could also consider using YCM-Generator to generate the ycm_extra_conf.py
file.
If Clang encounters errors when compiling the header files that your file includes, then it's probably going to take a long time to get completions. When the completion menu finally appears, it's going to have a large number of unrelated completion strings (type/function names that are not actually members). This is because Clang fails to build a precompiled preamble for your file if there are any errors in the included headers and that preamble is key to getting fast completions.
Call the :YcmDiags
command to see if any errors or warnings were detected in your file.
Ensure that you have enabled the Java completer. See the installation guide for details.
Create a project file (gradle or maven) file in the root directory of your Java project, by following the instructions below.
(Optional) Configure the LSP server. The jdt.ls configuration options can be found in their codebase.
If you previously used Eclim or Syntastic for Java, disable them for Java.
Edit a Java file from your project.
In order to provide semantic analysis, the Java completion engine requires knowledge of your project structure. In particular it needs to know the class path to use, when compiling your code. Fortunately jdt.ls supports eclipse project files, maven projects and gradle projects.
NOTE: Our recommendation is to use either maven or gradle projects.
The native support for Java includes YCM's native realtime diagnostics display. This can conflict with other diagnostics plugins like Syntastic, so when enabling Java support, please manually disable Syntastic Java diagnostics.
Add the following to your vimrc
:
let g:syntastic_java_checkers = []
The native support for Java includes YCM's native realtime diagnostics display. This can conflict with other diagnostics plugins like Eclim, so when enabling Java support, please manually disable Eclim Java diagnostics.
Add the following to your vimrc
:
let g:EclimFileTypeValidate = 0
NOTE: We recommend disabling Eclim entirely when editing Java with YCM's native Java support. This can be done temporarily with :EclimDisable
.
Eclipse style projects require two files: .project and .classpath.
If your project already has these files due to previously being set up within eclipse, then no setup is required. jdt.ls should load the project just fine (it's basically eclipse after all).
However, if not, it is possible (easy in fact) to craft them manually, though it is not recommended. You're better off using gradle or maven (see below).
A simple eclipse style project example can be found in the ycmd test directory. Normally all that is required is to copy these files to the root of your project and to edit the .classpath
to add additional libraries, such as:
<classpathentry kind="lib" path="/path/to/external/jar" />
<classpathentry kind="lib" path="/path/to/external/java/source" />
It may also be necessary to change the directory in which your source files are located (paths are relative to the .project file itself):
<classpathentry kind="src" output="target/classes" path="path/to/src/" />
NOTE: The eclipse project and classpath files are not a public interface and it is highly recommended to use Maven or Gradle project definitions if you don't already use eclipse to manage your projects.
Maven needs a file named pom.xml in the root of the project. Once again a simple pom.xml can be found in ycmd source.
The format of pom.xml files is way beyond the scope of this document, but we do recommend using the various tools that can generate them for you, if you're not familiar with them already.
Gradle projects require a build.gradle. Again, there is a trivial example in ycmd's tests.
The format of build.gradle files is way beyond the scope of this document, but we do recommend using the various tools that can generate them for you, if you're not familiar with them already.
Some users have experienced issues with their jdt.ls when using the Groovy language for their build.gradle. As such, try using Kotlin instead.
If you're not getting completions or diagnostics, check the server health:
:YcmDebugInfo
. Ensure that the following lines are present:-- jdt.ls Java Language Server running
-- jdt.ls Java Language Server Startup Status: Ready
:YcmToggleLogs
. The jdt.ls log file is called .log
(for some reason).If you get a message about "classpath is incomplete", then make sure you have correctly configured the project files.
If you get messages about unresolved imports, then make sure you have correctly configured the project files, in particular check that the classpath is set correctly.
YCM relies on OmniSharp-Roslyn to provide completion and code navigation. OmniSharp-Roslyn needs a solution file for a C# project and there are two ways of letting YCM know about your solution files.
YCM will scan all parent directories of the file currently being edited and look for file with .sln
extension.
If YCM loads .ycm_extra_conf.py
which contains CSharpSolutionFile
function, YCM will try to use that to determine the solution file. This is useful when one wants to override the default behaviour and specify a solution file that is not in any of the parent directories of the currently edited file. Example:
def CSharpSolutionFile( filepath ):
# `filepath` is the path of the file user is editing
return '/path/to/solution/file' # Can be relative to the `.ycm_extra_conf.py`
If the path returned by CSharpSolutionFile
is not an actual file, YCM will fall back to the other way of finding the file.
YCM relies on the Jedi engine to provide completion and code navigation. By default, it will pick the version of Python running the ycmd server and use its sys.path
. While this is fine for simple projects, this needs to be configurable when working with virtual environments or in a project with third-party packages. The next sections explain how to do that.
A common practice when working on a Python project is to install its dependencies in a virtual environment and develop the project inside that environment. To support this, YCM needs to know the interpreter path of the virtual environment. You can specify it by creating a .ycm_extra_conf.py
file at the root of your project with the following contents:
def Settings( **kwargs ):
return {
'interpreter_path': '/path/to/virtual/environment/python'
}
Here, /path/to/virtual/environment/python
is the path to the Python used by the virtual environment you are working in. Typically, the executable can be found in the Scripts
folder of the virtual environment directory on Windows and in the bin
folder on other platforms.
If you don't like having to create a .ycm_extra_conf.py
file at the root of your project and would prefer to specify the interpreter path with a Vim option, read the Configuring through Vim options section.
Another common practice is to put the dependencies directly into the project and add their paths to sys.path
at runtime in order to import them. YCM needs to be told about this path manipulation to support those dependencies. This can be done by creating a .ycm_extra_conf.py
file at the root of the project. This file must define a Settings( **kwargs )
function returning a dictionary with the list of paths to prepend to sys.path
under the sys_path
key. For instance, the following .ycm_extra_conf.py
adds the paths /path/to/some/third_party/package
and /path/to/another/third_party/package
at the start of sys.path
:
def Settings( **kwargs ):
return {
'sys_path': [
'/path/to/some/third_party/package',
'/path/to/another/third_party/package'
]
}
If you would rather prepend paths to sys.path
with a Vim option, read the Configuring through Vim options section.
If you need further control on how to add paths to sys.path
, you should define the PythonSysPath( **kwargs )
function in the .ycm_extra_conf.py
file. Its keyword arguments are sys_path
which contains the default sys.path
, and interpreter_path
which is the path to the Python interpreter. Here's a trivial example that insert the /path/to/third_party/package
path at the second position of sys.path
:
def PythonSysPath( **kwargs ):
sys_path = kwargs[ 'sys_path' ]
sys_path.insert( 1, '/path/to/third_party/package' )
return sys_path
A more advanced example can be found in YCM's own .ycm_extra_conf.py
.
You may find inconvenient to have to create a .ycm_extra_conf.py
file at the root of each one of your projects in order to set the path to the Python interpreter and/or add paths to sys.path
and would prefer to be able to configure those through Vim options. Don't worry, this is possible by using the g:ycm_extra_conf_vim_data
option and creating a global extra configuration file. Let's take an example. Suppose that you want to set the interpreter path with the g:ycm_python_interpreter_path
option and prepend paths to sys.path
with the g:ycm_python_sys_path
option. Suppose also that you want to name the global extra configuration file global_extra_conf.py
and that you want to put it in your HOME folder. You should then add the following lines to your vimrc:
let g:ycm_python_interpreter_path = ''
let g:ycm_python_sys_path = []
let g:ycm_extra_conf_vim_data = [
\ 'g:ycm_python_interpreter_path',
\ 'g:ycm_python_sys_path'
\]
let g:ycm_global_ycm_extra_conf = '~/global_extra_conf.py'
Then, create the ~/global_extra_conf.py
file with the following contents:
def Settings( **kwargs ):
client_data = kwargs[ 'client_data' ]
return {
'interpreter_path': client_data[ 'g:ycm_python_interpreter_path' ],
'sys_path': client_data[ 'g:ycm_python_sys_path' ]
}
That's it. You are done. Note that you don't need to restart the server when setting one of the options. YCM will automatically pick the new values.
YCM uses rust-analyzer for Rust semantic completion.
NOTE: Previously, YCM used rls for rust completion. This is no longer supported, as the Rust community has decided on rust-analyzer as the future of Rust tooling.
Completions and GoTo commands within the current crate and its dependencies should work out of the box with no additional configuration (provided that you built YCM with the --rust-completer
flag; see the Installation section for details). The install script takes care of installing the Rust source code, so no configuration is necessary.
rust-analyzer
supports a myriad of options. These are configured using LSP configuration, and are documented here.
Completions and GoTo commands should work out of the box (provided that you built YCM with the --go-completer
flag; see the Installation section for details). The server only works for projects with the "canonical" layout.
gopls
also has a handful of undocumented options for which the source code is the only reference.
NOTE: YCM originally used the Tern engine for JavaScript but due to Tern not being maintained anymore by its main author and the TSServer engine offering more features, YCM is moving to TSServer. This won't affect you if you were already using Tern but you are encouraged to do the switch by deleting the third_party/ycmd/third_party/tern_runtime/node_modules
directory in YCM folder. If you are a new user but still want to use Tern, you should pass the --js-completer
option to the install.py
script during installation. Further instructions on how to setup YCM with Tern are available on the wiki.
All JavaScript and TypeScript features are provided by the TSServer engine, which is included in the TypeScript SDK. To enable these features, install Node.js and npm and call the install.py
script with the --ts-completer
flag.
TSServer relies on the jsconfig.json
file for JavaScript and the tsconfig.json
file for TypeScript to analyze your project. Ensure the file exists at the root of your project.
To get diagnostics in JavaScript, set the checkJs
option to true
in your jsconfig.json
file:
{
"compilerOptions": {
"checkJs": true
}
}
C-family, C#, Go, Java, Python, Rust, and JavaScript/TypeScript languages are supported natively by YouCompleteMe using the Clang, OmniSharp-Roslyn, Gopls, jdt.ls, Jedi, rust-analyzer, and TSServer engines, respectively. Check the installation section for instructions to enable these features if desired.
Similar to other LSP clients, YCM can use an arbitrary LSP server with the help of g:ycm_language_server
option. An example of a value of this option would be:
let g:ycm_language_server =
\ [
\ {
\ 'name': 'yaml',
\ 'cmdline': [ '/path/to/yaml/server/yaml-language-server', '--stdio' ],
\ 'filetypes': [ 'yaml' ]
\ },
\ {
\ 'name': 'rust',
\ 'cmdline': [ 'ra_lsp_server' ],
\ 'filetypes': [ 'rust' ],
\ 'project_root_files': [ 'Cargo.toml' ]
\ },
\ {
\ 'name': 'godot',
\ 'filetypes': [ 'gdscript' ],
\ 'port': 6008,
\ 'project_root_files': [ 'project.godot' ]
\ }
\ ]
Each dictionary contains the following keys:
name
(string, mandatory): When configuring a LSP server the value of the name
key will be used as the kwargs[ 'language' ]
. Can be anything you like.filetypes
(list of string, mandatory): List of Vim filetypes this server should be used for.project_root_files
(list of string, optional): List of filenames to search for when trying to determine the project root.cmdline
(list of string, optional): If supplied, the server is started with this command line (each list element is a command line word). Typically, the server should be started with STDIO communication. If not supplied, port
must be supplied.port
(number, optional): If supplied, ycmd will connect to the server at localhost:<port>
using TCP (remote servers are not supported).capabilities
(dict, optional): If supplied, this is a dictionary that is merged with the LSP client capabilities reported to the language server. This can be used to enable or disable certain features, such as the support for configuration sections (workspace/configuration
).See the LSP Examples project for more examples of configuring the likes of PHP, Ruby, Kotlin, and D.
Many LSP servers allow some level of user configuration. YCM enables this with the help of .ycm_extra_conf.py
files. Here's an example of jdt.ls user examples of configuring the likes of PHP, Ruby, Kotlin, D, and many, many more.
def Settings( **kwargs ):
if kwargs[ 'language' ] == 'java':
return {
'ls': {
'java.format.onType.enabled': True
}
}
The ls
key tells YCM that the dictionary should be passed to the LSP server. For each of the LSP server's configuration you should look up the respective server's documentation.
Some servers request settings from arbitrary 'sections' of configuration. There is no concept of configuration sections in vim, so you can specify an additional config_sections
dictionary which maps section to a dictionary of config required by the server. For example:
def Settings( **kwargs ):
if kwargs[ 'language' ] == 'java':
return {
'ls': {
'java.format.onType.enabled': True
},
'config_sections': {
'some section': {
'some option': 'some value'
}
}
The sections and options/values are complete server-specific and rarely well documented.
omnifunc
for semantic completionYCM will use your omnifunc
(see :h omnifunc
in Vim) as a source for semantic completions if it does not have a native semantic completion engine for your file's filetype. Vim comes with rudimentary omnifuncs for various languages like Ruby, PHP, etc. It depends on the language.
You can get a stellar omnifunc for Ruby with Eclim. Just make sure you have the latest Eclim installed and configured (this means Eclim >= 2.2.*
and Eclipse >= 4.2.*
).
After installing Eclim remember to create a new Eclipse project within your application by typing :ProjectCreate <path-to-your-project> -n ruby
inside vim and don't forget to have let g:EclimCompletionMethod = 'omnifunc'
in your vimrc. This will make YCM and Eclim play nice; YCM will use Eclim's omnifuncs as the data source for semantic completions and provide the auto-triggering and subsequence-based matching (and other YCM features) on top of it.
You have two options here: writing an omnifunc
for Vim's omnicomplete system that YCM will then use through its omni-completer, or a custom completer for YCM using the Completer API.
Here are the differences between the two approaches:
If you want to use the omnifunc
system, see the relevant Vim docs with :h complete-functions
. For the Completer API, see the API docs.
If you want to upstream your completer into YCM's source, you should use the Completer API.
YCM will display diagnostic notifications for the C-family, C#, Go, Java, JavaScript, Rust and TypeScript languages. Since YCM continuously recompiles your file as you type, you'll get notified of errors and warnings in your file as fast as possible.
Here are the various pieces of the diagnostic UI:
gvim
and a red background in vim
).The new diagnostics (if any) will be displayed the next time you press any key on the keyboard. So if you stop typing and just wait for the new diagnostics to come in, that will not work. You need to press some key for the GUI to update.
Having to press a key to get the updates is unfortunate, but cannot be changed due to the way Vim internals operate; there is no way that a background task can update Vim's GUI after it has finished running. You have to press a key. This will make YCM check for any pending diagnostics updates.
You can force a full, blocking compilation cycle with the :YcmForceCompileAndDiagnostics
command (you may want to map that command to a key; try putting nnoremap <F5> :YcmForceCompileAndDiagnostics<CR>
in your vimrc). Calling this command will force YCM to immediately recompile your file and display any new diagnostics it encounters. Do note that recompilation with this command may take a while and during this time the Vim GUI will be blocked.
YCM will display a short diagnostic message when you move your cursor to the line with the error. You can get a detailed diagnostic message with the <leader>d
key mapping (can be changed in the options) YCM provides when your cursor is on the line with the diagnostic.
You can also see the full diagnostic message for all the diagnostics in the current file in Vim's locationlist
, which can be opened with the :lopen
and :lclose
commands (make sure you have set let g:ycm_always_populate_location_list = 1
in your vimrc). A good way to toggle the display of the locationlist
with a single key mapping is provided by another (very small) Vim plugin called ListToggle (which also makes it possible to change the height of the locationlist
window), also written by yours truly.
You can change the styling for the highlighting groups YCM uses. For the signs in the Vim gutter, the relevant groups are:
YcmErrorSign
, which falls back to group SyntasticErrorSign
and then error
if they existYcmWarningSign
, which falls back to group SyntasticWarningSign
and then todo
if they existYou can also style the line that has the warning/error with these groups:
YcmErrorLine
, which falls back to group SyntasticErrorLine
if it existsYcmWarningLine
, which falls back to group SyntasticWarningLine
if it existsNote that the line highlighting groups only work when the g:ycm_enable_diagnostic_signs
option is set. If you want highlighted lines but no signs in the Vim gutter, set the signcolumn
option to no
in your vimrc:
set signcolumn=no
The syntax groups used to highlight regions of text with errors/warnings:
YcmErrorSection
, which falls back to group SyntasticError
if it exists and then SpellBad
YcmWarningSection
, which falls back to group SyntasticWarning
if it exists and then SpellCap
Here's how you'd change the style for a group:
highlight YcmErrorLine guibg=#3f0000
This feature requires Vim and is not supported in Neovim
YCM provides a way to search for and jump to a symbol in the current project or document when using supported languages.
You can search for symbols in the current workspace when the GoToSymbol
request is supported and the current document when GoToDocumentOutline
is supported.
Here's a quick demo:
As you can see, you can type and YCM filters down the list as you type. The current set of matches are displayed in a popup window in the centre of the screen and you can select an entry with the keyboard, to jump to that position. Any matches are then added to the quickfix list.
To enable:
nmap <something> <Plug>(YCMFindSymbolInWorkspace)
nmap <something> <Plug>(YCMFindSymbolInDocument)
e.g.
nmap <leader>yfw <Plug>(YCMFindSymbolInWorkspace)
nmap <leader>yfd <Plug>(YCMFindSymbolInDocument)
When searching, YCM opens a prompt buffer at the top of the screen for the input, and puts you in insert mode. This means that you can hit <Esc>
to go into normal mode and use any other input commands that are supported in prompt buffers. As you type characters, the search is updated.
While the popup is open, the following keys are intercepted:
<C-j>
, <Down>
, <C-n>
, <Tab>
- select the next item<C-k>
, <Up>
, <C-p>
, <S-Tab>
- select the previous item<PageUp>
, <kPageUp>
- jump up one screenful of items<PageDown>
, <kPageDown>
- jump down one screenful of items<Home>
, <kHome>
- jump to first item<End>
, <kEnd>
- jump to last item<CR>
- jump to the selected item<C-c>
cancel/dismiss the popupThe search is also cancelled if you leave the prompt buffer window at any time, so you can use window commands <C-w>...
for example.
NOTE: Pressing <Esc>
does not close the popup - you must use Ctrl-c
for that, or use a window command (e.g. <Ctrl-w>j
) or the mouse to leave the prompt buffer window.
:YcmRestartServer
commandIf the ycmd completion server suddenly stops for some reason, you can restart it with this command.
:YcmForceCompileAndDiagnostics
commandCalling this command will force YCM to immediately recompile your file and display any new diagnostics it encounters. Do note that recompilation with this command may take a while and during this time the Vim GUI will be blocked.
You may want to map this command to a key; try putting nnoremap <F5> :YcmForceCompileAndDiagnostics<CR>
in your vimrc.
:YcmDiags
commandCalling this command will fill Vim's locationlist
with errors or warnings if any were detected in your file and then open it. If a given error or warning can be fixed by a call to :YcmCompleter FixIt
, then (FixIt available)
is appended to the error or warning text. See the FixIt
completer subcommand for more information.
NOTE: The absence of (FixIt available)
does not strictly imply a fix-it is not available as not all completers are able to provide this indication. For example, the c-sharp completer provides many fix-its but does not add this additional indication.
The g:ycm_open_loclist_on_ycm_diags
option can be used to prevent the location list from opening, but still have it filled with new diagnostic data. See the Options section for details.
:YcmShowDetailedDiagnostic
commandThis command shows the full diagnostic text when the user's cursor is on the line with the diagnostic.
:YcmDebugInfo
commandThis will print out various debug information for the current file. Useful to see what compile commands will be used for the file if you're using the semantic completion engine.
:YcmToggleLogs
commandThis command presents the list of logfiles created by YCM, the ycmd server, and the semantic engine server for the current filetype, if any. One of these logfiles can be opened in the editor (or closed if already open) by entering the corresponding number or by clicking on it with the mouse. Additionally, this command can take the logfile names as arguments. Use the <TAB>
key (or any other key defined by the wildchar
option) to complete the arguments or to cycle through them (depending on the value of the wildmode
option). Each logfile given as an argument is directly opened (or closed if already open) in the editor. Only for debugging purposes.
:YcmCompleter
commandThis command gives access to a number of additional IDE-like features in YCM, for things like semantic GoTo, type information, FixIt and refactoring.
This command accepts a range that can either be specified through a selection in one of Vim's visual modes (see :h visual-use
) or on the command line. For instance, :2,5YcmCompleter
will apply the command from line 2 to line 5. This is useful for the Format
subcommand.
Call YcmCompleter
without further arguments for a list of the commands you can call for the current completer.
See the file type feature summary for an overview of the features available for each file type. See the YcmCompleter subcommands section for more information on the available subcommands and their usage.
NOTE: See the docs for the YcmCompleter
command before tackling this section.
The invoked subcommand is automatically routed to the currently active semantic completer, so :YcmCompleter GoToDefinition
will invoke the GoToDefinition
subcommand on the Python semantic completer if the currently active file is a Python one and on the Clang completer if the currently active file is a C-family language one.
You may also want to map the subcommands to something less verbose; for instance, nnoremap <leader>jd :YcmCompleter GoTo<CR>
maps the <leader>jd
sequence to the longer subcommand invocation.
These commands are useful for jumping around and exploring code. When moving the cursor, the subcommands add entries to Vim's jumplist
so you can use CTRL-O
to jump back to where you were before invoking the command (and CTRL-I
to jump forward; see :h jumplist
for details). If there is more than one destination, the quickfix list (see :h quickfix
) is populated with the available locations and opened to full width at the bottom of the screen. You can change this behavior by using the YcmQuickFixOpened
autocommand.
GoToInclude
subcommandLooks up the current line for a header and jumps to it.
Supported in filetypes: c, cpp, objc, objcpp, cuda
GoToDeclaration
subcommandLooks up the symbol under the cursor and jumps to its declaration.
Supported in filetypes: c, cpp, objc, objcpp, cuda, cs, go, java, javascript, python, rust, typescript
GoToDefinition
subcommandLooks up the symbol under the cursor and jumps to its definition.
NOTE: For C-family languages this only works in certain situations, namely when the definition of the symbol is in the current translation unit. A translation unit consists of the file you are editing and all the files you are including with #include
directives (directly or indirectly) in that file.
Supported in filetypes: c, cpp, objc, objcpp, cuda, cs, go, java, javascript, python, rust, typescript
GoTo
subcommandThis command tries to perform the "most sensible" GoTo operation it can. Currently, this means that it tries to look up the symbol under the cursor and jumps to its definition if possible; if the definition is not accessible from the current translation unit, jumps to the symbol's declaration. For C-family languages, it first tries to look up the current line for a header and jump to it. For C#, implementations are also considered and preferred.
Supported in filetypes: c, cpp, objc, objcpp, cuda, cs, go, java, javascript, python, rust, typescript
GoToImprecise
subcommandWARNING: This command trades correctness for speed!
Same as the GoTo
command except that it doesn't recompile the file with libclang before looking up nodes in the AST. This can be very useful when you're editing files that take long to compile but you know that you haven't made any changes since the last parse that would lead to incorrect jumps. When you're just browsing around your codebase, this command can spare you quite a bit of latency.
Supported in filetypes: c, cpp, objc, objcpp, cuda
GoToSymbol <symbol query>
subcommandFinds the definition of all symbols matching a specified string. Note that this does not use any sort of smart/fuzzy matching. However, an interactive symbol search is also available.
Supported in filetypes: c, cpp, objc, objcpp, cuda, cs, java, javascript, python, typescript
GoToReferences
subcommandThis command attempts to find all of the references within the project to the identifier under the cursor and populates the quickfix list with those locations.
Supported in filetypes: c, cpp, objc, objcpp, cuda, java, javascript, python, typescript, rust
GoToImplementation
subcommandLooks up the symbol under the cursor and jumps to its implementation (i.e. non-interface). If there are multiple implementations, instead provides a list of implementations to choose from.
Supported in filetypes: cs, go, java, rust, typescript, javascript
GoToImplementationElseDeclaration
subcommandLooks up the symbol under the cursor and jumps to its implementation if one, else jump to its declaration. If there are multiple implementations, instead provides a list of implementations to choose from.
Supported in filetypes: cs
GoToType
subcommandLooks up the symbol under the cursor and jumps to the definition of its type e.g. if the symbol is an object, go to the definition of its class.
Supported in filetypes: go, java, javascript, typescript
GoToDocumentOutline
subcommandProvides a list of symbols in current document, in the quickfix list. See also interactive symbol search.
Supported in filetypes: c, cpp, objc, objcpp, cuda, go, java, rust
GoToCallers
and GoToCallees
subcommandsPopulate the quickfix list with the callers, or callees respectively, of the function associated with the current cursor position. The semantics of this differ depending on the filetype and language server.
Only supported for LSP servers which provide the callHierarchyProvider
capability.
These commands are useful for finding static information about the code, such as the types of variables, viewing declarations and documentation strings.
GetType
subcommandEchos the type of the variable or method under the cursor, and where it differs, the derived type.
For example:
std::string s;
Invoking this command on s
returns std::string => std::basic_string<char>
NOTE: Causes re-parsing of the current translation unit.
Supported in filetypes: c, cpp, objc, objcpp, cuda, java, javascript, go, python, typescript, rust
GetTypeImprecise
subcommandWARNING: This command trades correctness for speed!
Same as the GetType
command except that it doesn't recompile the file with libclang before looking up nodes in the AST. This can be very useful when you're editing files that take long to compile but you know that you haven't made any changes since the last parse that would lead to incorrect type. When you're just browsing around your codebase, this command can spare you quite a bit of latency.
Supported in filetypes: c, cpp, objc, objcpp, cuda
GetParent
subcommandEchos the semantic parent of the point under the cursor.
The semantic parent is the item that semantically contains the given position.
For example:
class C {
void f();
};
void C::f() {
}
In the out-of-line definition of C::f
, the semantic parent is the class C
, of which this function is a member.
In the example above, both declarations of C::f
have C
as their semantic context, while the lexical context of the first C::f
is C
and the lexical context of the second C::f
is the translation unit.
For global declarations, the semantic parent is the translation unit.
NOTE: Causes re-parsing of the current translation unit.
Supported in filetypes: c, cpp, objc, objcpp, cuda
GetDoc
subcommandDisplays the preview window populated with quick info about the identifier under the cursor. Depending on the file type, this includes things like:
Supported in filetypes: c, cpp, objc, objcpp, cuda, cs, go, java, javascript, python, typescript, rust
GetDocImprecise
subcommandWARNING: This command trades correctness for speed!
Same as the GetDoc
command except that it doesn't recompile the file with libclang before looking up nodes in the AST. This can be very useful when you're editing files that take long to compile but you know that you haven't made any changes since the last parse that would lead to incorrect docs. When you're just browsing around your codebase, this command can spare you quite a bit of latency.
Supported in filetypes: c, cpp, objc, objcpp, cuda
These commands make changes to your source code in order to perform refactoring or code correction. YouCompleteMe does not perform any action which cannot be undone, and never saves or writes files to the disk.
FixIt
subcommandWhere available, attempts to make changes to the buffer to correct diagnostics on the current line. Where multiple suggestions are available (such as when there are multiple ways to resolve a given warning, or where multiple diagnostics are reported for the current line), the options are presented and one can be selected.
Completers which provide diagnostics may also provide trivial modifications to the source in order to correct the diagnostic. Examples include syntax errors such as missing trailing semi-colons, spurious characters, or other errors which the semantic engine can deterministically suggest corrections.
If no fix-it is available for the current line, or there is no diagnostic on the current line, this command has no effect on the current buffer. If any modifications are made, the number of changes made to the buffer is echo'd and the user may use the editor's undo command to revert.
When a diagnostic is available, and g:ycm_echo_current_diagnostic
is set to 1, then the text (FixIt)
is appended to the echo'd diagnostic when the completer is able to add this indication. The text (FixIt available)
is also appended to the diagnostic text in the output of the :YcmDiags
command for any diagnostics with available fix-its (where the completer can provide this indication).
NOTE: Causes re-parsing of the current translation unit.
Supported in filetypes: c, cpp, objc, objcpp, cuda, cs, go, java, javascript, rust, typescript
RefactorRename <new name>
subcommandIn supported file types, this command attempts to perform a semantic rename of the identifier under the cursor. This includes renaming declarations, definitions and usages of the identifier, or any other language-appropriate action. The specific behavior is defined by the semantic engine in use.
Similar to FixIt
, this command applies automatic modifications to your source files. Rename operations may involve changes to multiple files, which may or may not be open in Vim buffers at the time. YouCompleteMe handles all of this for you. The behavior is described in the following section.
Supported in filetypes: c, cpp, objc, objcpp, cuda, java, javascript, python, typescript, rust, cs
When a Refactor or FixIt command touches multiple files, YouCompleteMe attempts to apply those modifications to any existing open, visible buffer in the current tab. If no such buffer can be found, YouCompleteMe opens the file in a new small horizontal split at the top of the current window, applies the change, and then hides the window. NOTE: The buffer remains open, and must be manually saved. A confirmation dialog is opened prior to doing this to remind you that this is about to happen.
Once the modifications have been made, the quickfix list (see :help quickfix
) is populated with the locations of all modifications. This can be used to review all automatic changes made by using :copen
. Typically, use the CTRL-W <enter>
combination to open the selected file in a new split. It is possible to customize how the quickfix window is opened by using the YcmQuickFixOpened
autocommand.
The buffers are not saved automatically. That is, you must save the modified buffers manually after reviewing the changes from the quickfix list. Changes can be undone using Vim's powerful undo features (see :help undo
). Note that Vim's undo is per-buffer, so to undo all changes, the undo commands must be applied in each modified buffer separately.
NOTE: While applying modifications, Vim may find files which are already open and have a swap file. The command is aborted if you select Abort or Quit in any such prompts. This leaves the Refactor operation partially complete and must be manually corrected using Vim's undo features. The quickfix list is not populated in this case. Inspect :buffers
or equivalent (see :help buffers
) to see the buffers that were opened by the command.
Format
subcommandThis command formats the whole buffer or some part of it according to the value of the Vim options shiftwidth
and expandtab
(see :h 'sw'
and :h et
respectively). To format a specific part of your document, you can either select it in one of Vim's visual modes (see :h visual-use
) and run the command or directly enter the range on the command line, e.g. :2,5YcmCompleter Format
to format it from line 2 to line 5.
Supported in filetypes: c, cpp, objc, objcpp, cuda, java, javascript, go, typescript, rust, cs
OrganizeImports
subcommandThis command removes unused imports and sorts imports in the current file. It can also group imports from the same module in TypeScript and resolves imports in Java.
Supported in filetypes: java, javascript, typescript
These commands are for general administration, rather than IDE-like features. They cover things like the semantic engine server instance and compilation flags.
ExecuteCommand <args>
subcommandSome LSP completers (currently only Java completers) support executing server specific commands. Consult the jdt.ls documentation to find out what commands are supported and which arguments are expected.
The support for ExecuteCommand
was implemented to support plugins like Vimspector to debug java, but isn't limited to that specific use case.
RestartServer
subcommandRestarts the downstream semantic engine server for those semantic engines that work as separate servers that YCM talks to.
Supported in filetypes: c, cpp, objc, objcpp, cuda, cs, go, java, javascript, rust, typescript
ReloadSolution
subcommandInstruct the Omnisharp-Roslyn server to clear its cache and reload all files from disk. This is useful when files are added, removed, or renamed in the solution, files are changed outside of Vim, or whenever Omnisharp-Roslyn cache is out-of-sync.
Supported in filetypes: cs
youcompleteme#GetErrorCount
functionGet the number of YCM Diagnostic errors. If no errors are present, this function returns 0.
For example:
call youcompleteme#GetErrorCount()
Both this function and youcompleteme#GetWarningCount
can be useful when integrating YCM with other Vim plugins. For example, a lightline user could add a diagnostics section to their statusline which would display the number of errors and warnings.
youcompleteme#GetWarningCount
functionGet the number of YCM Diagnostic warnings. If no warnings are present, this function returns 0.
For example:
call youcompleteme#GetWarningCount()
youcompleteme#GetCommandResponse( ... )
functionRun a completer subcommand and return the result as a string. This can be useful for example to display the GetGoc
output in a popup window, e.g.:
let s:ycm_hover_popup = -1
function s:Hover()
let response = youcompleteme#GetCommandResponse( 'GetDoc' )
if response == ''
return
endif
call popup_hide( s:ycm_hover_popup )
let s:ycm_hover_popup = popup_atcursor( balloon_split( response ), {} )
endfunction
" CursorHold triggers in normal mode after a delay
autocmd CursorHold * call s:Hover()
" Or, if you prefer, a mapping:
nnoremap <silent> <leader>D :call <SID>Hover()<CR>
NOTE: This is only an example, for real hover support, see g:ycm_auto_hover
.
If the completer subcommand result is not a string (for example, it's a FixIt or a Location), or if the completer subcommand raises an error, an empty string is returned, so that calling code does not have to check for complex error conditions.
The arguments to the function are the same as the arguments to the :YcmCompleter
ex command, e.g. the name of the subcommand, followed by any additional subcommand arguments. As with the YcmCompleter
command, if the first argument is ft=<filetype>
the request is targeted at the specified filetype completer. This is an advanced usage and not necessary in most cases.
NOTE: The request is run synchronously and blocks Vim until the response is received, so we do not recommend running this as part of an autocommand that triggers frequently.
youcompleteme#GetCommandResponseAsync( callback, ... )
functionThis works exactly like youcompleteme#GetCommandResponse
, except that instead of returning the result, you supply a callback
argument. This argument must be a FuncRef
to a function taking a single argument response
. This callback will be called with the command response at some point later, or immediately.
As with youcompleteme#GetCommandResponse()
, this function will call the callback with ''
(an empty string) if the request is not sent, or if there was some sort of error.
Here's an example that's similar to the one above:
let s:ycm_hover_popup = -1
function! s:ShowDataPopup( response ) abort
if response == ''
return
endif
call popup_hide( s:ycm_hover_popup )
let s:ycm_hover_popup = popup_atcursor( balloon_split( response ), {} )
endfunction
function! s:GetData() abort
call youcompleteme#GetCommandResponseAsync(
\ function( 's:ShowDataPopup' ),
\ 'GetDoc' )
endfunction
autocommand CursorHold * call s:GetData()
Again, see g:ycm_auto_hover
for proper hover support.
NOTE: The callback may be called immediately, in the stack frame that called this function.
NOTE: Only one command request can be outstanding at once. Attempting to request a second responses while the first is outstanding will result in the second callback being immediately called with ''
.
YcmLocationOpened
autocommandThis User
autocommand is fired when YCM opens the location list window in response to the YcmDiags
command. By default, the location list window is opened to the bottom of the current window and its height is set to fit all entries. This behavior can be overridden by using the YcmLocationOpened
autocommand which is triggered while the cursor is in the location list window. For instance:
function! s:CustomizeYcmLocationWindow()
" Move the window to the top of the screen.
wincmd K
" Set the window height to 5.
5wincmd _
" Switch back to working window.
wincmd p
endfunction
autocmd User YcmLocationOpened call s:CustomizeYcmLocationWindow()
YcmQuickFixOpened
autocommandThis User
autocommand is fired when YCM opens the quickfix window in response to the GoTo*
and RefactorRename
subcommands. By default, the quickfix window is opened to full width at the bottom of the screen and its height is set to fit all entries. This behavior can be overridden by using the YcmQuickFixOpened
autocommand which is triggered while the cursor is in the quickfix window. For instance:
function! s:CustomizeYcmQuickFixWindow()
" Move the window to the top of the screen.
wincmd K
" Set the window height to 5.
5wincmd _
endfunction
autocmd User YcmQuickFixOpened call s:CustomizeYcmQuickFixWindow()
All options have reasonable defaults so if the plug-in works after installation you don't need to change any options. These options can be configured in your vimrc script by including a line like this:
let g:ycm_min_num_of_chars_for_completion = 1
Note that after changing an option in your vimrc script you have to restart ycmd with the :YcmRestartServer
command for the changes to take effect.
g:ycm_min_num_of_chars_for_completion
optionThis option controls the number of characters the user needs to type before identifier-based completion suggestions are triggered. For example, if the option is set to 2
, then when the user types a second alphanumeric character after a whitespace character, completion suggestions will be triggered. This option is NOT used for semantic completion.
Setting this option to a high number like 99
effectively turns off the identifier completion engine and just leaves the semantic engine.
Default: 2
let g:ycm_min_num_of_chars_for_completion = 2
g:ycm_min_num_identifier_candidate_chars
optionThis option controls the minimum number of characters that a completion candidate coming from the identifier completer must have to be shown in the popup menu.
A special value of 0
means there is no limit.
NOTE: This option only applies to the identifier completer; it has no effect on the various semantic completers.
Default: 0
let g:ycm_min_num_identifier_candidate_chars = 0
g:ycm_max_num_candidates
optionThis option controls the maximum number of semantic completion suggestions shown in the completion menu. This only applies to suggestions from semantic completion engines; see the g:ycm_max_identifier_candidates
option to limit the number of suggestions from the identifier-based engine.
A special value of 0
means there is no limit.
NOTE: Setting this option to 0
or to a value greater than 100
is not recommended as it will slow down completion when there are a very large number of suggestions.
Default: 50
let g:ycm_max_num_candidates = 50
g:ycm_max_num_candidates_to_detail
optionSome completion engines require completion candidates to be 'resolved' in order to get detailed info such as inline documentation, method signatures etc. This information is displayed by YCM in the preview window, or if completeopt
contains popup
, in the info popup next to the completion menu.
By default, if the info popup is in use, and there are more than 10 candidates, YCM will defer resolving candidates until they are selected in the completion menu. Otherwise, YCM must resolve the details upfront, which can be costly.
If neither popup
nor preview
are in completeopt
, YCM disables resolving altogether as the information would not be displayed.
This setting can be used to override these defaults and controls the number of completion candidates that should be resolved upfront. Typically users do not need to change this, as YCM will work out an appropriate value based on your completeopt
and g:ycm_add_preview_to_completeopt
settings. However, you may override this calculation by setting this value to a number:
-1
- Resolve all candidates up front0
- Never resolve any candidates up front.> 0
- Resolve up to this many candidates up front. If the number of candidates is greater than this value, no candidates are resolved.In the later two cases, if completeopt
contains popup
, then candidates are resolved on demand asynchronously.
Default:
0
if neither popup
nor preview
are in completeopt
.10
if popup
is in completeopt.-1
if preview
is in completeopt.Example:
let g:ycm_max_num_candidates_to_detail = 0
g:ycm_max_num_identifier_candidates
optionThis option controls the maximum number of completion suggestions from the identifier-based engine shown in the completion menu.
A special value of 0
means there is no limit.
NOTE: Setting this option to 0
or to a value greater than 100
is not recommended as it will slow down completion when there are a very large number of suggestions.
Default: 10
let g:ycm_max_num_identifier_candidates = 10
g:ycm_auto_trigger
optionWhen set to 0
, this option turns off YCM's identifier completer (the as-you-type popup) and the semantic triggers (the popup you'd get after typing .
or ->
in say C++). You can still force semantic completion with the <C-Space>
shortcut.
If you want to just turn off the identifier completer but keep the semantic triggers, you should set g:ycm_min_num_of_chars_for_completion
to a high number like 99
.
Default: 1
let g:ycm_auto_trigger = 1
g:ycm_filetype_whitelist
optionThis option controls for which Vim filetypes (see :h filetype
) should YCM be turned on. The option value should be a Vim dictionary with keys being filetype strings (like python
, cpp
, etc.) and values being unimportant (the dictionary is used like a hash set, meaning that only the keys matter).
The *
key is special and matches all filetypes. By default, the whitelist contains only this *
key.
YCM also has a g:ycm_filetype_blacklist
option that lists filetypes for which YCM shouldn't be turned on. YCM will work only in filetypes that both the whitelist and the blacklist allow (the blacklist "allows" a filetype by not having it as a key).
For example, let's assume you want YCM to work in files with the cpp
filetype. The filetype should then be present in the whitelist either directly (cpp
key in the whitelist) or indirectly through the special *
key. It should not be present in the blacklist.
Filetypes that are blocked by the either of the lists will be completely ignored by YCM, meaning that neither the identifier-based completion engine nor the semantic engine will operate in them.
You can get the filetype of the current file in Vim with :set ft?
.
Default: {'*': 1}
let g:ycm_filetype_whitelist = {'*': 1}
** Completion in buffers with no filetype **
There is one exception to the above rule. YCM supports completion in buffers with no filetype set, but this must be explicitly whitelisted. To identify buffers with no filetype, we use the ycm_nofiletype
pseudo-filetype. To enable completion in buffers with no filetype, set:
let g:ycm_filetype_whitelist = {
\ '*': 1,
\ 'ycm_nofiletype': 1
\ }
g:ycm_filetype_blacklist
optionThis option controls for which Vim filetypes (see :h filetype
) should YCM be turned off. The option value should be a Vim dictionary with keys being filetype strings (like python
, cpp
, etc.) and values being unimportant (the dictionary is used like a hash set, meaning that only the keys matter).
See the g:ycm_filetype_whitelist
option for more details on how this works.
Default: [see next line]
let g:ycm_filetype_blacklist = {
\ 'tagbar': 1,
\ 'notes': 1,
\ 'markdown': 1,
\ 'netrw': 1,
\ 'unite': 1,
\ 'text': 1,
\ 'vimwiki': 1,
\ 'pandoc': 1,
\ 'infolog': 1,
\ 'leaderf': 1,
\ 'mail': 1
\}
In addition, ycm_nofiletype
(representing buffers with no filetype set) is blacklisted if ycm_nofiletype
is not explicitly whitelisted (using g:ycm_filetype_whitelist
).
g:ycm_filetype_specific_completion_to_disable
optionThis option controls for which Vim filetypes (see :h filetype
) should the YCM semantic completion engine be turned off. The option value should be a Vim dictionary with keys being filetype strings (like python
, cpp
, etc.) and values being unimportant (the dictionary is used like a hash set, meaning that only the keys matter). The listed filetypes will be ignored by the YCM semantic completion engine, but the identifier-based completion engine will still trigger in files of those filetypes.
Note that even if semantic completion is not turned off for a specific filetype, you will not get semantic completion if the semantic engine does not support that filetype.
You can get the filetype of the current file in Vim with :set ft?
.
Default: [see next line]
let g:ycm_filetype_specific_completion_to_disable = {
\ 'gitcommit': 1
\}
g:ycm_filepath_blacklist
optionThis option controls for which Vim filetypes (see :h filetype
) should filepath completion be disabled. The option value should be a Vim dictionary with keys being filetype strings (like python
, cpp
, etc.) and values being unimportant (the dictionary is used like a hash set, meaning that only the keys matter).
The *
key is special and matches all filetypes. Use this key if you want to completely disable filepath completion:
let g:ycm_filepath_blacklist = {'*': 1}
You can get the filetype of the current file in Vim with :set ft?
.
Default: [see next line]
let g:ycm_filepath_blacklist = {
\ 'html': 1,
\ 'jsx': 1,
\ 'xml': 1,
\}
g:ycm_show_diagnostics_ui
optionWhen set, this option turns on YCM's diagnostic display features. See the Diagnostic display section in the User Manual for more details.
Specific parts of the diagnostics UI (like the gutter signs, text highlighting, diagnostic echo and auto location list population) can be individually turned on or off. See the other options below for details.
Note that YCM's diagnostics UI is only supported for C-family languages.
When set, this option also makes YCM remove all Syntastic checkers set for the c
, cpp
, objc
, objcpp
, and cuda
filetypes since this would conflict with YCM's own diagnostics UI.
If you're using YCM's identifier completer in C-family languages but cannot use the clang-based semantic completer for those languages and want to use the GCC Syntastic checkers, unset this option.
Default: 1
let g:ycm_show_diagnostics_ui = 1
g:ycm_error_symbol
optionYCM will use the value of this option as the symbol for errors in the Vim gutter.
This option is part of the Syntastic compatibility layer; if the option is not set, YCM will fall back to the value of the g:syntastic_error_symbol
option before using this option's default.
Default: >>
let g:ycm_error_symbol = '>>'
g:ycm_warning_symbol
optionYCM will use the value of this option as the symbol for warnings in the Vim gutter.
This option is part of the Syntastic compatibility layer; if the option is not set, YCM will fall back to the value of the g:syntastic_warning_symbol
option before using this option's default.
Default: >>
let g:ycm_warning_symbol = '>>'
g:ycm_enable_diagnostic_signs
optionWhen this option is set, YCM will put icons in Vim's gutter on lines that have a diagnostic set. Turning this off will also turn off the YcmErrorLine
and YcmWarningLine
highlighting.
This option is part of the Syntastic compatibility layer; if the option is not set, YCM will fall back to the value of the g:syntastic_enable_signs
option before using this option's default.
Default: 1
let g:ycm_enable_diagnostic_signs = 1
g:ycm_enable_diagnostic_highlighting
optionWhen this option is set, YCM will highlight regions of text that are related to the diagnostic that is present on a line, if any.
This option is part of the Syntastic compatibility layer; if the option is not set, YCM will fall back to the value of the g:syntastic_enable_highlighting
option before using this option's default.
Default: 1
let g:ycm_enable_diagnostic_highlighting = 1
g:ycm_echo_current_diagnostic
optionWhen this option is set, YCM will echo the text of the diagnostic present on the current line when you move your cursor to that line. If a FixIt
is available for the current diagnostic, then (FixIt)
is appended.
This option is part of the Syntastic compatibility layer; if the option is not set, YCM will fall back to the value of the g:syntastic_echo_current_error
option before using this option's default.
Default: 1
let g:ycm_echo_current_diagnostic = 1
g:ycm_auto_hover
optionThis option controls whether or not YCM shows documentation in a popup at the cursor location after a short delay. Only supported in Vim.
When this option is set to 'CursorHold'
, the popup is displayed on the CursorHold
autocommand. See :help CursorHold
for the details, but this means that it is displayed after updatetime
milliseconds. When set to an empty string, the popup is not automatically displayed.
In addition to this setting, there is the <plug>(YCMHover)
mapping, which can be used to manually trigger or hide the popup (it works like a toggle). For example:
nmap <leader>D <plug>(YCMHover)
After dismissing the popup with this mapping, it will not be automatically triggered again until the cursor is moved (i.e. CursorMoved
autocommand).
The displayed documentation depends on what the completer for the current language supports. It's selected heuristically in this order of preference:
GetHover
with markdown
syntaxGetDoc
with no syntaxGetType
with the syntax of the current file.You can customise this by manually setting up b:ycm_hover
to your liking. This buffer-local variable can be set to a dictionary with the following keys:
command
: The YCM completer subcommand which should be run on hoversyntax
: The syntax to use (as in set syntax=
) in the popup window for highlighting.For example, to use C/C++ syntax highlighting in the popup for C-family languages, add something like this to your vimrc:
augroup MyYCMCustom
autocmd!
autocmd FileType c,cpp let b:ycm_hover = {
\ 'command': 'GetDoc',
\ 'syntax': &filetype
\ }
augroup END
Default: 'CursorHold'
g:ycm_filter_diagnostics
optionThis option controls which diagnostics will be rendered by YCM. This option holds a dictionary of key-values, where the keys are Vim's filetype strings delimited by commas and values are dictionaries describing the filter.
A filter is a dictionary of key-values, where the keys are the type of filter, and the value is a list of arguments to that filter. In the case of just a single item in the list, you may omit the brackets and just provide the argument directly. If any filter matches a diagnostic, it will be dropped and YCM will not render it.
The following filter types are supported:
re.search
, not re.match
)level: "error"
will remove all errors from the diagnostics.NOTE: The regex syntax is NOT Vim's, it's Python's.
Default: {}
The following example will do, for java filetype only:
ta<something>co
let g:ycm_filter_diagnostics = {
\ "java": {
\ "regex": [ "ta.+co", ... ],
\ "level": "error",
\ ...
\ }
\ }
g:ycm_always_populate_location_list
optionWhen this option is set, YCM will populate the location list automatically every time it gets new diagnostic data. This option is off by default so as not to interfere with other data you might have placed in the location list.
See :help location-list
in Vim to learn more about the location list.
This option is part of the Syntastic compatibility layer; if the option is not set, YCM will fall back to the value of the g:syntastic_always_populate_loc_list
option before using this option's default.
Note: if YCM's errors aren't visible, it might be that YCM is updating an older location list. See :help :lhistory
and :lolder
.
Default: 0
let g:ycm_always_populate_location_list = 0
g:ycm_open_loclist_on_ycm_diags
optionWhen this option is set, :YcmDiags
will automatically open the location list after forcing a compilation and filling the list with diagnostic data.
See :help location-list
in Vim to learn more about the location list.
Default: 1
let g:ycm_open_loclist_on_ycm_diags = 1
g:ycm_complete_in_comments
optionWhen this option is set to 1
, YCM will show the completion menu even when typing inside comments.
Default: 0
let g:ycm_complete_in_comments = 0
g:ycm_complete_in_strings
optionWhen this option is set to 1
, YCM will show the completion menu even when typing inside strings.
Note that this is turned on by default so that you can use the filename completion inside strings. This is very useful for instance in C-family files where typing #include "
will trigger the start of filename completion. If you turn off this option, you will turn off filename completion in such situations as well.
Default: 1
let g:ycm_complete_in_strings = 1
g:ycm_collect_identifiers_from_comments_and_strings
optionWhen this option is set to 1
, YCM's identifier completer will also collect identifiers from strings and comments. Otherwise, the text in comments and strings will be ignored.
Default: 0
let g:ycm_collect_identifiers_from_comments_and_strings = 0
g:ycm_collect_identifiers_from_tags_files
optionWhen this option is set to 1
, YCM's identifier completer will also collect identifiers from tags files. The list of tags files to examine is retrieved from the tagfiles()
Vim function which examines the tags
Vim option. See :h 'tags'
for details.
YCM will re-index your tags files if it detects that they have been modified.
The only supported tag format is the Exuberant Ctags format. The format from "plain" ctags is NOT supported. Ctags needs to be called with the --fields=+l
option (that's a lowercase L
, not a one) because YCM needs the language:<lang>
field in the tags output.
See the FAQ for pointers if YCM does not appear to read your tag files.
This option is off by default because it makes Vim slower if your tags are on a network directory.
Default: 0
let g:ycm_collect_identifiers_from_tags_files = 0
g:ycm_seed_identifiers_with_syntax
optionWhen this option is set to 1
, YCM's identifier completer will seed its identifier database with the keywords of the programming language you're writing.
Since the keywords are extracted from the Vim syntax file for the filetype, all keywords may not be collected, depending on how the syntax file was written. Usually at least 95% of the keywords are successfully extracted.
Default: 0
let g:ycm_seed_identifiers_with_syntax = 0
g:ycm_extra_conf_vim_data
optionIf you're using semantic completion for C-family files, this option might come handy; it's a way of sending data from Vim to your Settings
function in your .ycm_extra_conf.py
file.
This option is supposed to be a list of VimScript expression strings that are evaluated for every request to the ycmd server and then passed to your Settings
function as a client_data
keyword argument.
For instance, if you set this option to ['v:version']
, your Settings
function will be called like this:
# The '801' value is of course contingent on Vim 8.1; in 8.0 it would be '800'
Settings( ..., client_data = { 'v:version': 801 } )
So the client_data
parameter is a dictionary mapping Vim expression strings to their values at the time of the request.
The correct way to define parameters for your Settings
function:
def Settings( **kwargs ):
You can then get to client_data
with kwargs['client_data']
.
Default: []
let g:ycm_extra_conf_vim_data = []
g:ycm_server_python_interpreter
optionYCM will by default search for an appropriate Python interpreter on your system. You can use this option to override that behavior and force the use of a specific interpreter of your choosing.
NOTE: This interpreter is only used for the ycmd server. The YCM client running inside Vim always uses the Python interpreter that's embedded inside Vim.
Default: ''
let g:ycm_server_python_interpreter = ''
g:ycm_keep_logfiles
optionWhen this option is set to 1
, YCM and the ycmd completion server will keep the logfiles around after shutting down (they are deleted on shutdown by default).
To see where the logfiles are, call :YcmDebugInfo
.
Default: 0
let g:ycm_keep_logfiles = 0
g:ycm_log_level
optionThe logging level that YCM and the ycmd completion server use. Valid values are the following, from most verbose to least verbose:
debug
info
warning
error
critical
Note that debug
is very verbose.
Default: info
let g:ycm_log_level = 'info'
g:ycm_auto_start_csharp_server
optionWhen set to 1
, the OmniSharp-Roslyn server will be automatically started (once per Vim session) when you open a C# file.
Default: 1
let g:ycm_auto_start_csharp_server = 1
g:ycm_auto_stop_csharp_server
optionWhen set to 1
, the OmniSharp-Roslyn server will be automatically stopped upon closing Vim.
Default: 1
let g:ycm_auto_stop_csharp_server = 1
g:ycm_csharp_server_port
optionWhen g:ycm_auto_start_csharp_server is set to 1
, specifies the port for the OmniSharp-Roslyn server to listen on. When set to 0
uses an unused port provided by the OS.
Default: 0
let g:ycm_csharp_server_port = 0
g:ycm_csharp_insert_namespace_expr
optionBy default, when YCM inserts a namespace, it will insert the using
statement under the nearest using
statement. You may prefer that the using
statement is inserted somewhere, for example, to preserve sorting. If so, you can set this option to override this behavior.
When this option is set, instead of inserting the using
statement itself, YCM will set the global variable g:ycm_namespace_to_insert
to the namespace to insert, and then evaluate this option's value as an expression. The option's expression is responsible for inserting the namespace - the default insertion will not occur.
Default: ''
let g:ycm_csharp_insert_namespace_expr = ''
g:ycm_add_preview_to_completeopt
optionWhen this option is set to 1
, YCM will add the preview
string to Vim's completeopt
option (see :h completeopt
). If your completeopt
option already has preview
set, there will be no effect. Alternatively, when set to popup
and your version of Vim supports popup windows (see :help popup
), the popup
string will be used instead. You can see the current state of your completeopt
setting with :set completeopt?
(yes, the question mark is important).
When preview
is present in completeopt
, YCM will use the preview
window at the top of the file to store detailed information about the current completion candidate (but only if the candidate came from the semantic engine). For instance, it would show the full function prototype and all the function overloads in the window if the current completion is a function name.
When popup
is present in completeopt
, YCM will instead use a popup
window to the side of the completion popup for storing detailed information about the current completion candidate. In addition, YCM may truncate the detailed completion information in order to give the popup sufficient room to display that detailed information.
Default: 0
let g:ycm_add_preview_to_completeopt = 0
g:ycm_autoclose_preview_window_after_completion
optionWhen this option is set to 1
, YCM will auto-close the preview
window after the user accepts the offered completion string. If there is no preview
window triggered because there is no preview
string in completeopt
, this option is irrelevant. See the g:ycm_add_preview_to_completeopt
option for more details.
Default: 0
let g:ycm_autoclose_preview_window_after_completion = 0
g:ycm_autoclose_preview_window_after_insertion
optionWhen this option is set to 1
, YCM will auto-close the preview
window after the user leaves insert mode. This option is irrelevant if g:ycm_autoclose_preview_window_after_completion
is set or if no preview
window is triggered. See the g:ycm_add_preview_to_completeopt
option for more details.
Default: 0
let g:ycm_autoclose_preview_window_after_insertion = 0
g:ycm_max_diagnostics_to_display
optionThis option controls the maximum number of diagnostics shown to the user when errors or warnings are detected in the file. This option is only relevant for the C-family, C#, Java, JavaScript, and TypeScript languages.
A special value of 0
means there is no limit.
Default: 30
let g:ycm_max_diagnostics_to_display = 30
g:ycm_key_list_select_completion
optionThis option controls the key mappings used to select the first completion string. Invoking any of them repeatedly cycles forward through the completion list.
Some users like adding <Enter>
to this list.
Default: ['<TAB>', '<Down>']
let g:ycm_key_list_select_completion = ['<TAB>', '<Down>']
g:ycm_key_list_previous_completion
optionThis option controls the key mappings used to select the previous completion string. Invoking any of them repeatedly cycles backwards through the completion list.
Note that one of the defaults is <S-TAB>
which means Shift-TAB. That mapping will probably only work in GUI Vim (Gvim or MacVim) and not in plain console Vim because the terminal usually does not forward modifier key combinations to Vim.
Default: ['<S-TAB>', '<Up>']
let g:ycm_key_list_previous_completion = ['<S-TAB>', '<Up>']
g:ycm_key_list_stop_completion
optionThis option controls the key mappings used to close the completion menu. This is useful when the menu is blocking the view, when you need to insert the <TAB>
character, or when you want to expand a snippet from UltiSnips and navigate through it.
Default: ['<C-y>']
let g:ycm_key_list_stop_completion = ['<C-y>']
g:ycm_key_invoke_completion
optionThis option controls the key mapping used to invoke the completion menu for semantic completion. By default, semantic completion is triggered automatically after typing .
, ->
and ::
in insert mode (if semantic completion support has been compiled in). This key mapping can be used to trigger semantic completion anywhere. Useful for searching for top-level functions and classes.
Console Vim (not Gvim or MacVim) passes <Nul>
to Vim when the user types <C-Space>
so YCM will make sure that <Nul>
is used in the map command when you're editing in console Vim, and <C-Space>
in GUI Vim. This means that you can just press <C-Space>
in both console and GUI Vim and YCM will do the right thing.
Setting this option to an empty string will make sure no mapping is created.
Default: <C-Space>
let g:ycm_key_invoke_completion = '<C-Space>'
g:ycm_key_detailed_diagnostics
optionThis option controls the key mapping used to show the full diagnostic text when the user's cursor is on the line with the diagnostic. It basically calls :YcmShowDetailedDiagnostic
.
Setting this option to an empty string will make sure no mapping is created.
Default: <leader>d
let g:ycm_key_detailed_diagnostics = '<leader>d'
g:ycm_global_ycm_extra_conf
optionNormally, YCM searches for a .ycm_extra_conf.py
file for compilation flags (see the User Guide for more details on how this works). This option specifies a fallback path to a config file which is used if no .ycm_extra_conf.py
is found.
You can place such a global file anywhere in your filesystem.
Default: ''
let g:ycm_global_ycm_extra_conf = ''
g:ycm_confirm_extra_conf
optionWhen this option is set to 1
YCM will ask once per .ycm_extra_conf.py
file if it is safe to be loaded. This is to prevent execution of malicious code from a .ycm_extra_conf.py
file you didn't write.
To selectively get YCM to ask/not ask about loading certain .ycm_extra_conf.py
files, see the g:ycm_extra_conf_globlist
option.
Default: 1
let g:ycm_confirm_extra_conf = 1
g:ycm_extra_conf_globlist
optionThis option is a list that may contain several globbing patterns. If a pattern starts with a !
all .ycm_extra_conf.py
files matching that pattern will be blacklisted, that is they won't be loaded and no confirmation dialog will be shown. If a pattern does not start with a !
all files matching that pattern will be whitelisted. Note that this option is not used when confirmation is disabled using g:ycm_confirm_extra_conf
and that items earlier in the list will take precedence over the later ones.
Rules:
*
matches everything?
matches any single character[seq]
matches any character in seq[!seq]
matches any char not in seqExample:
let g:ycm_extra_conf_globlist = ['~/dev/*','!~/*']
~/dev
directory so .ycm_extra_conf.py
files from there will be loaded..ycm_extra_conf.py
file from there won't be loaded.~/dev
directory will be blacklisted.NOTE: The glob pattern is first expanded with Python's os.path.expanduser()
and then resolved with os.path.abspath()
before being matched against the filename.
Default: []
let g:ycm_extra_conf_globlist = []
g:ycm_filepath_completion_use_working_dir
optionBy default, YCM's filepath completion will interpret relative paths like ../
as being relative to the folder of the file of the currently active buffer. Setting this option will force YCM to always interpret relative paths as being relative to Vim's current working directory.
Default: 0
let g:ycm_filepath_completion_use_working_dir = 0
g:ycm_semantic_triggers
optionThis option controls the character-based triggers for the various semantic completion engines. The option holds a dictionary of key-values, where the keys are Vim's filetype strings delimited by commas and values are lists of strings, where the strings are the triggers.
Setting key-value pairs on the dictionary adds semantic triggers to the internal default set (listed below). You cannot remove the default triggers, only add new ones.
A "trigger" is a sequence of one or more characters that trigger semantic completion when typed. For instance, C++ (cpp
filetype) has .
listed as a trigger. So when the user types foo.
, the semantic engine will trigger and serve foo
's list of member functions and variables. Since C++ also has ->
listed as a trigger, the same thing would happen when the user typed foo->
.
It's also possible to use a regular expression as a trigger. You have to prefix your trigger with re!
to signify it's a regex trigger. For instance, re!\w+\.
would only trigger after the \w+\.
regex matches.
NOTE: The regex syntax is NOT Vim's, it's Python's.
Default: [see next line]
let g:ycm_semantic_triggers = {
\ 'c': ['->', '.'],
\ 'objc': ['->', '.', 're!\[[_a-zA-Z]+\w*\s', 're!^\s*[^\W\d]\w*\s',
\ 're!\[.*\]\s'],
\ 'ocaml': ['.', '#'],
\ 'cpp,cuda,objcpp': ['->', '.', '::'],
\ 'perl': ['->'],
\ 'php': ['->', '::'],
\ 'cs,d,elixir,go,groovy,java,javascript,julia,perl6,python,scala,typescript,vb': ['.'],
\ 'ruby,rust': ['.', '::'],
\ 'lua': ['.', ':'],
\ 'erlang': [':'],
\ }
g:ycm_cache_omnifunc
optionSome omnicompletion engines do not work well with the YCM cache—in particular, they might not produce all possible results for a given prefix. By unsetting this option you can ensure that the omnicompletion engine is re-queried on every keypress. That will ensure all completions will be presented, but might cause stuttering and lagginess if the omnifunc is slow.
Default: 1
let g:ycm_cache_omnifunc = 1
g:ycm_use_ultisnips_completer
optionBy default, YCM will query the UltiSnips plugin for possible completions of snippet triggers. This option can turn that behavior off.
Default: 1
let g:ycm_use_ultisnips_completer = 1
g:ycm_goto_buffer_command
optionDefines where GoTo*
commands result should be opened. Can take one of the following values: 'same-buffer'
, 'split'
, or 'split-or-existing-window'
. If this option is set to the 'same-buffer'
but current buffer can not be switched (when buffer is modified and nohidden
option is set), then result will be opened in a split. When the option is set to 'split-or-existing-window'
, if the result is already open in a window of the current tab page (or any tab pages with the :tab
modifier; see below), it will jump to that window. Otherwise, the result will be opened in a split as if the option was set to 'split'
.
To customize the way a new window is split, prefix the GoTo*
command with one of the following modifiers: :aboveleft
, :belowright
, :botright
, :leftabove
, :rightbelow
, :topleft
, and :vertical
. For instance, to split vertically to the right of the current window, run the command:
:rightbelow vertical YcmCompleter GoTo
To open in a new tab page, use the :tab
modifier with the 'split'
or 'split-or-existing-window'
options e.g.:
:tab YcmCompleter GoTo
Default: 'same-buffer'
let g:ycm_goto_buffer_command = 'same-buffer'
g:ycm_disable_for_files_larger_than_kb
optionDefines the max size (in Kb) for a file to be considered for completion. If this option is set to 0 then no check is made on the size of the file you're opening.
Default: 1000
let g:ycm_disable_for_files_larger_than_kb = 1000
g:ycm_use_clangd
optionThis option controls whether clangd should be used as completion engine for C-family languages. Can take one of the following values: 1
, 0
, with meanings:
1
: YCM will use clangd if clangd binary exists in third party or it was provided with ycm_clangd_binary_path
option.0
: YCM will never use clangd completer.Default: 1
let g:ycm_use_clangd = 1
g:ycm_clangd_binary_path
optionWhen ycm_use_clangd
option is set to 1
, this option sets the path to clangd binary.
Default: ''
let g:ycm_clangd_binary_path = ''
g:ycm_clangd_args
optionThis option controls the command line arguments passed to the clangd binary. It appends new options and overrides the existing ones.
Default: []
let g:ycm_clangd_args = []
g:ycm_clangd_uses_ycmd_caching
optionThis option controls which ranking and filtering algorithm to use for completion items. It can take values:
1
: Uses ycmd's caching and filtering logic.0
: Uses clangd's caching and filtering logic.Default: 1
let g:ycm_clangd_uses_ycmd_caching = 1
g:ycm_language_server
optionThis option lets YCM use an arbitrary Language Server Protocol (LSP) server, not unlike many other completion systems. The officially supported completers are favoured over custom LSP ones, so overriding an existing completer means first making sure YCM won't choose that existing completer in the first place.
A simple working example of this option can be found in the section called "Semantic Completion for Other Languages".
Many working examples can be found in the YCM lsp-examples repo.
Default: []
let g:ycm_language_server = []
g:ycm_disable_signature_help
optionThis option allows you to disable all signature help for all completion engines. There is no way to disable it per-completer. This option is reserved, meaning that while signature help support remains experimental, its values and meaning may change and it may be removed in a future version.
Default: 0
" Disable signature help
let g:ycm_disable_signature_help = 1
g:ycm_gopls_binary_path
optionIn case the system-wide gopls
binary is newer than the bundled one, setting this option to the path of the system-wide gopls
would make YCM use that one instead.
If the path is just gopls
, YCM will search in $PATH
.
g:ycm_gopls_args
optionSimilar to the g:ycm_clangd_args
, this option allows passing additional flags to the gopls
command line.
Default: []
let g:ycm_gopls_args = []
g:ycm_rls_binary_path
and g:ycm_rustc_binary_path
optionsYCM no longer uses RLS for rust, and these options are therefore no longer supported.
To use a custom rust-analyzer, see g:ycm_rust_toolchain_root
.
g:ycm_rust_toolchain_root
optionOptionally specify the path to a custom rust toolchain including at least a supported version of rust-analyzer
.
g:ycm_tsserver_binary_path
optionSimilar to the gopls
path, this option tells YCM where is the TSServer executable located.
g:ycm_roslyn_binary_path
optionSimilar to the gopls
path, this option tells YCM where is the Omnisharp-Roslyn executable located.
g:ycm_update_diagnostics_in_insert_mode
optionWith async diagnostics, LSP servers might send new diagnostics mid-typing. If seeing these new diagnostics while typing is not desired, this option can be set to 0.
Default: 1
let g:ycm_update_diagnostics_in_insert_mode = 1
The FAQ section has been moved to the wiki.
Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.
If you have questions about the plugin or need help, please join the Gitter room or use the ycm-users mailing list.
If you have bug reports or feature suggestions, please use the issue tracker. Before you do, please carefully read CONTRIBUTING.md as this asks for important diagnostics which the team will use to help get you going.
The latest version of the plugin is available at https://ycm-core.github.io/YouCompleteMe/.
The author's homepage is https://val.markovic.io.
Please do NOT go to #vim on freenode for support. Please contact the YouCompleteMe maintainers directly using the contact details.
This software is licensed under the GPL v3 license. © 2015-2018 YouCompleteMe contributors
If you like YCM so much that you're wiling to part with your hard-earned cash, please consider donating to one of the following charities, which are meaningful to the current maintainers (in no particular order):
Please note: The YCM maintainers do not specifically endorse nor necessarily have any relationship with the above charities. Disclosure: It is noted that one key maintainer is family with Trustees of Greyhound Rescue Wales.
Author: ycm-core
Source Code: https://github.com/ycm-core/YouCompleteMe
License: GPL-3.0 License