flutterazureazure-functionsazure-blob-storageazure-http-trigger

how to trigger the http trigger in function using a button flutter?


I am currently trying a http trigger in azure functions. But the trigger should happen if I click a button on my flutter web application. Should I use REST API or any other way to do this. the url is

https://functionappname.azurewebsites.net/api/http_trigger?blob_name=file.text

Code

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

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

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

class MyHomePage extends StatelessWidget {
  Future<void> triggerAzureFunction() async {
    // Replace 'YOUR_FUNCTION_URL' with the URL of your Azure Function HTTP trigger
    final url = Uri.parse('YOUR_FUNCTION_URL');

    try {
      final response = await http.get(url);
      if (response.statusCode == 200) {
        print('Azure Function triggered successfully');
        // Handle success response
      } else {
        print('Failed to trigger Azure Function: ${response.statusCode}');
        // Handle failure response
      }
    } catch (e) {
      print('Failed to trigger Azure Function: $e');
      // Handle exception
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Azure Function Trigger'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: triggerAzureFunction,
          child: Text('Trigger Azure Function'),
        ),
      ),
    );
  }
}

error

Failed to trigger Azure Function: XMLHttpRequest error.

I suspected CORS so given the "*" to allow all request. Still getting the same error


Solution

  • To trigger the Http trigger function, you have to pass the function URL in the code.

    Failed to trigger Azure Function: XMLHttpRequest error.

    It is a CORS error, to resolve this error, implement a backend layer that calls the function URL.

    enter image description here

    Code Snippet:

    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Azure Function Data Fetcher',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key? key}) : super(key: key);
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      String? data;
    
      Future<void> fetchData() async {
        String url = "https://functionname.azurewebsites.net/api/HttpTrigger";
        try {
          final response = await http.get(Uri.parse(url));
    
          if (response.statusCode == 200) {
            setState(() {
              data = response.body;
            });
          } else {
            print('Failed to fetch data. Error code: ${response.statusCode}');
          }
        } catch (error) {
          print('Error fetching data: $error');
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Azure Function Data Fetcher'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                ElevatedButton(
                  onPressed: fetchData,
                  child: Text('Fetch Data from Azure Function'),
                ),
                SizedBox(height: 20),
                if (data != null)
                  Text(
                    'Data from Azure Function: $data',
                    style: TextStyle(fontSize: 16),
                  ),
              ],
            ),
          ),
        );
      }
    }
    

    enter image description here

    References:

    https://www.digitalocean.com/community/tutorials/flutter-flutter-http