Where is a correct place to initialize get_it in widget?

443 Views Asked by At

I need to initialize get_it right in the widget file so that it would be available down the widget three. Normally we would do it next to runApp() but here I need it for demonstration purposes.

Is it a correct place to initialize it?

import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';

import 'form_store.dart';

final getIt = GetIt.instance;

class FormExample extends StatefulWidget {
  const FormExample();

  @override
  _FormExampleState createState() => _FormExampleState();
}

class _FormExampleState extends State<FormExample> {
  final store = getIt.get<FormStore>();

  @override
  void initState() {
    super.initState();
    getIt.registerSingleton<FormStore>(FormStore());
    store.setupValidations();
  }

  ...

// in the same .dart file
// this widget will be used in build method of the above FormExample class 
class InnerPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final store = GetIt.I<FormStore>();
    return Scaffold(
      body: Center(child: Text('Hello ${store.name}')),
    );
  }
}
0

There are 0 best solutions below