ids_material_sdk 3.9.8 copy "ids_material_sdk: ^3.9.8" to clipboard
ids_material_sdk: ^3.9.8 copied to clipboard

IDS Material SDK for Flutter offers fast networking, cache optimisation, custom widgets like Multi-Select DropDown, theming tools, and performance boosts to reduce server costs.

example/main.dart

import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:ids_material_sdk/ids_api_manager.dart';
import 'package:ids_material_sdk/public/index.dart';
import 'package:ids_material_sdk/src/cryptos/ids_crypto_configuration.dart';
import 'package:ids_material_sdk/src/cryptos/ids_crypto_manager.dart';
import 'package:ids_material_sdk/ui/widget/fields/ids_field_title.dart';
import 'package:ids_material_sdk/ui/widget/fields/ids_text_area_title.dart';
import 'package:ids_material_sdk/ui/widget/fields/ids_uitextfield.dart';
import 'package:ids_material_sdk/ui/widget/ids_dropdown.dart';
import 'package:ids_material_sdk/ui/widget/ids_dropdown_string.dart';
import 'package:ids_material_sdk/ui/widget/ids_dropdown_title.dart';
import 'package:ids_material_sdk/ui/widget/ids_multiselect_drop_down.dart';
import 'package:ids_material_sdk/ui/widget/theme.dart';
import 'package:ids_material_sdk/utilities/ids_enum_common.dart';
import 'package:ids_material_sdk/utilities/ids_helper.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  final TextEditingController _editingController = TextEditingController();
  List<String> selectedJobRole = [];
  List<String> jobRole = []; // Placeholder for job role list
  String _selectedValue = "";

  @override
  void initState() {
    super.initState();
    // Example network request when the widget initializes
    makeApiCalls();
  }

  ///[07-04-2025] Example: AES-256-CBC Encryption and Decryption Using IDSCryptoManager
  /// IDSCryptoConfiguration
  void cryptoExample() {
    // Sample payload to encrypt
    Map<String, dynamic> param = {
      "username": "8967564321",
      "countryCode": "+91"
    };
    // Step 1: Convert your data to JSON string
    final jsonData = jsonEncode(param);
    debugPrint("Sending this JSON to be encrypted: $jsonData");

    // Step 2: Create an instance of IDSCryptoConfiguration with a secure password
    final crypto = IDSCryptoConfiguration(
      password: 'b6edf65dd8e3db',
    );

    // Step 3: Use the high-level manager to handle encryption/decryption
    final cryptoManager = IDSCryptoManager(crypto: crypto);

    // Step 4: Encrypt the data
    final encrypted = cryptoManager.encryptText(jsonData);
    debugPrint('\nEncrypted Text:\n$encrypted\n');

    // Step 5: Decrypt the data back to its original form
    final decrypted = cryptoManager.decryptText(encrypted);
    debugPrint('Decrypted Text:\n$decrypted');
  }

  // Example of form data based API call
  void makeApiCalls() {
    var request = {"UserName": "ddd", "Password": "ddd"};
    // Example: Upload form data (POST)
    final Future<Map<String, dynamic>> apiResponse = IDSApiManager()
        .uploadFormData("http://ids.com/api/v1/login", request,
            "local-url-path-of-file", {"Connection": "keep-alive"});
    apiResponse.then((response) {
      IDSHelper.debugJSON(response);
    });

    // Example: POST form data (returns array)
    /**
     * Example code of networking api. use case is that when api return the array response. use the below sample code snippet in your project, This code snipped is for form data based api.
     */
    final Future<List<dynamic>> apiResponse1 = IDSApiManager()
        .postFormDataInBgArray("http://ids.com/api/v1/login", request,
            {"Connection": "keep-alive"});
    apiResponse1.then((response) {
      IDSHelper.debugJSON(response);
    });

    // Example: Get request
    /**
     * Example code of networking api. use the below sample code snippet in your project, This code snipped is for get method.
     */
    final Future<Map<String, dynamic>> apiResponse2 =
        IDSApiManager().getInBg("http://ids.com/api/v1/getUsers", {});
    apiResponse2.then((response) {
      IDSHelper.debugJSON(response);
    });

    // Example: Upload file with parameters
    /**
     * Example code of networking api. use the below sample code snippet in your project, This code snipped is upload the file with parameters.
     */
    var request2 = {"UserName": "ddd", "Password": "ddd"};
    final Future<Map<String, dynamic>> apiResponse3 = IDSApiManager()
        .uploadFormData("http://ids.com/api/v1/uploadDocuments", request2,
            "local-url-path-of-file", {"Connection": "keep-alive"});
    apiResponse3.then((response) {
      IDSHelper.debugJSON(response);
    });

    // Example: POST JSON payload
    /**
     * Example code of networking api. use the below sample code snippet in your project, This code snipped is for json body payload based api.
     */
    var request3 = {"UserName": "ddd", "Password": "ddd"};
    final Future<Map<String, dynamic>> apiResponse4 = IDSApiManager().postInBg(
        "http://ids.com/api/v1/login", request3, {"Connection": "keep-alive"});
    apiResponse4.then((response) {
      IDSHelper.debugJSON(response);
    });

    /**
     * Example code of networking api. use the below sample code snippet in your project, This code snipped is for form data based api.
     */
    var request4 = {"UserName": "ddd", "Password": "ddd"};
    final Future<Map<String, dynamic>> apiResponse5 = IDSApiManager()
        .postFormDataInBg("http://ids.com/api/v1/login", request4,
            {"Connection": "keep-alive"}, IDSMethodType.post);
    apiResponse5.then((response) => {IDSHelper.debugJSON(response)});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('IDS Material SDK Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // TextField Example
            /**
             * Example code of texfield. use the below sample code snippet in your project.
             */
            IDSUITextField(
              controller: _editingController,
              hintText: "Password",
              prefixIcon: Icons.lock,
              prefixIconColor: Colors.grey,
              hintTextColor: Colors.grey,
              textColor: Colors.black,
              borderColor: Colors.grey,
              focusedBorderColor: Colors.deepOrangeAccent,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Password is required';
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            // MultiSelect DropDown Example
            IDSMultiSelectDropDown(
              limit: 3,
              onChanged: (List<String> selected) {
                setState(() {
                  selectedJobRole = selected;
                });
              },
              options: jobRole,
              selectedValues: selectedJobRole,
              onLimitMessage: (limit) {
                // Show toast or snackbar for limit reached
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text("You can only select $limit items")),
                );
              },
              whenEmpty: 'Select Job Role',
            ),
            const SizedBox(height: 16),

            ///IDSFieldTitle code snippet
            IDSFieldTitle(
              title: "Descriptions",
              controller: _editingController,
              hintText: "bill entry",
              hintTextColor: Colors.grey,
              textColor: Colors.black,
              borderColor: Colors.grey,
              focusedBorderColor: Colors.red,
              circularRadius: 8.0,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return "Description cannot be empty";
                }
                return null;
              },
            ),

            ///IDSDropdownTitle code snippet
            IDSDropdownTitle(
                title: 'DISPATCH MODE',
                selectedValue: "selected value",
                onTap: () {
                  debugPrint("callback");
                }),

            /// IDSTextAreaTitle code snippet
            kHeight(10),
            IDSTextAreaTitle(
                title: "Descriptions *",
                height: 160,
                controller: _editingController,
                hintText: "Enter Description",
                hintTextColor: Colors.grey,
                textColor: Colors.black,
                borderColor: Colors.grey,
                focusedBorderColor: Colors.red,
                circularRadius: 8.0,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return "Description cannot be empty";
                  }
                  return null;
                },
                maxLines: 20),
            kHeight(10),

            /// IDSChipsRadioGroup code snippet
            IDSChipsRadioGroup(
              options: ["Yes", "No"],
              selectedOption: _selectedValue,
              onChanged: (value) {
                setState(() {
                  _selectedValue = value;
                });
              },
              chipsHeight: 40,
              chipsSelectedBgColor: Colors.indigoAccent,
            ),
            kHeight(10),
            // Dropdown Button Example
            ElevatedButton(
              onPressed: () {
                navigateToIDSDropDown(context, 1, 'jobRole', jobRole);
              },
              child: const Text('Show Dropdown'),
            ),

            kHeight(10),

            /// UIStepProgressWidget code example
            const Padding(
              padding: EdgeInsets.zero,
              child: UIStepProgressWidget(
                totalSteps: 4,
                currentStep: 1,
                height: 12,
                activeColor: Colors.red,
                inactiveColor: Colors.grey,
                horizontalMargin: 5,
              ),
            ),
            kHeight(10),

            ///  UIProgressIndicator code example
            const Padding(
              padding: EdgeInsets.zero,
              child: UIProgressIndicator(
                progressValue: 0.5,
                height: 12,
                activeColor: Colors.blue,
                inactiveColor: Colors.grey,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // Method to navigate to IDSDropDown dialog
  void navigateToIDSDropDown(
      BuildContext context, int code, String key, List<dynamic>? array) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Center(
          child: Dialog(
            shape: const RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: IDSDropDown(
              appBarBg: Colors.red,
              requestedCode: code,
              jsonKeyName: key,
              dropDownArray: array,
              callback: (requestedCode, json) {
                if (requestedCode == 1) {
                  // Handle selection logic here
                  // Example:
                  // setState(() {
                  //   selectedJobRole = json["name"];
                  // });
                }
              },
            ),
          ),
        );
      },
    );
  }

  // Method to navigate to IDSDropDownString dialog
  void navigateToIDSDropDownString(
      BuildContext context, int code, List<String> array) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Center(
          child: Dialog(
            shape: const RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: SizedBox(
              height: MediaQuery.of(context).size.width,
              child: IDSDropDownString(
                appBarBg: Colors.red,
                requestedCode: code,
                dropDownArray: array,
                callback: (requestedCode, value) {
                  if (requestedCode == 1) {
                    // Handle string selection logic
                  }
                },
              ),
            ),
          ),
        );
      },
    );
  }

  /// Multi part form data upload to any server
  /// uploadFormData
  Future<void> uploadFormData() async {
    var request = {
      "earthing_value": "2",
      "power_value": "3.4",
    };
    Map<String, String>? filesUpload = {
      "customer_signature": "file-path-replace-here",
      "engineer_signature": "file-path-replace-here"
    };

    IDSHelper.debugJSON(request);
    var header = {"Connection": "keep-alive", "Authorization": "Bearer token"};

    final Future<Map<String, dynamic>> apiResponse = IDSApiManager()
        .uploadMultiPartFormData(
            endPoint: 'api-end-point-here',
            payloadParams: request,
            fileUploads: filesUpload,
            headers: header,
            method: IDSMethodType.post);
    apiResponse.then((response) => {
          IDSHelper.debugJSON(response),
          setState(() {}),
        });
  }

  /// Example usage demonstrating how to use the [IDSDownloadManager] to download files
  /// import this line  import 'package:ids_material_sdk/downloads/index.dart';
  void exampleUsage(String fileUrl) {
    IDSDownloadManager.instance.download(
      url: fileUrl,
      success: (fileBytes) async {
        // Handle successful download, e.g., display the file
        //print('Download successful. File size: ${fileBytes.lengthInBytes} bytes');
        /* /// path_provider add this in your pub file if not exist
        final fileName = fileUrl.split('/').last;
        final tempDir = await getTemporaryDirectory();
        final file = File('${tempDir.path}/$fileName');
        await file.writeAsBytes(fileBytes.lengthInBytes as List<int>);*/
      },
      failure: (error) {
        // Handle download error
        //print('Download failed with error: $error');
      },
    );
  }

  /// Internet connection example
  Future<void> checkConnection() async {
    // 1. Check the current internet connection status
    bool isConnected = await IDSInternetChecker.isConnected();
    if (kDebugMode) {
      print("status is = $isConnected");
    }
    // 2. Listen for changes in internet connectivity status
    IDSInternetChecker.onConnectionChange.listen((isConnected) {
      if (isConnected) {
        // 3. Handle internet reconnection
        if (kDebugMode) {
          print("Internet reconnected");
        }
      } else {
        // 4. Handle internet disconnection
        if (kDebugMode) {
          print("Internet connection lost");
        }
      }
    });
  }

  void loaderExample() async {
    IDSLoader(context).showLoader();
    try {
      await Future.delayed(
          const Duration(seconds: 3)); // Simulate a network call
    } finally {
      IDSLoader(mounted ? context : context).hideLoader();
    }
  }
}
26
likes
160
points
236
downloads

Publisher

verified publisherivandigitalsolutions.com

Weekly Downloads

IDS Material SDK for Flutter offers fast networking, cache optimisation, custom widgets like Multi-Select DropDown, theming tools, and performance boosts to reduce server costs.

Repository (GitHub)

Documentation

API reference

License

MIT (license)

Dependencies

connectivity_plus, crypto, encrypt, flutter, flutter_html, html_unescape, http, internet_connection_checker, logger, states_rebuilder, xml

More

Packages that depend on ids_material_sdk