Home > Net >  How to resolve "Non-nullable instance field '_controller' must be initialized" e
How to resolve "Non-nullable instance field '_controller' must be initialized" e

Time:07-20

I need to open a local HTML file, for which I am trying to use the following code:

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

  @override
  State<HelpScreen> createState() => _HelpScreenState();
}

class _HelpScreenState extends State<HelpScreen> {
WebViewController _controller;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Help')),
      body: WebView(
        initialUrl: 'about:blank',
        onWebViewCreated: (WebViewController webViewController) {
          _controller = webViewController;
          _loadHtmlFromAssets();
        },
      ),
    );
  }

  _loadHtmlFromAssets() async {
    String fileText = await rootBundle.loadString('assets/Privacy Policy.html');
    _controller.loadUrl( Uri.dataFromString(
        fileText,
        mimeType: 'text/html',
        encoding: Encoding.getByName('utf-8')
    ).toString());
  }
}

I have met it several times on the Internet. For example, here.

But when I try to use it I get an error:

Non-nullable instance field '_controller' must be initialized. (Documentation) Try adding an initializer expression, or a generative constructor that initializes it, or mark it 'late'.

_controller is highlighted in red and prevents the application from starting. How to fix it?

CodePudding user response:

As WebViewController is non-nullable, you'll need to initialize it, like at the time of declaration or in the constructor initializing formals. But I can see you are initializing at a later stage. So, it's better to use late.

Change

WebViewController _controller;

to

late WebViewController _controller;

CodePudding user response:

You need to add the late keyword since you're initializing _controller later on:

class _HelpScreenState extends State<HelpScreen> {
  late WebViewController _controller;
  • Related