【问题标题】:How I can have a Service provider to my All widgets?如何为我的所有小部件提供服务提供商?
【发布时间】:2022-08-04 16:12:34
【问题描述】:

我做了一个 Api 类:


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
   }
}

我做了一个登录小部件:


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\',
            )
          ],
        ),
      ),
    );
  }
}

还有一个使用 api 的页面:

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

   // Dender another PAge
}

因此,每次我需要执行登录时,我都需要提供一个通用的 Api 实例并传递它。有没有更好的方法来拥有一个通用的 Api 服务并使用某种服务提供商?

    标签: flutter dart


    【解决方案1】:

    为此,您将需要使用服务定位器。 您可以使用广泛用于此的provider,但您需要为其传递上下文。 如果您不想传递上下文,可以使用get_it

    我个人在我的项目中使用get_it,它工作正常。

    【讨论】:

      猜你喜欢
      • 2011-07-27
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 2018-10-23
      • 2016-08-23
      • 1970-01-01
      • 2017-05-26
      相关资源
      最近更新 更多