0% found this document useful (0 votes)
9 views6 pages

Cheat - Sheet - Advanced Flutter

This document serves as a cheat sheet for advanced Flutter development, covering key topics such as calling APIs, managing state, and utilizing native features. It includes code examples for making HTTP requests, handling errors, accessing device sensors, and managing local storage. Additionally, it discusses integrating plugins for functionalities like audio playback and maps within Flutter applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views6 pages

Cheat - Sheet - Advanced Flutter

This document serves as a cheat sheet for advanced Flutter development, covering key topics such as calling APIs, managing state, and utilizing native features. It includes code examples for making HTTP requests, handling errors, accessing device sensors, and managing local storage. Additionally, it discusses integrating plugins for functionalities like audio playback and maps within Flutter applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

5/19/25, 12:31 PM

Cheat Sheet: Advanced Flutter


Calling APIs in Flutter

Type Description Code Example

Future<void> fetchData() async {


var response = await
[Link]([Link]('[Link]
print([Link]);
}

Making Your First Learn how to perform a basic HTTP GET


API Call request

try {
var response = await
[Link]([Link]('[Link]
print([Link]);
} catch (e) {
print('Caught error: $e');
}

Handling API
Implement error handling for API requests
Errors

var data = jsonDecode([Link]);


print('User name: ${data['username']}');

Decode JSON data received from an API


Parsing JSON Data
into Dart objects

Future<void> getUserData() async {


var response = await
[Link]([Link]('[Link]
var data = jsonDecode([Link]);
print('User name: ${data['name']}');
}

Asynchronous Use async and await for asynchronous API


Programming calls

Future<void> postData() async {


var response = await
[Link]([Link]('[Link] body: {'name': 'John Doe'});
print('Response status: ${[Link]}');
}

Send data to an API using the POST


Post Data to API
method

[Link] Page 1 of 6
5/19/25, 12:31 PM

Future<void> fetchWithHeaders() async {


var response = await [Link](
[Link]('[Link]
headers: {'Authorization': 'Bearer your_token_here'}
);
print('Data with headers: ${[Link]}');
}

Fetch Data with Make HTTP requests with additional


Headers headers

Introduction to mobile native features in Flutter

Type Description Code Example

Future<void> takePicture() async {


final cameras = await availableCameras();
final firstCamera = [Link];
final CameraController controller = CameraController(firstCamera, [Link]);
await [Link]();
final image = await [Link]();
[Link]();
}
Utilize the native camera
Accessing the
functionality via the Flutter
Camera
plugin

Position position = await


[Link](desiredAccuracy: [Link]);
print('Current location: ${[Link]}, ${[Link]}');

Fetch the current location


Using GPS using the geolocation
plugin

SharedPreferences prefs = await


[Link]();
await [Link]('username', 'exampleUser');

Store data locally using the


Local Storage
shared_preferences plugin

StreamSubscription<dynamic> subscription = [Link]((AccelerometerEvent event) {


print(event);
});

Interact with native device


Accessing
sensors like the
Device Sensors
accelerometer

[Link] Page 2 of 6
5/19/25, 12:31 PM

FlutterLocalNotificationsPlugin notificationsPlugin = FlutterLocalNotificationsPlugin();


var androidDetails = AndroidNotificationDetails('channelId', 'channelName', 'channelDescription');
var generalNotificationDetails = NotificationDetails(android: androidDetails);
await [Link](0, 'Test Title', 'Test Body', generalNotificationDetails);

Schedule and manage


Managing
notifications locally on the
Notifications
device

Managing state in Flutter

Type Description Code Example

setState(() {
_counter++;
});

Manage local widget


Provides a way to manage and update
state changes in a
the local state of a widget
StatefulWidget

MyInheritedWidget(
data: counter,
child: ChildWidget()
);

Provides a way to pass data down the


InheritedWidget widget tree and allows descendants to
rebuild when the data changes

final _formKey = GlobalKey<FormState>();


Form(
key: _formKey,
child: Column(
children: [
TextFormField(validator: (value) => [Link] ? 'Cannot be empty' : null),
ElevatedButton(
onPressed: () {
if (_formKey.[Link]()) {
// Process data
}
},
Utilize GlobalKey to access the state child: Text('Submit')
GlobalKey and )
from anywhere in the app, commonly
FormState ],
used with forms )
);

ChangeNotifierProvider(
create: (context) => DataModel(),
child: Consumer<DataModel>(
builder: (context, dataModel, child) {
return Text('${[Link]}');
},

[Link] Page 3 of 6
5/19/25, 12:31 PM

),
);
A wrapper around InheritedWidget to
Provider for state
make state management easier and
management
more efficient

Flutter Persistence with Local Storage

Type Description Code Example

final prefs = await [Link]();


[Link]('counter', 10);
int counter = [Link]('counter') ?? 0;

SharedPreferences Ideal for simple data such as user preferences and settings

Ideal for structured data and complex queries. It works like a


SQLite
traditional database

Files Read/write files for documents or media

Hive: A fast, NoSQL database for Flutter.


Third-Party Packages LocalStorage: Similar to web local storage, ideal for storing
JSON data.

final prefs = await [Link]();

Initialize Local Storage Set up the chosen storage method at the start of your app.

// Saving data
[Link]('counter', 10);
// Retrieving data
int counter = [Link]('counter') ?? 0;
// Deleting data
[Link]('counter');

CRUD Operations Implement Create, Read, Update, and Delete functions.

import 'dart:convert';
Map userMap = jsonDecode(jsonString);
var user = [Link](userMap);

Serialization/Deserialization Encode and decode data using JSON for complex structures

[Link] Page 4 of 6
5/19/25, 12:31 PM

class UserProvider with ChangeNotifier {


User _user;
User get user => _user;
void loadUser() {
String userJson = [Link]('user');
_user = [Link](jsonDecode(userJson));
notifyListeners();
}
}
Integrating with State Use state management tools (e.g., Provider, Riverpod) to handle
Management local storage updates dynamically in the UI

Plugins in Flutter

Type Description Code Example

if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}

Using the Open a URL in the mobile browser from a


url_launcher Plugin Flutter app

// Typically handled in your [Link] by specifying compatible versions


dependencies:
flutter:
sdk: flutter
url_launcher: ^6.0.3

Managing Plugin Ensure that plugins are compatible with


Compatibility the version of Flutter you are using

final cameras = await availableCameras();


final firstCamera = [Link];
final cameraController = CameraController(firstCamera, [Link]);
await [Link]();

Access the device camera to capture


Camera Plugin
photos and videos

final player = AudioPlayer();


await [Link](UrlSource('[Link]

Audio Players Play audio files and streams in Flutter with


Plugin the Audio Players plugin

[Link] Page 5 of 6
5/19/25, 12:31 PM

GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: LatLng(0.0, 0.0),
zoom: 10.0,
),
);

Integrate maps into your Flutter


Flutter Maps Plugin
applications using the maps plugin

[Link] Page 6 of 6

You might also like