id
stringlengths 14
17
| text
stringlengths 23
1.11k
| source
stringlengths 35
114
|
---|---|---|
98f6e20a03d5-1 | To work with named routes,
use the Navigator.pushNamed() function.
This example replicates the functionality from the original recipe,
demonstrating how to use named routes using the following steps:
Create two screens.
Define the routes.
Navigate to the second screen using Navigator.pushNamed().
Return to the first screen using Navigator.pop().
1. Create two screens
First, create two screens to work with. The first screen contains a
button that navigates to the second screen. The second screen contains a
button that navigates back to the first.
2. Define the routes
Next, define the routes by providing additional properties
to the MaterialApp constructor: the initialRoute
and the routes themselves.
The initialRoute property defines which route the app should start with.
The routes property defines the available named routes and the widgets
to build when navigating to those routes. | https://docs.flutter.dev/cookbook/navigation/named-routes/index.html |
98f6e20a03d5-2 | Warning:
When using initialRoute, don’t define a home property.
3. Navigate to the second screen
With the widgets and routes in place, trigger navigation by using the
Navigator.pushNamed() method.
This tells Flutter to build the widget defined in the
routes table and launch the screen.
In the build() method of the FirstScreen widget, update the onPressed()
callback:
4. Return to the first screen
To navigate back to the first screen, use the
Navigator.pop() function.
Interactive example
Navigate to a new screen and back
Pass arguments to a named route | https://docs.flutter.dev/cookbook/navigation/named-routes/index.html |
c6c1a7c26356-0 | Navigate with named routes
Set up app links for Android
Pass arguments to a named route
Cookbook
Navigation
Pass arguments to a named route
1. Define the arguments you need to pass
2. Create a widget that extracts the arguments
3. Register the widget in the routes table
4. Navigate to the widget
Alternatively, extract the arguments using onGenerateRoute
Interactive example
The Navigator provides the ability to navigate
to a named route from any part of an app using
a common identifier.
In some cases, you might also need to pass arguments to a
named route. For example, you might wish to navigate to the /user route and
pass information about the user to that route.
Note:
Named routes are no longer recommended for most
applications. For more information, see
Limitations in the navigation overview page. | https://docs.flutter.dev/cookbook/navigation/navigate-with-arguments/index.html |
c6c1a7c26356-1 | Navigator.pushNamed() method. Extract the arguments using the
ModalRoute.of() method or inside an
onGenerateRoute()
function provided to the
MaterialApp or
CupertinoApp
constructor.
This recipe demonstrates how to pass arguments to a named
route and read the arguments using ModalRoute.of()
and onGenerateRoute() using the following steps:
Define the arguments you need to pass.
Create a widget that extracts the arguments.
Register the widget in the routes table.
Navigate to the widget.
1. Define the arguments you need to pass
First, define the arguments you need to pass to the new route.
In this example, pass two pieces of data:
The title of the screen and a message.
To pass both pieces of data, create a class that stores this information.
2. Create a widget that extracts the arguments | https://docs.flutter.dev/cookbook/navigation/navigate-with-arguments/index.html |
c6c1a7c26356-2 | 2. Create a widget that extracts the arguments
Next, create a widget that extracts and displays the
title and message from the ScreenArguments.
To access the ScreenArguments,
use the ModalRoute.of() method.
This method returns the current route with the arguments.
3. Register the widget in the routes table
Next, add an entry to the routes provided to the MaterialApp widget. The
routes define which widget should be created based on the name of the route.
4. Navigate to the widget
Navigator.pushNamed().
Provide the arguments to the route via the
Alternatively, extract the arguments using onGenerateRoute
Instead of extracting the arguments directly inside the widget, you can also
extract the arguments inside an onGenerateRoute()
function and pass them to a widget.
The onGenerateRoute() function creates the correct route based on the given
RouteSettings.
Interactive example | https://docs.flutter.dev/cookbook/navigation/navigate-with-arguments/index.html |
c6c1a7c26356-3 | Interactive example
Navigate with named routes
Set up app links for Android | https://docs.flutter.dev/cookbook/navigation/navigate-with-arguments/index.html |
0f4e4870fd7c-0 | Animate a widget across screens
Navigate with named routes
Navigate to a new screen and back
Cookbook
Navigation
Navigate to a new screen and back
1. Create two routes
2. Navigate to the second route using Navigator.push()
3. Return to the first route using Navigator.pop()
Interactive example
Most apps contain several screens for displaying different types of
information.
For example, an app might have a screen that displays products.
When the user taps the image of a product, a new screen displays
details about the product.
Terminology: In Flutter, screens and pages are called routes.
The remainder of this recipe refers to routes.
In Android, a route is equivalent to an Activity.
In iOS, a route is equivalent to a ViewController.
In Flutter, a route is just a widget. | https://docs.flutter.dev/cookbook/navigation/navigation-basics/index.html |
0f4e4870fd7c-1 | This recipe uses the Navigator to navigate to a new route.
The next few sections show how to navigate between two routes,
using these steps:
Create two routes.
Navigate to the second route using Navigator.push().
Return to the first route using Navigator.pop().
1. Create two routes
First, create two routes to work with. Since this is a basic example,
each route contains only a single button. Tapping the button on the
first route navigates to the second route. Tapping the button on the
second route returns to the first route.
First, set up the visual structure:
2. Navigate to the second route using Navigator.push()
Navigator.push()
method. The
MaterialPageRoute,
which is useful because it transitions to the
new route using a platform-specific animation. | https://docs.flutter.dev/cookbook/navigation/navigation-basics/index.html |
0f4e4870fd7c-2 | In the build() method of the FirstRoute widget,
update the onPressed() callback:
3. Return to the first route using Navigator.pop()
How do you close the second route and return to the first?
By using the Navigator.pop() method.
The pop() method removes the current Route from the stack of
routes managed by the Navigator.
To implement a return to the original route, update the onPressed()
callback in the SecondRoute widget:
Interactive example
Animate a widget across screens
Navigate with named routes | https://docs.flutter.dev/cookbook/navigation/navigation-basics/index.html |
88031d968a0d-0 | Return data from a screen
Delete data on the internet
Send data to a new screen
Cookbook
Navigation
Send data to a new screen
1. Define a todo class
2. Create a list of todos
Generate the list of todos
Display the list of todos using a ListView
3. Create a Todo screen to display the list
4. Create a detail screen to display information about a todo
5. Navigate and pass data to the detail screen
Interactive example
Alternatively, pass the arguments using RouteSettings
Create a detail screen to extract the arguments
Navigate and pass the arguments to the detail screen
Complete example
Often, you not only want to navigate to a new screen,
but also pass data to the screen as well.
For example, you might want to pass information about
the item that’s been tapped. | https://docs.flutter.dev/cookbook/navigation/passing-data/index.html |
88031d968a0d-1 | Remember: Screens are just widgets.
In this example, create a list of todos.
When a todo is tapped, navigate to a new screen (widget) that
displays information about the todo.
This recipe uses the following steps:
Define a todo class.
Display a list of todos.
Create a detail screen that can display information about a todo.
Navigate and pass data to the detail screen.
1. Define a todo class
First, you need a simple way to represent todos. For this example,
create a class that contains two pieces of data: the title and description.
2. Create a list of todos
Second, display a list of todos. In this example, generate
20 todos and show them using a ListView.
For more information on working with lists,
see the Use lists recipe.
Generate the list of todos
Display the list of todos using a ListView | https://docs.flutter.dev/cookbook/navigation/passing-data/index.html |
88031d968a0d-2 | Generate the list of todos
Display the list of todos using a ListView
So far, so good.
This generates 20 todos and displays them in a ListView.
3. Create a Todo screen to display the list
For this, we create a StatelessWidget. We call it TodosScreen.
Since the contents of this page won’t change during runtime,
we’ll have to require the list
of todos within the scope of this widget.
We pass in our ListView.builder as body of the widget we’re returning to build().
This’ll render the list on to the screen for you to get going!
With Flutter’s default styling, you’re good to go without sweating about
things that you’d like to do later on!
4. Create a detail screen to display information about a todo
Now, create the second screen. The title of the screen contains the
title of the todo, and the body of the screen shows the description. | https://docs.flutter.dev/cookbook/navigation/passing-data/index.html |
88031d968a0d-3 | Since the detail screen is a normal StatelessWidget,
require the user to enter a Todo in the UI.
Then, build the UI using the given todo.
5. Navigate and pass data to the detail screen
With a DetailScreen in place,
you’re ready to perform the Navigation.
In this example, navigate to the DetailScreen when a user
taps a todo in the list. Pass the todo to the DetailScreen.
To capture the user’s tap in the TodosScreen, write an onTap()
callback for the ListTile widget. Within the onTap() callback,
use the Navigator.push() method.
Interactive example
Alternatively, pass the arguments using RouteSettings
Repeat the first two steps.
Create a detail screen to extract the arguments | https://docs.flutter.dev/cookbook/navigation/passing-data/index.html |
88031d968a0d-4 | Create a detail screen to extract the arguments
Next, create a detail screen that extracts and displays the title and description from the Todo. To access the Todo, use the ModalRoute.of() method. This method returns the current route with the arguments.
Navigate and pass the arguments to the detail screen
Finally, navigate to the DetailScreen when a user taps
a ListTile widget using Navigator.push().
Pass the arguments as part of the RouteSettings.
The DetailScreen extracts these arguments.
Complete example
Return data from a screen
Delete data on the internet | https://docs.flutter.dev/cookbook/navigation/passing-data/index.html |
61aaef89606f-0 | Set up universal links for iOS
Send data to a new screen
Return data from a screen
Cookbook
Navigation
Return data from a screen
1. Define the home screen
2. Add a button that launches the selection screen
3. Show the selection screen with two buttons
4. When a button is tapped, close the selection screen
Yep button
Nope button
5. Show a snackbar on the home screen with the selection
Interactive example
In some cases, you might want to return data from a new screen.
For example, say you push a new screen that presents two options to a user.
When the user taps an option, you want to inform the first screen
of the user’s selection so that it can act on that information.
You can do this with the Navigator.pop()
method using the following steps: | https://docs.flutter.dev/cookbook/navigation/returning-data/index.html |
61aaef89606f-1 | You can do this with the Navigator.pop()
method using the following steps:
Define the home screen
Add a button that launches the selection screen
Show the selection screen with two buttons
When a button is tapped, close the selection screen
Show a snackbar on the home screen with the selection
1. Define the home screen
The home screen displays a button. When tapped,
it launches the selection screen.
2. Add a button that launches the selection screen
Now, create the SelectionButton, which does the following:
Launches the SelectionScreen when it’s tapped.
Waits for the SelectionScreen to return a result.
3. Show the selection screen with two buttons | https://docs.flutter.dev/cookbook/navigation/returning-data/index.html |
61aaef89606f-2 | 3. Show the selection screen with two buttons
Now, build a selection screen that contains two buttons.
When a user taps a button,
that app closes the selection screen and lets the home
screen know which button was tapped.
This step defines the UI.
The next step adds code to return data.
4. When a button is tapped, close the selection screen
Now, update the onPressed() callback for both of the buttons.
To return data to the first screen,
use the Navigator.pop() method,
which accepts an optional second argument called result.
Any result is returned to the Future in the SelectionButton.
Yep button
Nope button
5. Show a snackbar on the home screen with the selection
Now that you’re launching a selection screen and awaiting the result,
you’ll want to do something with the information that’s returned. | https://docs.flutter.dev/cookbook/navigation/returning-data/index.html |
61aaef89606f-3 | In this case, show a snackbar displaying the result by using the
_navigateAndDisplaySelection() method in SelectionButton:
Interactive example
Set up universal links for iOS
Send data to a new screen | https://docs.flutter.dev/cookbook/navigation/returning-data/index.html |
4eaf833c87b9-0 | Pass arguments to a named route
Set up universal links for iOS
Set up app links for Android
Cookbook
Navigation
Set up app links for Android
1. Customize a Flutter application
2. Modify AndroidManifest.xml
3. Hosting assetlinks.json file
Package name
sha256 fingerprint
Using google play app signing
Using local keystore
assetlinks.json
Testing
Appendix
Deep linking is a mechanism for launching an app with a URI. This URI
contains scheme, host, and path, and opens the app to a specific
screen.
A app link is a type of deep link that uses http or https and
is exclusive to Android devices. | https://docs.flutter.dev/cookbook/navigation/set-up-app-links/index.html |
4eaf833c87b9-1 | Setting up app links requires one to own a web domain. Otherwise, consider
using Firebase Hosting or GitHub Pages as a temporary solution.
1. Customize a Flutter application
Write a Flutter app that can handle an incoming URL.
This example uses the go_router package to handle the routing.
The Flutter team maintains the go_router package.
It provides a simple API to handle complex routing scenarios.
To create a new application, type flutter create <app-name>.
$ flutter create deeplink_cookbook
To include go_router package in your app, add a dependency for
go_router in the pubspec.yaml file.
dependencies:
flutter:
sdk: flutter
go_router: ^6.0.9
To handle the routing, create a GoRouter object in the main.dart file: | https://docs.flutter.dev/cookbook/navigation/set-up-app-links/index.html |
4eaf833c87b9-2 | To handle the routing, create a GoRouter object in the main.dart file:
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() => runApp(MaterialApp.router(routerConfig: router));
/// This handles '/' and '/details'.
final router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (_, __) => Scaffold(
appBar: AppBar(title: const Text('Home Screen')),
),
routes: [
GoRoute(
path: 'details',
builder: (_, __) => Scaffold(
appBar: AppBar(title: const Text('Details Screen')),
),
),
],
),
],
);
2. Modify AndroidManifest.xml
Open the Flutter project with Android Studio or VSCode. | https://docs.flutter.dev/cookbook/navigation/set-up-app-links/index.html |
4eaf833c87b9-3 | Open the Flutter project with Android Studio or VSCode.
Navigate to android/app/src/main/AndroidManifest.xml file
Add the following metadata tag and intent filter inside the <activity> tag with .MainActivity | https://docs.flutter.dev/cookbook/navigation/set-up-app-links/index.html |
4eaf833c87b9-4 | Add the following metadata tag and intent filter inside the <activity> tag with .MainActivity
Replace example.com with your own web domain.
<meta-data android:name="flutter_deeplinking_enabled" android:value="true" />
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" android:host="example.com" />
<data android:scheme="https" />
</intent-filter>
Note:
The metadata tag flutter_deeplinking_enabled opts into Flutter’s default deeplink handler. If
you are using the third-party plugins, such as uni_links, setting this metadata tag will
break these plugins. Omit this metadata tag if you prefer to use third-party plugins. | https://docs.flutter.dev/cookbook/navigation/set-up-app-links/index.html |
4eaf833c87b9-5 | 3. Hosting assetlinks.json file
Host an assetlinks.json file in using a web server with a domain that you own.
This file tells the mobile browser which Android application to open instead of the browser.
To create the file, get the package name of the Flutter app you created in the previous step and
the sha256 fingerprint of the signing key you will be using to build the APK.
Package name
Locate the package name in AndroidManifest.xml, the package property under <manifest> tag.
Package names are usually in the format of com.example.*.
sha256 fingerprint
Process may differ depending on the way apk is signed.
Using google play app signing
You can find the sha256 fingerprint directly from play developer console. Open your app in the play
console, under Release> Setup > App Integrity> App Signing tab
Using local keystore | https://docs.flutter.dev/cookbook/navigation/set-up-app-links/index.html |
4eaf833c87b9-6 | Using local keystore
If you are storing the key locally, you can generate sha256 using the following command.
assetlinks.json
The hosted file should look similar to this:
[{
"relation"
"delegate_permission/common.handle_all_urls"
],
"target"
"namespace"
"android_app"
"package_name"
"com.example.deeplink_cookbook"
"sha256_cert_fingerprints" | https://docs.flutter.dev/cookbook/navigation/set-up-app-links/index.html |
4eaf833c87b9-7 | "sha256_cert_fingerprints"
"FF:2A:CF:7B:DD:CC:F1:03:3E:E8:B2:27:7C:A2:E3:3C:DE:13:DB:AC:8E:EB:3A:B9:72:A1:0E:26:8A:F5:EC:AF"
}]
Set the package_name value to your Flutter application package name.
Set sha256_cert_fingerprints to the value you got from the previous step.
Host the file at a URL that resembles the following:
<webdomain>/.well-known/assetlinks.json
Verify that your browser can access this file.
Testing | https://docs.flutter.dev/cookbook/navigation/set-up-app-links/index.html |
4eaf833c87b9-8 | Verify that your browser can access this file.
Testing
You can use a real device or the Emulator to test a app link,
but first make sure you have executed flutter run at least once on
the devices. This ensures that the Flutter application is installed.
To test only the app setup, use the adb command:
Note:
This does not test whether the web files are hosted correctly, the command launches the app even
if web files are not presented.
To test both web and app setup, you need to click on a link directly through web browser or other
apps. One way is to create a Google Doc, add the link, and tap on it.
If everything is set up correctly, the Flutter application
launches and displays the details screen:
Appendix
Source code: deeplink_cookbook
Pass arguments to a named route
Set up universal links for iOS | https://docs.flutter.dev/cookbook/navigation/set-up-app-links/index.html |
a3696a2b5958-0 | Set up app links for Android
Return data from a screen
Set up universal links for iOS
Cookbook
Navigation
Set up universal links for iOS
1. Customize a Flutter application
2. Adjust iOS build settings
3. Hosting apple-app-site-association file
App ID
apple-app-site-association
Testing
Appendix
Deep linking is a mechanism for launching an app with a URI. This URI
contains scheme, host, and path, and opens the app to a specific
screen.
A universal link is a type of deep link that uses http or https and
is exclusive to Apple devices.
Setting up universal links requires one to own a web domain. Otherwise, consider
using Firebase Hosting or GitHub Pages as a temporary solution.
1. Customize a Flutter application | https://docs.flutter.dev/cookbook/navigation/set-up-universal-links/index.html |
a3696a2b5958-1 | 1. Customize a Flutter application
Write a Flutter app that can handle an incoming URL.
This example uses the go_router package to handle the routing.
The Flutter team maintains the go_router package.
It provides a simple API to handle complex routing scenarios.
To create a new application, type flutter create <app-name>.
$ flutter create deeplink_cookbook
To include go_router package in your app, add a dependency for
go_router in the pubspec.yaml file.
dependencies:
flutter:
sdk: flutter
go_router: ^6.0.9
To handle the routing, create a GoRouter object in the main.dart file:
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() => runApp(MaterialApp.router(routerConfig: router)); | https://docs.flutter.dev/cookbook/navigation/set-up-universal-links/index.html |
a3696a2b5958-2 | void main() => runApp(MaterialApp.router(routerConfig: router));
/// This handles '/' and '/details'.
final router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (_, __) => Scaffold(
appBar: AppBar(title: const Text('Home Screen')),
),
routes: [
GoRoute(
path: 'details',
builder: (_, __) => Scaffold(
appBar: AppBar(title: const Text('Details Screen')),
),
),
],
),
],
);
2. Adjust iOS build settings
Launch Xcode.
Open the ios/Runner.xcworkspace file inside the project’s ios folder.
Navigate to the Info Plist file in the ios/Runner folder.
In the Info property list, control-click at the list to add a row. | https://docs.flutter.dev/cookbook/navigation/set-up-universal-links/index.html |
a3696a2b5958-3 | In the Info property list, control-click at the list to add a row.
Control-click the newly added row and turn on the Raw Keys and Values mode
Update the key to FlutterDeepLinkingEnabled with a Boolean value set to YES.
Note:
The FlutterDeepLinkingEnabled property opts into Flutter’s default deeplink handler. If
you are using the third-party plugins, such as uni_links, setting this property will
break these plugins. Skip this step if you prefer to use third-party plugins.
Click the top-level Runner.
Click Sign & Signature.
Click + Capability to add a new domain.
Click Associated Domains.
In the Associated Domains section, click +.
Enter applinks:<web domain>. Replace <web domain> with your own domain name. | https://docs.flutter.dev/cookbook/navigation/set-up-universal-links/index.html |
a3696a2b5958-4 | Enter applinks:<web domain>. Replace <web domain> with your own domain name.
You have finished configuring the application for deep linking.
3. Hosting apple-app-site-association file
You need to host an apple-app-site-association file in the web domain.
This file tells the mobile browser which iOS application to open instead of the browser.
To create the file, get the app ID of the Flutter app you created in the previous step.
App ID
Apple formats the app ID as <team id>.<bundle id>.
Locate the bundle ID in the Xcode project.
Locate the team ID in the developer account.
For example: Given a team ID of S8QB4VV633
and a bundle ID of com.example.deeplinkCookbook, The app ID is
S8QB4VV633.com.example.deeplinkCookbook. | https://docs.flutter.dev/cookbook/navigation/set-up-universal-links/index.html |
a3696a2b5958-5 | apple-app-site-association
The hosted file should have the following content:
"applinks"
"details"
"appID"
"S8QB4VV633.com.example.deeplinkCookbook"
"paths"
"*"
Set the appID value to your Flutter application ID.
Set the paths value to ["*"].
The paths field specifies the allowed universal links.
Using the asterisk, * redirects every path to the Flutter application.
If needed, change the paths value to a setting more appropriate
to your app.
Host the file at a URL that resembles the following:
<webdomain>/.well-known/apple-app-site-association
Verify that your browser can access this file.
Testing | https://docs.flutter.dev/cookbook/navigation/set-up-universal-links/index.html |
a3696a2b5958-6 | Verify that your browser can access this file.
Testing
Note:
It might take up to 24 hours before Apple’s
Content Delivery Network (CDN)
requests the apple-app-site-association (AASA) file from your web domain.
The universal link won’t work until the CDN requests the file.
To bypass Apple’s CDN, check out the alternate mode section.
You can use a real device or the Simulator to test a universal link,
but first make sure you have executed flutter run at least once on
the devices. This ensures that the Flutter application is installed.
If using the Simulator, test using the Xcode CLI:
Otherwise, type the URL in the Note app and click it.
If everything is set up correctly, the Flutter application
launches and displays the details screen:
Appendix
Source code: deeplink_cookbook | https://docs.flutter.dev/cookbook/navigation/set-up-universal-links/index.html |
a3696a2b5958-7 | Appendix
Source code: deeplink_cookbook
Set up app links for Android
Return data from a screen | https://docs.flutter.dev/cookbook/navigation/set-up-universal-links/index.html |
1c012685a1cc-0 | Fetch data from the internet
Parse JSON in the background
Make authenticated requests
Cookbook
Networking
Make authenticated requests
Add authorization headers
Complete example
To fetch data from most web services, you need to provide
authorization. There are many ways to do this,
but perhaps the most common uses the Authorization HTTP header.
Add authorization headers
The http package provides a
convenient way to add headers to your requests.
Alternatively, use the HttpHeaders
class from the dart:io library.
Complete example
This example builds upon the
Fetching data from the internet recipe.
Fetch data from the internet
Parse JSON in the background | https://docs.flutter.dev/cookbook/networking/authenticated-requests/index.html |
d15b19943da4-0 | Make authenticated requests
Send data to the internet
Parse JSON in the background
Cookbook
Networking
Parse JSON in the background
1. Add the http package
2. Make a network request
3. Parse and convert the JSON into a list of photos
Create a Photo class
Convert the response into a list of photos
4. Move this work to a separate isolate
Notes on working with isolates
Complete example
By default, Dart apps do all of their work on a single thread.
In many cases, this model simplifies coding and is fast enough
that it does not result in poor app performance or stuttering animations,
often called “jank.”
However, you might need to perform an expensive computation,
such as parsing a very large JSON document.
If this work takes more than 16 milliseconds,
your users experience jank. | https://docs.flutter.dev/cookbook/networking/background-parsing/index.html |
d15b19943da4-1 | To avoid jank, you need to perform expensive computations
like this in the background.
On Android, this means scheduling work on a different thread.
In Flutter, you can use a separate Isolate.
This recipe uses the following steps:
Add the http package.
Make a network request using the http package.
Convert the response into a list of photos.
Move this work to a separate isolate.
1. Add the http package
First, add the http package to your project.
The http package makes it easier to perform network
requests, such as fetching data from a JSON endpoint.
dependencies
http
<latest_version>
2. Make a network request
This example covers how to fetch a large JSON document
that contains a list of 5000 photo objects from the
JSONPlaceholder REST API,
using the http.get() method. | https://docs.flutter.dev/cookbook/networking/background-parsing/index.html |
d15b19943da4-2 | Note:
You’re providing an http.Client to the function in this example.
This makes the function easier to test and use in different environments.
3. Parse and convert the JSON into a list of photos
Next, following the guidance from the
Fetch data from the internet recipe,
convert the http.Response into a list of Dart objects.
This makes the data easier to work with.
Create a Photo class
First, create a Photo class that contains data about a photo.
Include a fromJson() factory method to make it easy to create a
Photo starting with a JSON object.
Convert the response into a list of photos
Now, use the following instructions to update the
fetchPhotos() function so that it returns a
Future<List<Photo>>:
Create a parsePhotos() function that converts the response
body into a List<Photo>.
Use the parsePhotos() function in the fetchPhotos() function. | https://docs.flutter.dev/cookbook/networking/background-parsing/index.html |
d15b19943da4-3 | Use the parsePhotos() function in the fetchPhotos() function.
4. Move this work to a separate isolate
If you run the fetchPhotos() function on a slower device,
you might notice the app freezes for a brief moment as it parses and
converts the JSON. This is jank, and you want to get rid of it.
You can remove the jank by moving the parsing and conversion
to a background isolate using the compute()
function provided by Flutter. The compute() function runs expensive
functions in a background isolate and returns the result. In this case,
run the parsePhotos() function in the background.
Notes on working with isolates
You might experience errors if you try to pass more complex objects,
such as a Future or http.Response between isolates.
As an alternate solution, check out the worker_manager or
workmanager packages for background processing.
Complete example
Make authenticated requests | https://docs.flutter.dev/cookbook/networking/background-parsing/index.html |
d15b19943da4-4 | Complete example
Make authenticated requests
Send data to the internet | https://docs.flutter.dev/cookbook/networking/background-parsing/index.html |
4e78fcaabbe4-0 | Send data to a new screen
Fetch data from the internet
Delete data on the internet
Cookbook
Networking
Delete data on the internet
1. Add the http package
2. Delete data on the server
3. Update the screen
Returning a response from the deleteAlbum() method
Complete example
This recipe covers how to delete data over
the internet using the http package.
This recipe uses the following steps:
Add the http package.
Delete data on the server.
Update the screen.
1. Add the http package
To install the http package,
add it to the dependencies section of the pubspec.yaml file.
You can find the latest version of the
http package on pub.dev.
dependencies
http | https://docs.flutter.dev/cookbook/networking/delete-data/index.html |
4e78fcaabbe4-1 | dependencies
http
<latest_version>
Import the http package.
2. Delete data on the server
This recipe covers how to delete an album from the
JSONPlaceholder using the http.delete() method.
Note that this requires the id of the album that
you want to delete. For this example,
use something you already know, for example id = 1.
The http.delete() method returns a Future that contains a Response.
Future is a core Dart class for working with
async operations. A Future object represents a potential
value or error that will be available at some time in the future.
The http.Response class contains the data received from a successful
http call.
The deleteAlbum() method takes an id argument that
is needed to identify the data to be deleted from the server.
3. Update the screen | https://docs.flutter.dev/cookbook/networking/delete-data/index.html |
4e78fcaabbe4-2 | 3. Update the screen
In order to check whether the data has been deleted or not,
first fetch the data from the JSONPlaceholder
using the http.get() method, and display it in the screen.
(See the Fetch Data recipe for a complete example.)
You should now have a Delete Data button that,
when pressed, calls the deleteAlbum() method.
Now, when you click on the Delete Data button,
the deleteAlbum() method is called and the id
you are passing is the id of the data that you retrieved
from the internet. This means you are going to delete
the same data that you fetched from the internet.
Returning a response from the deleteAlbum() method
Once the delete request has been made,
you can return a response from the deleteAlbum()
method to notify our screen that the data has been deleted. | https://docs.flutter.dev/cookbook/networking/delete-data/index.html |
4e78fcaabbe4-3 | FutureBuilder() now rebuilds when it receives a response.
Since the response won’t have any data in its body
if the request was successful,
the Album.fromJson() method creates an instance of the
Album object with a default value (null in our case).
This behavior can be altered in any way you wish.
That’s all!
Now you’ve got a function that deletes the data from the internet.
Complete example
Send data to a new screen
Fetch data from the internet | https://docs.flutter.dev/cookbook/networking/delete-data/index.html |
b84648abc070-0 | Delete data on the internet
Make authenticated requests
Fetch data from the internet
Cookbook
Networking
Fetch data from the internet
1. Add the http package
2. Make a network request
3. Convert the response into a custom Dart object
Create an Album class
Convert the http.Response to an Album
4. Fetch the data
5. Display the data
Why is fetchAlbum() called in initState()?
Testing
Complete example
Fetching data from the internet is necessary for most apps.
Luckily, Dart and Flutter provide tools, such as the
http package, for this type of work.
This recipe uses the following steps:
Add the http package.
Make a network request using the http package. | https://docs.flutter.dev/cookbook/networking/fetch-data/index.html |
b84648abc070-1 | Add the http package.
Make a network request using the http package.
Convert the response into a custom Dart object.
Fetch and display the data with Flutter.
1. Add the http package
The http package provides the
simplest way to fetch data from the internet.
To install the http package, add it to the
dependencies section of the pubspec.yaml file.
You can find the latest version of the
http package the pub.dev.
dependencies
http
<latest_version>
Import the http package.
Additionally, in your AndroidManifest.xml file,
add the Internet permission.
<!-- Required to fetch data from the internet. -->
<uses-permission
android:name=
"android.permission.INTERNET"
/>
2. Make a network request | https://docs.flutter.dev/cookbook/networking/fetch-data/index.html |
b84648abc070-2 | />
2. Make a network request
This recipe covers how to fetch a sample album from the
JSONPlaceholder using the http.get() method.
The http.get() method returns a Future that contains a Response.
Future is a core Dart class for working with
async operations. A Future object represents a potential
value or error that will be available at some time in the future.
The http.Response class contains the data received from a successful
http call.
3. Convert the response into a custom Dart object
While it’s easy to make a network request, working with a raw
Future<http.Response> isn’t very convenient.
To make your life easier,
convert the http.Response into a Dart object.
Create an Album class
First, create an Album class that contains the data from the
network request. It includes a factory constructor that
creates an Album from JSON. | https://docs.flutter.dev/cookbook/networking/fetch-data/index.html |
b84648abc070-3 | Converting JSON by hand is only one option.
For more information, see the full article on
JSON and serialization.
Convert the http.Response to an Album
Now, use the following steps to update the fetchAlbum()
function to return a Future<Album>:
Convert the response body into a JSON Map with
the dart:convert package.
If the server does return an OK response with a status code of
200, then convert the JSON Map into an Album
using the fromJson() factory method.
If the server does not return an OK response with a status code of 200,
then throw an exception.
(Even in the case of a “404 Not Found” server response,
throw an exception. Do not return null.
This is important when examining
the data in snapshot, as shown below.)
Hooray!
Now you’ve got a function that fetches an album from the internet.
4. Fetch the data | https://docs.flutter.dev/cookbook/networking/fetch-data/index.html |
b84648abc070-4 | 4. Fetch the data
Call the fetchAlbum() method in either the
initState() or didChangeDependencies()
methods.
The initState() method is called exactly once and then never again.
If you want to have the option of reloading the API in response to an
InheritedWidget changing, put the call into the
didChangeDependencies() method.
See State for more details.
This Future is used in the next step.
5. Display the data
To display the data on screen, use the
FutureBuilder widget.
The FutureBuilder widget comes with Flutter and
makes it easy to work with asynchronous data sources.
You must provide two parameters:
The Future you want to work with.
In this case, the future returned from
the fetchAlbum() function.
A builder function that tells Flutter
what to render, depending on the
state of the Future: loading, success, or error. | https://docs.flutter.dev/cookbook/networking/fetch-data/index.html |
b84648abc070-5 | Note that snapshot.hasData only returns true
when the snapshot contains a non-null data value.
Because fetchAlbum can only return non-null values,
the function should throw an exception
even in the case of a “404 Not Found” server response.
Throwing an exception sets the snapshot.hasError to true
which can be used to display an error message.
Otherwise, the spinner will be displayed.
Why is fetchAlbum() called in initState()?
Although it’s convenient,
it’s not recommended to put an API call in a build() method.
Flutter calls the build() method every time it needs
to change anything in the view,
and this happens surprisingly often.
The fetchAlbum() method, if placed inside build(), is repeatedly
called on each rebuild causing the app to slow down.
Storing the fetchAlbum() result in a state variable ensures that
the Future is executed only once and then cached for subsequent
rebuilds. | https://docs.flutter.dev/cookbook/networking/fetch-data/index.html |
b84648abc070-6 | Testing
For information on how to test this functionality,
see the following recipes:
Introduction to unit testing
Mock dependencies using Mockito
Complete example
Delete data on the internet
Make authenticated requests | https://docs.flutter.dev/cookbook/networking/fetch-data/index.html |
8fc3e78dd960-0 | Networking
Cookbook
Networking
Delete data on the internet
Fetch data from the internet
Make authenticated requests
Parse JSON in the background
Send data to the internet
Update data over the internet
Work with WebSockets | https://docs.flutter.dev/cookbook/networking/index.html |
aa6468b6f545-0 | Parse JSON in the background
Update data over the internet
Send data to the internet
Cookbook
Networking
Send data to the internet
1. Add the http package
2. Sending data to server
3. Convert the http.Response to a custom Dart object
Create an Album class
Convert the http.Response to an Album
4. Get a title from user input
5. Display the response on screen
Complete example
Sending data to the internet is necessary for most apps.
The http package has got that covered, too.
This recipe uses the following steps:
Add the http package.
Send data to a server using the http package.
Convert the response into a custom Dart object.
Get a title from user input.
Display the response on screen. | https://docs.flutter.dev/cookbook/networking/send-data/index.html |
aa6468b6f545-1 | Get a title from user input.
Display the response on screen.
1. Add the http package
To install the http package, add it to the dependencies section
of the pubspec.yaml file. You can find the latest version of the
http package on pub.dev.
dependencies
http
<latest_version>
Import the http package.
If you develop for android,
add the following permission inside the manifest tag
in the AndroidManifest.xml file located at android/app/src/main.
<uses-permission
android:name=
"android.permission.INTERNET"
/>
2. Sending data to server
This recipe covers how to create an Album
by sending an album title to the
JSONPlaceholder using the
http.post() method. | https://docs.flutter.dev/cookbook/networking/send-data/index.html |
aa6468b6f545-2 | Import dart:convert for access to jsonEncode to encode the data:
Use the http.post() method to send the encoded data:
The http.post() method returns a Future that contains a Response.
Future is a core Dart class for working with
asynchronous operations. A Future object represents a potential
value or error that will be available at some time in the future.
The http.Response class contains the data received from a successful
http call.
The createAlbum() method takes an argument title
that is sent to the server to create an Album.
3. Convert the http.Response to a custom Dart object
While it’s easy to make a network request,
working with a raw Future<http.Response>
isn’t very convenient. To make your life easier,
convert the http.Response into a Dart object.
Create an Album class | https://docs.flutter.dev/cookbook/networking/send-data/index.html |
aa6468b6f545-3 | Create an Album class
First, create an Album class that contains
the data from the network request.
It includes a factory constructor that
creates an Album from JSON.
Converting JSON by hand is only one option.
For more information, see the full article on
JSON and serialization.
Convert the http.Response to an Album
Use the following steps to update the createAlbum()
function to return a Future<Album>:
Convert the response body into a JSON Map with the
dart:convert package.
If the server returns a CREATED response with a status
code of 201, then convert the JSON Map into an Album
using the fromJson() factory method. | https://docs.flutter.dev/cookbook/networking/send-data/index.html |
aa6468b6f545-4 | If the server doesn’t return a CREATED response with a
status code of 201, then throw an exception.
(Even in the case of a “404 Not Found” server response,
throw an exception. Do not return null.
This is important when examining
the data in snapshot, as shown below.)
Hooray! Now you’ve got a function that sends the title to a
server to create an album.
4. Get a title from user input
Next, create a TextField to enter a title and
a ElevatedButton to send data to server.
Also define a TextEditingController to read the
user input from a TextField.
When the ElevatedButton is pressed, the _futureAlbum
is set to the value returned by createAlbum() method.
On pressing the Create Data button, make the network request,
which sends the data in the TextField to the server
as a POST request.
The Future, _futureAlbum, is used in the next step. | https://docs.flutter.dev/cookbook/networking/send-data/index.html |
aa6468b6f545-5 | 5. Display the response on screen
To display the data on screen, use the
FutureBuilder widget.
The FutureBuilder widget comes with Flutter and
makes it easy to work with asynchronous data sources.
You must provide two parameters:
The Future you want to work with. In this case,
the future returned from the createAlbum() function.
A builder function that tells Flutter what to render,
depending on the state of the Future: loading,
success, or error.
Complete example
Parse JSON in the background
Update data over the internet | https://docs.flutter.dev/cookbook/networking/send-data/index.html |
026f6380ec78-0 | Send data to the internet
Work with WebSockets
Update data over the internet
Cookbook
Networking
Update data over the internet
1. Add the http package
2. Updating data over the internet using the http package
3. Convert the http.Response to a custom Dart object
Create an Album class
Convert the http.Response to an Album
4. Get the data from the internet
5. Update the existing title from user input
5. Display the response on screen
Complete example
Updating data over the internet is necessary for most apps.
The http package has got that covered!
This recipe uses the following steps:
Add the http package.
Update data over the internet using the http package.
Convert the response into a custom Dart object. | https://docs.flutter.dev/cookbook/networking/update-data/index.html |
026f6380ec78-1 | Convert the response into a custom Dart object.
Get the data from the internet.
Update the existing title from user input.
Update and display the response on screen.
1. Add the http package
To install the http package,
add it to the dependencies section
of the pubspec.yaml file.
You can find the latest version of the
http package on pub.dev.
dependencies
http
<latest_version>
Import the http package.
2. Updating data over the internet using the http package
This recipe covers how to update an album title to the
JSONPlaceholder using the http.put() method.
The http.put() method returns a Future that contains a Response.
Future is a core Dart class for working with
async operations. A Future object represents a potential
value or error that will be available at some time in the future. | https://docs.flutter.dev/cookbook/networking/update-data/index.html |
026f6380ec78-2 | The http.Response class contains the data received from a successful
http call.
The updateAlbum() method takes an argument, title,
which is sent to the server to update the Album.
3. Convert the http.Response to a custom Dart object
While it’s easy to make a network request,
working with a raw Future<http.Response>
isn’t very convenient. To make your life easier,
convert the http.Response into a Dart object.
Create an Album class
First, create an Album class that contains the data from the
network request. It includes a factory constructor that
creates an Album from JSON.
Converting JSON by hand is only one option.
For more information, see the full article on
JSON and serialization.
Convert the http.Response to an Album
Now, use the following steps to update the updateAlbum()
function to return a Future<Album>: | https://docs.flutter.dev/cookbook/networking/update-data/index.html |
026f6380ec78-3 | Convert the response body into a JSON Map with the
dart:convert package.
If the server returns an UPDATED response with a status
code of 200, then convert the JSON Map into an Album
using the fromJson() factory method.
If the server doesn’t return an UPDATED response with a
status code of 200, then throw an exception.
(Even in the case of a “404 Not Found” server response,
throw an exception. Do not return null.
This is important when examining
the data in snapshot, as shown below.)
Hooray!
Now you’ve got a function that updates the title of an album.
4. Get the data from the internet
Get the data from internet before you can update it.
For a complete example, see the Fetch data recipe.
Ideally, you will use this method to set
_futureAlbum during initState to fetch
the data from the internet. | https://docs.flutter.dev/cookbook/networking/update-data/index.html |
026f6380ec78-4 | 5. Update the existing title from user input
Create a TextField to enter a title and a ElevatedButton
to update the data on server.
Also define a TextEditingController to
read the user input from a TextField.
When the ElevatedButton is pressed,
the _futureAlbum is set to the value returned by
updateAlbum() method.
On pressing the Update Data button, a network request
sends the data in the TextField to the server as a POST request.
The _futureAlbum variable is used in the next step.
5. Display the response on screen
To display the data on screen, use the
FutureBuilder widget.
The FutureBuilder widget comes with Flutter and
makes it easy to work with async data sources.
You must provide two parameters:
The Future you want to work with. In this case,
the future returned from the updateAlbum() function. | https://docs.flutter.dev/cookbook/networking/update-data/index.html |
026f6380ec78-5 | A builder function that tells Flutter what to render,
depending on the state of the Future: loading,
success, or error.
Complete example
Send data to the internet
Work with WebSockets | https://docs.flutter.dev/cookbook/networking/update-data/index.html |
6abb4b9be5b1-0 | Update data over the internet
Persist data with SQLite
Work with WebSockets
Cookbook
Networking
Work with WebSockets
1. Connect to a WebSocket server
2. Listen for messages from the server
How this works
3. Send data to the server
How this works
4. Close the WebSocket connection
Complete example
In addition to normal HTTP requests,
you can connect to servers using WebSockets.
WebSockets allow for two-way communication with a server
without polling.
In this example, connect to a
test WebSocket server sponsored by Lob.com.
The server sends back the same message you send to it.
This recipe uses the following steps:
Connect to a WebSocket server.
Listen for messages from the server. | https://docs.flutter.dev/cookbook/networking/web-sockets/index.html |
6abb4b9be5b1-1 | Listen for messages from the server.
Send data to the server.
Close the WebSocket connection.
1. Connect to a WebSocket server
The web_socket_channel package provides the
tools you need to connect to a WebSocket server.
The package provides a WebSocketChannel
that allows you to both listen for messages
from the server and push messages to the server.
In Flutter, use the following line to
create a WebSocketChannel that connects to a server:
2. Listen for messages from the server
Now that you’ve established a connection,
listen to messages from the server.
After sending a message to the test server,
it sends the same message back.
In this example, use a StreamBuilder
widget to listen for new messages, and a
Text widget to display them.
How this works
The WebSocketChannel provides a
Stream of messages from the server. | https://docs.flutter.dev/cookbook/networking/web-sockets/index.html |
6abb4b9be5b1-2 | The WebSocketChannel provides a
Stream of messages from the server.
The Stream class is a fundamental part of the dart:async package.
It provides a way to listen to async events from a data source.
Unlike Future, which returns a single async response,
the Stream class can deliver many events over time.
The StreamBuilder widget connects to a Stream
and asks Flutter to rebuild every time it
receives an event using the given builder() function.
3. Send data to the server
To send data to the server,
add() messages to the sink provided
by the WebSocketChannel.
How this works
The WebSocketChannel provides a
StreamSink to push messages to the server.
The StreamSink class provides a general way to add sync or async
events to a data source.
4. Close the WebSocket connection
After you’re done using the WebSocket, close the connection:
Complete example | https://docs.flutter.dev/cookbook/networking/web-sockets/index.html |
6abb4b9be5b1-3 | Complete example
Update data over the internet
Persist data with SQLite | https://docs.flutter.dev/cookbook/networking/web-sockets/index.html |
46c594c995fd-0 | Persistence
Cookbook
Persistence
Persist data with SQLite
Read and write files
Store key-value data on disk | https://docs.flutter.dev/cookbook/persistence/index.html |
baabc1f0ed57-0 | Read and write files
Play and pause a video
Store key-value data on disk
Cookbook
Persistence
Store key-value data on disk
1. Add the dependency
2. Save data
3. Read data
4. Remove data
Supported types
Testing support
Complete example
If you have a relatively small collection of key-values
to save, you can use the shared_preferences plugin.
Normally,
you would have to write native platform integrations for storing
data on both iOS and Android. Fortunately,
the shared_preferences plugin can be used to persist
key-value data on disk. The shared preferences plugin
wraps NSUserDefaults on iOS and SharedPreferences on Android,
providing a persistent store for simple data.
This recipe uses the following steps: | https://docs.flutter.dev/cookbook/persistence/key-value/index.html |
baabc1f0ed57-1 | This recipe uses the following steps:
Add the dependency.
Save data.
Read data.
Remove data.
Note:
To learn more, watch this short Package of the Week video on the shared_preferences package:
1. Add the dependency
Before starting, add the shared_preferences
plugin to the pubspec.yaml file:
dependencies
flutter
sdk
flutter
shared_preferences
<newest
version>"
2. Save data
To persist data, use the setter methods provided by the
SharedPreferences class. Setter methods are available for
various primitive types, such as setInt, setBool, and setString.
Setter methods do two things: First, synchronously update the
key-value pair in-memory. Then, persist the data to disk. | https://docs.flutter.dev/cookbook/persistence/key-value/index.html |
baabc1f0ed57-2 | 3. Read data
To read data, use the appropriate getter method provided by the
SharedPreferences class. For each setter there is a corresponding getter.
For example, you can use the getInt, getBool, and getString methods.
4. Remove data
To delete data, use the remove() method.
Supported types
Although key-value storage is easy and convenient to use,
it has limitations:
Only primitive types can be used: int, double, bool, string,
and stringList.
It’s not designed to store a lot of data.
For more information about shared preferences on Android,
see the shared preferences documentation
on the Android developers website.
Testing support
It’s a good idea to test code that persists data using
shared_preferences. You can do this by mocking out the
MethodChannel used by the shared_preferences library. | https://docs.flutter.dev/cookbook/persistence/key-value/index.html |
baabc1f0ed57-3 | Populate SharedPreferences with initial values in your tests
by running the following code in a setupAll() method in
your test files:
Complete example
Read and write files
Play and pause a video | https://docs.flutter.dev/cookbook/persistence/key-value/index.html |
874289225aa7-0 | Persist data with SQLite
Store key-value data on disk
Read and write files
Cookbook
Persistence
Read and write files
1. Find the correct local path
2. Create a reference to the file location
3. Write data to the file
4. Read data from the file
Complete example
In some cases, you need to read and write files to disk.
For example, you may need to persist data across app launches,
or download data from the internet and save it for later offline use.
To save files to disk, combine the path_provider
plugin with the dart:io library.
This recipe uses the following steps:
Find the correct local path.
Create a reference to the file location.
Write data to the file.
Read data from the file. | https://docs.flutter.dev/cookbook/persistence/reading-writing-files/index.html |
874289225aa7-1 | Write data to the file.
Read data from the file.
Note:
To learn more, watch this Package of the Week video on the path_provider package:
1. Find the correct local path
This example displays a counter. When the counter changes,
write data on disk so you can read it again when the app loads.
Where should you store this data?
The path_provider package
provides a platform-agnostic way to access commonly used locations on the
device’s file system. The plugin currently supports access to
two file system locations:
A temporary directory (cache) that the system can
clear at any time. On iOS, this corresponds to the
NSCachesDirectory. On Android, this is the value that
getCacheDir() returns.
A directory for the app to store files that only
it can access. The system clears the directory only when the app
is deleted.
On iOS, this corresponds to the NSDocumentDirectory.
On Android, this is the AppData directory. | https://docs.flutter.dev/cookbook/persistence/reading-writing-files/index.html |
874289225aa7-2 | This example stores information in the documents directory.
You can find the path to the documents directory as follows:
2. Create a reference to the file location
Once you know where to store the file, create a reference to the
file’s full location. You can use the File
class from the dart:io library to achieve this.
3. Write data to the file
Now that you have a File to work with,
use it to read and write data.
First, write some data to the file.
The counter is an integer, but is written to the
file as a string using the '$counter' syntax.
4. Read data from the file
Now that you have some data on disk, you can read it.
Once again, use the File class.
Complete example
Persist data with SQLite
Store key-value data on disk | https://docs.flutter.dev/cookbook/persistence/reading-writing-files/index.html |
e385237f8276-0 | Work with WebSockets
Read and write files
Persist data with SQLite
Cookbook
Persistence
Persist data with SQLite
1. Add the dependencies
2. Define the Dog data model
3. Open the database
4. Create the dogs table
5. Insert a Dog into the database
6. Retrieve the list of Dogs
7. Update a Dog in the database
8. Delete a Dog from the database
Example
If you are writing an app that needs to persist and query large amounts of data on
the local device, consider using a database instead of a local file or
key-value store. In general, databases provide faster inserts, updates,
and queries compared to other local persistence solutions. | https://docs.flutter.dev/cookbook/persistence/sqlite/index.html |
e385237f8276-1 | Flutter apps can make use of the SQLite databases via the
sqflite plugin available on pub.dev.
This recipe demonstrates the basics of using sqflite
to insert, read, update, and remove data about various Dogs.
If you are new to SQLite and SQL statements, review the
SQLite Tutorial to learn the basics before
completing this recipe.
This recipe uses the following steps:
Add the dependencies.
Define the Dog data model.
Open the database.
Create the dogs table.
Insert a Dog into the database.
Retrieve the list of dogs.
Update a Dog in the database.
Delete a Dog from the database.
1. Add the dependencies
To work with SQLite databases, import the sqflite and path packages.
The sqflite package provides classes and functions to
interact with a SQLite database. | https://docs.flutter.dev/cookbook/persistence/sqlite/index.html |
e385237f8276-2 | The sqflite package provides classes and functions to
interact with a SQLite database.
The path package provides functions to
define the location for storing the database on disk.
dependencies
flutter
sdk
flutter
sqflite
path
Make sure to import the packages in the file you’ll be working in.
2. Define the Dog data model
Before creating the table to store information on Dogs, take a few moments to
define the data that needs to be stored. For this example, define a Dog class
that contains three pieces of data:
A unique id, the name, and the age of each dog.
3. Open the database
Before reading and writing data to the database, open a connection
to the database. This involves two steps: | https://docs.flutter.dev/cookbook/persistence/sqlite/index.html |
e385237f8276-3 | Define the path to the database file using getDatabasesPath() from the
sqflite package, combined with the join function from the path package.
Open the database with the openDatabase() function from sqflite.
Note:
In order to use the keyword await, the code must be placed
inside an async function. You should place all the following
table functions inside void main() async {}.
4. Create the dogs table
The id is a Dart int, and is stored as an INTEGER SQLite
Datatype. It is also good practice to use an id as the primary
key for the table to improve query and update times.
The name is a Dart String, and is stored as a TEXT SQLite
Datatype.
The age is also a Dart int, and is stored as an INTEGER
Datatype.
For more information about the available Datatypes that can be stored in a
SQLite database, see the official SQLite Datatypes documentation. | https://docs.flutter.dev/cookbook/persistence/sqlite/index.html |
e385237f8276-4 | 5. Insert a Dog into the database
Now that you have a database with a table suitable for storing information
about various dogs, it’s time to read and write data.
First, insert a Dog into the dogs table. This involves two steps:
Convert the Dog into a Map
Use the insert() method to store the
Map in the dogs table.
6. Retrieve the list of Dogs
Now that a Dog is stored in the database, query the database
for a specific dog or a list of all dogs. This involves two steps:
Run a query against the dogs table. This returns a List<Map>.
Convert the List<Map> into a List<Dog>.
7. Update a Dog in the database
After inserting information into the database,
you might want to update that information at a later time.
You can do this by using the update()
method from the sqflite library. | https://docs.flutter.dev/cookbook/persistence/sqlite/index.html |
e385237f8276-5 | This involves two steps:
Convert the Dog into a Map.
Use a where clause to ensure you update the correct Dog.
Warning:
Always use whereArgs to pass arguments to a where statement.
This helps safeguard against SQL injection attacks.
Do not use string interpolation, such as where: "id = ${dog.id}"!
8. Delete a Dog from the database
In addition to inserting and updating information about Dogs,
you can also remove dogs from the database. To delete data,
use the delete() method from the sqflite library.
In this section, create a function that takes an id and deletes the dog with
a matching id from the database. To make this work, you must provide a where
clause to limit the records being deleted.
Example
To run the example:
Create a new Flutter project.
Add the sqflite and path packages to your pubspec.yaml. | https://docs.flutter.dev/cookbook/persistence/sqlite/index.html |
e385237f8276-6 | Add the sqflite and path packages to your pubspec.yaml.
Paste the following code into a new file called lib/db_test.dart.
Run the code with flutter run lib/db_test.dart.
Work with WebSockets
Read and write files | https://docs.flutter.dev/cookbook/persistence/sqlite/index.html |
0b83c3d6d593-0 | Plugins
Cookbook
Plugins
Play and pause a video
Take a picture using the camera | https://docs.flutter.dev/cookbook/plugins/index.html |
62f11d4bf3a6-0 | Play and pause a video
An introduction to integration testing
Take a picture using the camera
Cookbook
Plugins
Take a picture using the camera
1. Add the required dependencies
2. Get a list of the available cameras
3. Create and initialize the CameraController
4. Use a CameraPreview to display the camera’s feed
5. Take a picture with the CameraController
6. Display the picture with an Image widget
Complete example
Many apps require working with the device’s cameras to
take photos and videos. Flutter provides the camera plugin
for this purpose. The camera plugin provides tools to get a list of the
available cameras, display a preview coming from a specific camera,
and take photos or videos. | https://docs.flutter.dev/cookbook/plugins/picture-using-camera/index.html |
62f11d4bf3a6-1 | This recipe demonstrates how to use the camera plugin to display a preview,
take a photo, and display it using the following steps:
Add the required dependencies.
Get a list of the available cameras.
Create and initialize the CameraController.
Use a CameraPreview to display the camera’s feed.
Take a picture with the CameraController.
Display the picture with an Image widget.
1. Add the required dependencies
To complete this recipe, you need to add three dependencies to your app:
camera
Provides tools to work with the cameras on the device.
path_provider
Finds the correct paths to store images.
path
Creates paths that work on any platform.
dependencies
flutter
sdk
flutter
camera
path_provider | https://docs.flutter.dev/cookbook/plugins/picture-using-camera/index.html |
62f11d4bf3a6-2 | flutter
camera
path_provider
path
Tip:
For android, You must update minSdkVersion to 21 (or higher).
On iOS, lines below have to be added inside ios/Runner/Info.plist in order the access the camera and microphone.
<key>NSCameraUsageDescription</key>
<string>Explanation on why the camera access is needed.</string>
<key>NSMicrophoneUsageDescription</key>
<string>Explanation on why the microphone access is needed.</string>
2. Get a list of the available cameras
Next, get a list of available cameras using the camera plugin.
3. Create and initialize the CameraController | https://docs.flutter.dev/cookbook/plugins/picture-using-camera/index.html |
62f11d4bf3a6-3 | 3. Create and initialize the CameraController
Once you have a camera, use the following steps to
create and initialize a CameraController.
This process establishes a connection to
the device’s camera that allows you to control the camera
and display a preview of the camera’s feed.
Create a StatefulWidget with a companion State class.
Add a variable to the State class to store the CameraController.
Add a variable to the State class to store the Future
returned from CameraController.initialize().
Create and initialize the controller in the initState() method.
Dispose of the controller in the dispose() method.
Warning:
If you do not initialize the CameraController,
you cannot use the camera to display a preview and take pictures.
4. Use a CameraPreview to display the camera’s feed
Next, use the CameraPreview widget from the camera package to
display a preview of the camera’s feed. | https://docs.flutter.dev/cookbook/plugins/picture-using-camera/index.html |
62f11d4bf3a6-4 | Remember You must wait until the controller has finished
initializing before working with the camera. Therefore,
you must wait for the _initializeControllerFuture() created
in the previous step to complete before showing a CameraPreview.
Use a FutureBuilder for exactly this purpose.
5. Take a picture with the CameraController
takePicture() method, which returns an
XFile,
a cross-platform, simplified
In this example, create a FloatingActionButton that takes a picture
using the CameraController when a user taps on the button.
Taking a picture requires 2 steps:
Ensure that the camera is initialized.
Use the controller to take a picture and ensure that it returns a Future<XFile>.
It is good practice to wrap these operations in a try / catch block in order
to handle any errors that might occur.
6. Display the picture with an Image widget | https://docs.flutter.dev/cookbook/plugins/picture-using-camera/index.html |
62f11d4bf3a6-5 | 6. Display the picture with an Image widget
If you take the picture successfully, you can then display the saved picture
using an Image widget. In this case, the picture is stored as a file on
the device.
Therefore, you must provide a File to the Image.file constructor.
You can create an instance of the File class by passing the path created in
the previous step.
Complete example
Play and pause a video
An introduction to integration testing | https://docs.flutter.dev/cookbook/plugins/picture-using-camera/index.html |
0a52ee9cffbc-0 | Store key-value data on disk
Take a picture using the camera
Play and pause a video
Cookbook
Plugins
Play and pause a video
1. Add the video_player dependency
2. Add permissions to your app
Android
iOS
3. Create and initialize a VideoPlayerController
4. Display the video player
5. Play and pause the video
Complete example
Playing videos is a common task in app development,
and Flutter apps are no exception. To play videos,
the Flutter team provides the video_player plugin.
You can use the video_player plugin to play videos
stored on the file system, as an asset, or from the internet.
On iOS, the video_player plugin makes use of
AVPlayer to handle playback. On Android,
it uses ExoPlayer. | https://docs.flutter.dev/cookbook/plugins/play-video/index.html |
0a52ee9cffbc-1 | This recipe demonstrates how to use the video_player package to stream a
video from the internet with basic play and pause controls using
the following steps:
Add the video_player dependency.
Add permissions to your app.
Create and initialize a VideoPlayerController.
Display the video player.
Play and pause the video.
1. Add the video_player dependency
This recipe depends on one Flutter plugin: video_player. First, add this
dependency to your pubspec.yaml.
dependencies
flutter
sdk
flutter
video_player
2. Add permissions to your app
Next, update your android and ios configurations to ensure
that your app has the correct permissions to stream videos
from the internet.
Android | https://docs.flutter.dev/cookbook/plugins/play-video/index.html |
0a52ee9cffbc-2 | Android
Add the following permission to the AndroidManifest.xml file just after the
<application> definition. The AndroidManifest.xml file is found at
<project root>/android/app/src/main/AndroidManifest.xml.
<manifest
xmlns:android=
"http://schemas.android.com/apk/res/android"
<application
...
</application>
<uses-permission
android:name=
"android.permission.INTERNET"
/>
</manifest>
iOS
For iOS, add the following to the Info.plist file found at
<project root>/ios/Runner/Info.plist.
<key>NSAppTransportSecurity
</key>
<dict>
<key>NSAllowsArbitraryLoads | https://docs.flutter.dev/cookbook/plugins/play-video/index.html |
0a52ee9cffbc-3 | <dict>
<key>NSAllowsArbitraryLoads
</key>
<true/>
</dict>
Warning:
The video_player plugin doesn’t work on iOS simulators.
You must test videos on real iOS devices.
3. Create and initialize a VideoPlayerController
Now that you have the video_player plugin installed with the correct
permissions, create a VideoPlayerController. The
VideoPlayerController class allows you to connect to different types of
videos and control playback.
Before you can play videos, you must also initialize the controller.
This establishes the connection to the video and prepare the
controller for playback.
To create and initialize the VideoPlayerController do the following:
Create a StatefulWidget with a companion State class
Add a variable to the State class to store the VideoPlayerController | https://docs.flutter.dev/cookbook/plugins/play-video/index.html |
0a52ee9cffbc-4 | Add a variable to the State class to store the VideoPlayerController
Add a variable to the State class to store the Future returned from
VideoPlayerController.initialize
Create and initialize the controller in the initState method
Dispose of the controller in the dispose method
4. Display the video player
Now, display the video. The video_player plugin provides the
VideoPlayer widget to display the video initialized by
the VideoPlayerController.
By default, the VideoPlayer widget takes up as much space as possible.
This often isn’t ideal for videos because they are meant
to be displayed in a specific aspect ratio, such as 16x9 or 4x3.
Therefore, wrap the VideoPlayer widget in an AspectRatio
widget to ensure that the video has the correct proportions. | https://docs.flutter.dev/cookbook/plugins/play-video/index.html |
0a52ee9cffbc-5 | Furthermore, you must display the VideoPlayer widget after the
_initializeVideoPlayerFuture() completes. Use FutureBuilder to
display a loading spinner until the controller finishes initializing.
Note: initializing the controller does not begin playback.
5. Play and pause the video
By default, the video starts in a paused state. To begin playback,
call the play() method provided by the VideoPlayerController.
To pause playback, call the pause() method.
For this example,
add a FloatingActionButton to your app that displays a play
or pause icon depending on the situation.
When the user taps the button,
play the video if it’s currently paused,
or pause the video if it’s playing.
Complete example
Store key-value data on disk
Take a picture using the camera | https://docs.flutter.dev/cookbook/plugins/play-video/index.html |
c556916392c9-0 | Testing
Cookbook
Testing
Integration
Unit
Widget
Integration
An introduction to integration testing
Performance profiling
Unit
An introduction to unit testing
Mock dependencies using Mockito
Widget
An introduction to widget testing
Find widgets
Handle scrolling
Tap, drag, and enter text | https://docs.flutter.dev/cookbook/testing/index.html |
3d7dc9a8bbb6-0 | Integration
Cookbook
Testing
Integration
An introduction to integration testing
Performance profiling | https://docs.flutter.dev/cookbook/testing/integration/index.html |
99a6832fcc4d-0 | Take a picture using the camera
Performance profiling
An introduction to integration testing
Cookbook
Testing
Integration
Introduction
1. Create an app to test
2. Add the integration_test dependency
3. Create the test files
4. Write the integration test
5. Run the integration test
5a. Mobile
5b. Web
Unit tests and widget tests are handy for testing individual classes,
functions, or widgets. However, they generally don’t test how
individual pieces work together as a whole, or capture the performance
of an application running on a real device. These tasks are performed
with integration tests.
Integration tests are written using the integration_test package, provided
by the SDK. | https://docs.flutter.dev/cookbook/testing/integration/introduction/index.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.