I'm doing a simple demo app in Flutter using the flutter_webrtc plugin following this tutorial. When I test using Chrome its works just fine, in emulator the camera image never shows, and when I test on my Android smartphone the camera image only appears when I lock (power button) and unlock (power button again) the device.
I am using Windows 11, Android Studio 2022.1.1 Patch 1, Flutter 3.7.5, Dart 2.19.1 OpenJDK 19.0.2 and flutter_webrtc 0.9.23.
Right now my code is the following:
import 'package:flutter/material.dart';
import 'package:flutter_webrtc/flutter_webrtc.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _localVideoRenderer = RTCVideoRenderer();
void initRenderers() async {
await _localVideoRenderer.initialize();
}
_getUserMedia() async {
final Map<String, dynamic> mediaConstraints = {
'audio': true,
'video': true,
};
MediaStream stream =
await navigator.mediaDevices.getUserMedia(mediaConstraints);
_localVideoRenderer.srcObject = stream;
_localVideoRenderer.srcObject = stream;
return stream;
}
@override
void initState() {
initRenderers();
_getUserMedia();
super.initState();
}
@override
void dispose() async {
await _localVideoRenderer.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final ButtonStyle style =
ElevatedButton.styleFrom(textStyle: const TextStyle(fontSize: 20));
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Stack(
children: [
Positioned(
top: 0.0,
right: 0.0,
left: 0.0,
bottom: 0.0,
child: RTCVideoView(_localVideoRenderer))
],
),
);
}
}
I already tried to test on multiple platforms, already tried to invoke the method to show the camera image on a button and aready tried to use another tutorials.
This seems to be related to flutter state management, I added:
setState(() {
});
After srcObject = stream
and it works!