Flutter webview localhost

Flutter WebView – localhost

When using Flutter WebView to load content from localhost, there are a few steps you need to follow.

  1. Make sure your localhost server is running and accessible on your development machine.
  2. Add the internet permission to your AndroidManifest.xml file:
  3. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.your_app">
    
        <uses-permission android:name="android.permission.INTERNET" />
    
        <application
            ...
        </application>
    
    </manifest>
        
  4. Add the webview_flutter package to your pubspec.yaml file:
  5. dependencies:
      flutter:
        sdk: flutter
      webview_flutter: ^1.0.7
        
  6. Import the necessary libraries in your Dart file:
  7. import 'package:flutter/material.dart';
    import 'package:webview_flutter/webview_flutter.dart';
        
  8. Create a WebView widget in your widget tree:
  9. class MyWebView extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('WebView'),
          ),
          body: WebView(
            initialUrl: 'http://localhost:8000',
            javascriptMode: JavascriptMode.unrestricted,
          ),
        );
      }
    }
        

    In this example, we have a simple WebView widget that loads the content from “http://localhost:8000”. You can replace this URL with your own localhost URL and port number.

    Note that we have set the javascriptMode to JavascriptMode.unrestricted to enable JavaScript execution in the WebView.

  10. Add the MyWebView widget to your app’s main widget:
  11. void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter WebView',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyWebView(),
        );
      }
    }
        

    Now, when you run your app, it should load the content from your localhost server in the WebView.

Make sure to replace http://localhost:8000 with your own localhost URL. Also, note that using WebView with localhost may not work on iOS due to security restrictions. In that case, you can consider using a remote server or API endpoint.

Leave a comment