### Initialize Nutrient Flutter SDK
Source: https://www.nutrient.io/sdk/flutter/getting-started
This code snippet demonstrates the basic initialization of the Nutrient Flutter SDK. Ensure you have the SDK installed as a dependency in your Flutter project.
```dart
import 'package:nutrient_sdk/nutrient_sdk.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await NutrientFlutterSDK.initialize(apiKey: 'YOUR_API_KEY');
runApp(MyApp());
}
```
--------------------------------
### Initialize Nutrient Flutter SDK
Source: https://www.nutrient.io/sdk/flutter/getting-started
Initializes the Nutrient Flutter SDK, which is required since version 3.9.0. Pass a license key for production or null for trial (with a watermark). This setup is crucial before using any Nutrient functionalities.
```dart
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:nutrient_flutter/nutrient_flutter.dart';
const String documentPath = 'PDFs/Document.pdf';
void main() {
WidgetsFlutterBinding.ensureInitialized();
// Initialize Nutrient with the license key. Pass `null` to use the trial version.
Nutrient.initialize(androidLicenseKey: null, iosLicenseKey: null);
runApp(const MaterialApp(
home: MyApp(),
));
}
```
--------------------------------
### Initialize Flutter App with Nutrient
Source: https://www.nutrient.io/sdk/flutter/getting-started
This is the main entry point for a Flutter application. It initializes the Nutrient library and starts the application's root widget.
```dart
void main(){
Nutrient.initialize();
runApp(const MyApp());
}
```
--------------------------------
### Handle Document Load Events in Flutter
Source: https://www.nutrient.io/sdk/flutter/getting-started
This example shows how to listen for and react to document loading events using the Nutrient Flutter SDK. This is useful for showing loading indicators or performing actions once a document is ready.
```dart
import 'package:flutter/material.dart';
import 'package:nutrient_sdk/nutrient_sdk.dart';
NutrientPdfViewer(
pdfUrl: 'your_pdf_url.pdf',
onDocumentLoaded: () {
print('Document loaded successfully!');
// Perform actions after document is loaded
},
onDocumentError: (error) {
print('Error loading document: $error');
// Handle loading errors
},
)
```
--------------------------------
### Include Nutrient Web SDK from Local Installation in HTML
Source: https://www.nutrient.io/sdk/flutter/getting-started
This snippet demonstrates how to include the Nutrient Web SDK in your HTML file after a local installation. It assumes the `nutrient-viewer.js` file is placed in your `assets` folder.
```html
```
--------------------------------
### Create New Flutter Project
Source: https://www.nutrient.io/sdk/flutter/getting-started
Command to create a new Flutter project named 'nutrient_demo' with a specified organization identifier. This is a foundational step for integrating new Flutter libraries.
```bash
flutter create --org com.example.nutrient_demo nutrient_demo
```
--------------------------------
### Run Flutter Application
Source: https://www.nutrient.io/sdk/flutter/getting-started
This terminal command executes the Flutter application on a connected device or emulator. Ensure that an emulator is running or a device is connected before executing this command.
```bash
flutter run
```
--------------------------------
### Add AppCompat Dependency to Gradle
Source: https://www.nutrient.io/sdk/flutter/getting-started
Include the AppCompat AndroidX library in your `android/app/build.gradle` file's dependencies. Replace `` with the latest stable version from a Maven repository to leverage its features for UI compatibility.
```gradle
dependencies {
...
implementation "androidx.appcompat:appcompat:"
}
```
--------------------------------
### Create and Copy PDF Assets in Flutter
Source: https://www.nutrient.io/sdk/flutter/getting-started
These terminal commands demonstrate how to create a 'PDFs' directory and copy a PDF document into it, which is a necessary step for including assets in a Flutter application. This setup is crucial for displaying local PDF files within the app.
```bash
mkdir PDFs
```
```bash
cp ~/Downloads/Document.pdf PDFs/Document.pdf
```
--------------------------------
### Include Nutrient Web SDK via CDN in HTML
Source: https://www.nutrient.io/sdk/flutter/getting-started
This snippet shows how to add the Nutrient Web SDK to your HTML file using a CDN link. Ensure this is placed within the `` section. Replace `` with your desired SDK version.
```html
```
--------------------------------
### Configure Android Launcher Activity for Flutter (XML)
Source: https://www.nutrient.io/sdk/flutter/getting-started
This XML snippet shows how to update the `AndroidManifest.xml` file to use `FlutterAppCompatActivity` as the launcher activity. This is necessary for integrating the Nutrient Android SDK with Flutter applications.
```xml
```
--------------------------------
### Open AI Chat with Context (JavaScript)
Source: https://www.nutrient.io/sdk/flutter/getting-started
Generates a pre-filled prompt for AI chat services (ChatGPT, Claude, Grok) that includes the current page's URL and a request for assistance with the documentation. It opens the respective AI chat service in a new tab with the prompt ready.
```javascript
function v(i) {
const t = "https://www.nutrient.io",
o = window.location.pathname,
r = `I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`;
const s = `https://chatgpt.com/?q=${encodeURIComponent(r)}`;
window.open(s, "_blank");
}
function x(i) {
const t = "https://www.nutrient.io",
o = window.location.pathname,
r = `I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`;
const s = `https://claude.ai/new?q=${encodeURIComponent(r)}`;
window.open(s, "_blank");
}
function C(i) {
const t = "https://www.nutrient.io",
o = window.location.pathname,
r = `I'm looking at this Nutrient documentation: ${`${t}${o}`} Help me understand how to use it. Be ready to explain concepts, give examples, or help debug based on it.`;
const s = `https://grok.com/c?q=${encodeURIComponent(r)}`;
window.open(s, "_blank");
}
```
--------------------------------
### Load and Configure Kapa.ai Chatbot Widget
Source: https://www.nutrient.io/sdk/flutter/getting-started
This JavaScript function dynamically creates and configures the Kapa.ai chatbot widget. It determines the appropriate disclaimer and example questions based on the current URL path and applies numerous attributes to customize the widget's appearance and behavior, such as colors, fonts, button styles, and z-index.
```javascript
function u(){
const a=d(),t=document.createElement("script");
t.async=!0,t.src="https://widget.kapa.ai/kapa-widget.bundle.js",t.setAttribute("data-website-id","ec76a086-c5ce-409a-91bb-bee358fdb208"),t.setAttribute("data-project-color","#1A1414"),t.setAttribute("data-text-color","#1A1414"),t.setAttribute("data-modal-override-open-id","nutrient-sdk-docs-ai"),t.setAttribute("data-button-hide","false"),t.setAttribute("data-modal-open-by-default","true"),t.setAttribute("data-user-analytics-fingerprint-enabled","true"),t.setAttribute("data-project-name","Nutrient"),t.setAttribute("data-modal-title","Nutrient AI"),t.setAttribute("data-modal-disclaimer",a.modalDisclaimer),t.setAttribute("data-example-questions",a.exampleQuestions),t.setAttribute("data-modal-disclaimer-bg-color","#EFEBE7"),t.setAttribute("data-modal-disclaimer-text-color","#67594B"),t.setAttribute("data-modal-disclaimer-font-size","14px"),t.setAttribute("data-modal-disclaimer-padding","0.875rem"),t.setAttribute("data-query-input-font-size","1rem"),t.setAttribute("data-query-input-text-color","#1A1414"),t.setAttribute("data-query-input-placeholder-text-color","#67594B"),t.setAttribute("data-query-input-border-color","#1A1414"),t.setAttribute("data-query-input-focus-border-color","#DE9DCC"),t.setAttribute("data-submit-query-button-bg-color","#1A1414"),t.setAttribute("data-example-question-button-height","40px"),t.setAttribute("data-example-question-button-padding-x","1.5rem"),t.setAttribute("data-example-question-button-padding-y","0.75rem"),t.setAttribute("data-example-question-button-border","1px solid #C2B8AE !important"),t.setAttribute("data-example-question-button-border-radius","8px"),t.setAttribute("data-example-question-button-text-color","#1A1414"),t.setAttribute("data-example-question-button-box-shadow","none"),t.setAttribute("data-example-question-button-font-size","0.875rem"),t.setAttribute("data-example-question-button-hover-bg-color","#EFEBE7"),t.setAttribute("data-modal-z-index","999999"),t.setAttribute("data-modal-border-radius","1.5rem"),t.setAttribute("data-modal-header-bg-color","#DE9DCC"),t.setAttribute("data-modal-header-border-bottom","none"),t.setAttribute("data-modal-header-padding","1.5rem"),t.setAttribute("data-modal-title-font-weight","400"),t.setAttribute("data-modal-title-font-size","1.5rem"),t.setAttribute("data-modal-title-color","#1A1414"),t.setAttribute("data-button-text","ASK AI"),t.setAttribute("data-button-height","5rem"),t.setAttribute("data-button-width","5rem"),t.setAttribute("data-button-bg-color","#1A1414"),t.setAttribute("data-button-border-radius","1rem"),t.setAttribute("data-button-text-shadow","none"),t.setAttribute("data-button-text-font-weight","400"),t.setAttribute("data-button-text-font-size","0.75rem"),t.setAttribute("data-button-image-height","1.5rem"),t.setAttribute("data-button-image-width","1.5rem"),t.setAttribute("data-thread-clear-button-height","40px"),t.setAttribute("data-thread-clear-button-padding-x","16px"),t.setAttribute("data-thread-clear-button-padding-y","8px"),t.setAttribute("data-thread-clear-button-border","none"),t.setAttribute("data-thread-clear-button-border-radius","8px"),t.setAttribute("data-thread-clear-button-bg-color","#EFEBE7"),t.setAttribute("data-thread-clear-button-hover-bg-color","#E2DBD9"),t.setAttribute("data-thread-clear-button-text-color","#1A1414"),t.setAttribute("data-thread-clear-button-font-size","12px"),t.setAttribute("data-thread-clear-button-icon-size","24px")
document.body.appendChild(t)}
```
--------------------------------
### Flutter PDF Display with Nutrient Package
Source: https://www.nutrient.io/sdk/flutter/getting-started
Demonstrates how to display a PDF document within a Flutter application using the Nutrient package. This involves importing the package and using the NutrientView widget, providing the path to the PDF file.
```dart
import 'package:nutrient_flutter/nutrient_flutter.dart';
// ... inside your Flutter widget ...
Scaffold(
body: NutrientView(
documentPath: 'file:///path/to/Document.pdf',
),
);
```
--------------------------------
### Display a PDF Document in Flutter
Source: https://www.nutrient.io/sdk/flutter/getting-started
This example shows how to display a PDF document using the Nutrient Flutter SDK's PDF viewer widget. You'll need to provide a valid PDF URL or file path.
```dart
import 'package:flutter/material.dart';
import 'package:nutrient_sdk/nutrient_sdk.dart';
class PdfViewerScreen extends StatelessWidget {
final String pdfUrl;
const PdfViewerScreen({Key? key, required this.pdfUrl}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('PDF Viewer'))
body: NutrientPdfViewer(pdfUrl: pdfUrl),
);
}
}
```
--------------------------------
### Load and Display PDF in Flutter
Source: https://www.nutrient.io/sdk/flutter/getting-started
A Flutter widget that extracts a PDF document from assets and displays it using the NutrientView. Handles web and native platforms, temporary file creation, and loading states with error and progress indicators.
```dart
class MyApp extends StatelessWidget {
const MyApp({super.key});
Future extractAsset(BuildContext context, String assetPath) async {
if (kIsWeb) {
return assetPath;
}
final bytes = await DefaultAssetBundle.of(context).load(assetPath);
final list = bytes.buffer.asUint8List();
final tempDir = await Nutrient.getTemporaryDirectory();
final tempDocumentPath = '${tempDir.path}/$assetPath';
final file = File(tempDocumentPath);
await file.create(recursive: true);
file.writeAsBytesSync(list);
return file.path;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: extractAsset(context, documentPath),
builder: (context, snapshot) {
if (snapshot.hasData) {
/// NutrientView is a widget that displays a PDF document.
return NutrientView(
documentPath: snapshot.data!,
);
} else if (snapshot.hasError) {
return Center(
child: Text('${snapshot.error}'),
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
}),
);
}
}
```
--------------------------------
### Initialize VWO with settings and script loading
Source: https://www.nutrient.io/sdk/flutter/getting-started
This snippet shows the initialization process for VWO. It checks for VWO disable flags, retrieves settings, and constructs a URL to load the VWO JavaScript. It then either loads the script directly or via an XHR request based on the URL parameters. Initialization is deferred to prevent render blocking.
```javascript
if(d.URL.indexOf('__vwo_disable__')>-1)return; var e=this.settings_tolerance(); w._vwo_settings_timer=setTimeout(function(){
_vwo_code.finish(); stT.removeItem(cK) },e);
var o=window._vis_opt_url||d.URL, s='https://dev.visualwebsiteoptimizer.com/j.php?a='+account_id+'&u='+encodeURIComponent(o)+'&vn='+version; if(w.location.search.indexOf('_vwo_xhr')!==-1){ this.addScript({src:s}) }else{ this.load(s+'&x=true') }
// Defer initialization to prevent render blocking if(d.readyState === 'loading') { d.addEventListener('DOMContentLoaded', function() { code.init(); }); } else {
if('requestIdleCallback' in w) { requestIdleCallback(function() { code.init(); }, {timeout: 1000}); } else { setTimeout(function() { code.init(); }, 0); } }
```
--------------------------------
### Open Xcode Workspace
Source: https://www.nutrient.io/sdk/flutter/getting-started
Opens the Runner.xcworkspace file located in the ios folder of your project using the terminal. This action is typically performed to start development or make configuration changes within Xcode.
```bash
open ios/Runner.xcworkspace
```
--------------------------------
### Integrate Visual Website Optimizer (VWO) Script (JavaScript)
Source: https://www.nutrient.io/sdk/flutter/getting-started
This snippet initializes the VWO (Visual Website Optimizer) tracking script. It retrieves account ID and version from the inline script, then attempts to load VWO settings from local storage. It includes logic for managing settings tolerance and handling script loading, providing a fallback if VWO is not already present.
```javascript
window._vwo_code || (function() {
var account_id = 892495,
version = 2.1,
settings_tolerance = 2000,
hide_element = '', // Don't hide body to prevent flash
hide_element_style = '',
/* DO NOT EDIT BELOW THIS LINE */
f = false,
w = window,
d = document,
v = d.querySelector('#vwoCode'),
cK = '_vwo_' + account_id + '_settings',
cc = {};
try {
var c = JSON.parse(localStorage.getItem('_vwo_' + account_id + '_config'));
cc = c && typeof c === 'object' ? c : {};
} catch (e) {}
var stT = cc.stT == 'session' ? w.sessionStorage : w.localStorage;
var code = {
nonce: v && v.nonce,
library_tolerance: function() {
return typeof library_tolerance !== 'undefined' ? library_tolerance : undefined;
},
settings_tolerance: function() {
return cc.sT || settings_tolerance;
},
hide_element_style: function() {
return '{' + (cc.hES || hide_element_style) + '}';
},
hide_element: function() {
// Always return empty to prevent hiding
return '';
},
getVersion: function() {
return version;
},
finish: function(e) {
if (!f) {
f = true;
var t = d.getElementById('_vis_opt_path_hides');
if (t) t.parentNode.removeChild(t);
if (e) (new Image).src = 'https://dev.visualwebsiteoptimizer.com/ee.gif?a=' + account_id + e;
}
},
finished: function() {
return f;
},
addScript: function(e) {
var t = d.createElement('script');
t.type = 'text/javascript';
if (e.src) {
t.src = e.src;
t.async = true; // Make async
} else {
t.text = e.text;
}
v && t.setAttribute('nonce', v.nonce);
d.getElementsByTagName('head')[0].appendChild(t);
},
load: function(e, t) {
var n = this.getSettings(),
i = d.createElement('script'),
r = this;
t = t || {};
if (n) {
i.textContent = n;
d.getElementsByTagName('head')[0].appendChild(i);
if (!w.VWO || VWO.caE) {
stT.removeI
```
--------------------------------
### Update App Theme for Nutrient Android SDK (XML)
Source: https://www.nutrient.io/sdk/flutter/getting-started
These XML snippets demonstrate how to update the theme in `styles.xml` and `styles-night.xml` to use `PSPDFKit.Theme.Default` as the parent. This customization is required for the Nutrient UI when using the Nutrient Android SDK.
```xml