Flutter WebView – localhost
When using Flutter WebView to load content from localhost, there are a few steps you need to follow.
- Make sure your localhost server is running and accessible on your development machine.
- Add the internet permission to your AndroidManifest.xml file:
- Add the webview_flutter package to your pubspec.yaml file:
- Import the necessary libraries in your Dart file:
- Create a WebView widget in your widget tree:
- Add the MyWebView widget to your app’s main widget:
<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>
dependencies: flutter: sdk: flutter webview_flutter: ^1.0.7
import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart';
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.
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.