how to deploy flutter in azure app services

82 Views Asked by At

Currently working on flutter web gui and handling blob storage and data visualization. The web GUI is running in local host , I want to run the app in azure app services is it possible. If possible how to do it?

when I try to create it asks for web-app or static web app.

below is the program

import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

// ignore: camel_case_types
class alt extends StatelessWidget {
  const alt({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              await main();
            },
            child: const Text('Fetch Blob Data'),
          ),
        ),
      ),
    );
  }

  Future<void> main() async {
    String sasUrl =
        'https://stroageMM.blob.core.windows.net/binfile/ledblink.bin?sp=r&st=2024-02-13T06:58:48Z&se=2024-02-13T14:58:48Z&sv=2022-11-02&sr=b&sig=aa2%2BdywACIb2jU4ErTGDtrWLpKaFJtJt60xdewlJd7o%3D';

    try {
      // Send HTTP GET request to the SAS URL
      final response = await http.get(Uri.parse(sasUrl));

      if (response.statusCode == 200) {
        // Parse response body as bytes
        Uint8List bytes = response.bodyBytes;

        // Handle the data as needed
        // For example, you can decode the bytes to a string or save them to a file
        if (kDebugMode) {
          print('Received ${bytes.length} bytes of data.');
        }

        // Example: Decode bytes to a string
        String data = String.fromCharCodes(bytes);
        if (kDebugMode) {
          print('Data: $data');
        }
      } else {
        if (kDebugMode) {
          print('Failed to fetch data: ${response.statusCode}');
        }
      }
    } catch (e) {
      if (kDebugMode) {
        print('Error fetching data: $e');
      }
    }
  }
}
1

There are 1 best solutions below

8
Sampath On

Below are the steps for deploying a Flutter web application to Azure App Services using Azure Static Web Apps:

  • Make sure Flutter is installed and configured.

Enable Web Support:

You need to run the following commands to use the beta channel and enable web support:

flutter channel beta  
flutter upgrade  
flutter config --enable-web
  • Use the flutter create command to generate a new Flutter web project:
flutter create my_flutter_web_app
  • Go into your project directory and use the flutter build web command to compile:
cd my_flutter_web_app
flutter build web
  • Use the command below to run your Flutter web application in a Chrome browser:
flutter run -d chrome
  • Add staticwebapp.config.json in the root path (or) in my_flutter_web_app:
{
  "navigationFallback": {
    "rewrite": "index.html"
  }
}
  • Make sure to install Node.js, Azure Functions Core Tools, and Azure Static Web Apps CLI, and then install the following NPM packages:
npm install -g azure-functions-core-tools

npm install -g @azure/static-web-apps-cli
  • Use the swa init command to set up the configuration for deploying your app to Azure Static Web Apps:
swa init

enter image description here

  • Check swa-cli.config.json in the root path:
{
  "$schema": "https://aka.ms/azure/static-web-apps-cli/schema",
  "configurations": {
    "my-flutter-web-app": {
      "appLocation": ".",
      "outputLocation": "build\\web",
      "appBuildCommand": "flutter build web",
      "run": "flutter run -d edge --web-port 8080 ",
      "appDevserverUrl": "http://localhost:8080"
    }
  }
}
  • Use the swa build command to build your Flutter web app in preparation for deployment.

enter image description here

  • Use the swa deploy command to deploy your app to Azure App Services using Azure Static Web Apps.

enter image description here

enter image description here

  • Install the packages below:
dart pub global activate flutter_cors
flutter pub add http

The below sample Flutter web GUI code connects to Azure Blob Storage using a SAS URL and visualizes data in the UI:

lib/main.dart:


import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:typed_data';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: alt(),
    );
  }
}

class alt extends StatefulWidget {
  const alt({Key? key}) : super(key: key);

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

class _altState extends State<alt> {
  String? fetchedData;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Fetch Blob Data'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () async {
                await fetchData();
              },
              child: const Text('Fetch Blob Data'),
            ),
            SizedBox(height: 20),
            fetchedData != null
                ? Expanded(
                    child: SingleChildScrollView(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Text(
                          fetchedData!,
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                    ),
                  )
                : Container(),
          ],
        ),
      ),
    );
  }

  Future<void> fetchData() async {
    String sasUrl =
        'https://example.blob.core.windows.net/container/HelloWorld.txt?sp=r&st=2024-03-29T15:29:53Z&se=2024-03-29T23:29:53Z&sv=2022-11-02&sr=b&sig=SampleSignature
';

    try {
      // Send HTTP GET request to the SAS URL
      final response = await http.get(Uri.parse(sasUrl));

      if (response.statusCode == 200) {
        // Parse response body as bytes
        Uint8List bytes = response.bodyBytes;

        // Handle the data as needed
        // For example, you can decode the bytes to a string or save them to a file
        print('Received ${bytes.length} bytes of data.');

        // Example: Decode bytes to a string
        String data = String.fromCharCodes(bytes);
        setState(() {
          fetchedData = data;
        });
      } else {
        print('Failed to fetch data: ${response.statusCode}');
      }
    } catch (e) {
      print('Error fetching data: $e');
    }
  }
}




Azure Storage: enter image description here

  • Add CORS in the Azure portal for storage.

enter image description here

  • Make that the application is built and run.

enter image description here

  • Use swa build and swa deploy to build and deploy to Azure.

enter image description here