简体   繁体   中英

How I can have a Service provider to my All widgets?

I made an Api class:


class Api
{
   // Token for authentication
   String bearerToken;

   // Generate a bearer token
   void login(String username,String password){
     // Some Implementation hidden for simplicity
   }

   void refreshToken(){
     // Some Implementation hidden for simplicity
   }

   void consumeAnEndpointUsingBearerToken(){
     // Some Implementation hidden for simplicity
   }
}

And I made a Login widget:


class LoginPage extends StatefulWidget {
  final String title;
  final Api api;
  const LoginPage({Key? key, required this.title, required this.api})
      : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState(api);
}

class _LoginPageState extends State<LoginPage> {
  String username = '';
  String password = '';
  final Api api;
  
  _LoginPageState(this.api)

  void __setUsername(username) {
    this.username = username;
  }

  void __setPassword(password) {
    this.password = password;
  }

  void _login() {
    setState(() {
       api.login(username,password);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            AppTextInput(
              hintText: 'Username',
              onChanged: __setUsername,
            ),
            AppTextInput(
              obscureText: true,
              hintText: 'Password',
              onChanged: __setPassword,
            ),
            AppButton(
              onPressed: _login,
              text: 'Login',
            )
          ],
        ),
      ),
    );
  }
}

And an another page where api is Consumed:

class ConsumeApi extends StatelessWidget {
    const ConsumeApi({Key? key, required this.title, required this.api})
      : super(key: key);

   // Dender another PAge
}

So at every time I need to perform a login Ι''ll need to offer a common Api instance and pass it around. Is there a better way to have a common Api service and use a some sort of service provider?

You can use Get_It for dependency injection.

Create injectionContainer file:

final sl = GetIt.instance;

void init(){
   sl.registerSingleton(() => Api());
}

in your main, you need to call init():

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  di.init();
  runApp(MyApp());
}

and don't forget to Import the injectionContainer file:

import 'injection_container.dart' as di;

and now In every widget you can do this:

sl<Api>().login();

Now you have an object of API created for you when the app starts.

You will need to use service locator for this. You can use provider which is widely used for this but you'll need to pass context for it. If you do not want to pass context you can use get_it

I am personally using get_it in my project and it's workking fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM