'Error: Field '_webViewController' should be initialized because its type 'WebViewController' doesn't allow null

I am trying to run webview app which add some headers to website url ('cause I need to get device ID for push notifications service), but I get error:lib/main.dart:63:25: Error: Field '_webViewController' should be initialized because its type 'WebViewController' doesn't allow null.

Maybe someone can fix it? By the way, can someone check this code, what can be better here?

It's my first time creating Flutter app from scratch, so I need your opinio about this code :)

Main.dart code:

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:firebase_core/firebase_core.dart';

import 'notification.dart';

void main() async {
  await init();
  runApp(const MyApp());
}

Future init() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String notificationTitle = 'No Title';
  String notificationBody = 'No Body';
  String notificationData = 'No Data';

  @override
  void initState() {
    final firebaseMessaging = FCM();
    firebaseMessaging.setNotifications();

    firebaseMessaging.streamCtlr.stream.listen(_changeData);
    firebaseMessaging.bodyCtlr.stream.listen(_changeBody);
    firebaseMessaging.titleCtlr.stream.listen(_changeTitle);

    super.initState();
  }

  _changeData(String msg) => setState(() => notificationData = msg);
  _changeBody(String msg) => setState(() => notificationBody = msg);
  _changeTitle(String msg) => setState(() => notificationTitle = msg);

  final Completer<WebViewController> _completer =
      Completer<WebViewController>();
      WebViewController _webViewController;

      @override
      Widget build(BuildContext context) {
        _completer.future.then((controller) {
          _webViewController = controller;
          Map<String, String> header = {'cookie': 'device-id=12345'};
          _webViewController.loadUrl('https://helpmate.lt/', headers: header);
        });
        return Scaffold(
          body: Container(
            child:
            WebView(
              debuggingEnabled: true,
              javascriptMode: JavascriptMode.unrestricted,
              onWebViewCreated: (controller) async {
                _completer.complete(controller);
              })),
            );
      }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source