main.dart
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/legacy.dart';
import 'package:flutter/services.dart';
final navIndexProvider = StateProvider((ref) => 0);
// ローカルサーバーのインスタンス(シングルトン推奨)
final localhostServerProvider = Provider((ref) => InAppLocalhostServer());
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 画面の向きを横向きに固定
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft, // 横向き(左)
// DeviceOrientation.landscapeRight, // 横向き(右)
]).then((_) {
runApp(ProviderScope(child: MaterialApp(
debugShowCheckedModeBanner: false,
home: MainScreen()
)));
});
}
class MainScreen extends ConsumerStatefulWidget {
@override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends ConsumerState {
InAppWebViewController? webViewController;
final List pages = ["index1.html", "index2.html", "index3.html"];
@override
void initState() {
super.initState();
// ローカルサーバーの起動
ref.read(localhostServerProvider).start();
}
@override
Widget build(BuildContext context) {
final selectedIndex = ref.watch(navIndexProvider);
return Scaffold(
body: Row(
children: [
NavigationRail(
selectedIndex: selectedIndex,
onDestinationSelected: (index) {
ref.read(navIndexProvider.notifier).state = index;
webViewController?.loadUrl(
urlRequest: URLRequest(
url: WebUri("http://localhost:8080/html/${pages[index]}"),
),
);
},
labelType: NavigationRailLabelType.all,
backgroundColor: Colors.transparent,
destinations: const [
NavigationRailDestination(icon: Icon(Icons.home), label: Text('Home')),
NavigationRailDestination(icon: Icon(Icons.settings), label: Text('Settings')),
NavigationRailDestination(icon: Icon(Icons.favorite), label: Text('Category C')),
],
),
const VerticalDivider(thickness: 1, width: 1),
// メインコンテンツ (WebView)
Expanded(
child: InAppWebView(
initialUrlRequest: URLRequest(
// url: WebUri("http://localhost:8080/html/index1.html")
url: WebUri("http://localhost:8080/html/${pages[selectedIndex]}"),
),
onWebViewCreated: (controller) {
webViewController = controller;
},
),
),
],
),
);
}
@override
void dispose() {
// サーバーの停止
ref.read(localhostServerProvider).close();
super.dispose();
}
}
//タグの属性に
//android:usesCleartextTraffic="true"
//を設定します。こうすると、
//Androidアプリからのすべての通信でHTTPが許可されます。
//flutter_inappwebview: ^6.1.5
// assets:
// - html/index2.html
// - html/joy/assets/
// - html/joy/index.html
// - html/index1.html
// - html/css/
// - html/js/
// - html/index3.html