Flutter - 如何将用户数据传递给所有视图

Aar*_*ron 25 dart firebase-authentication flutter

我是一个新的移动应用程序开发的新手,并在我应该如何在我的应用程序中传递用户数据.

我已经尝试了几件事,但似乎都没有,我确信我应该遵循最好的练习模式.

因为它使示例更容易,我使用firebase进行身份验证.我目前有一个单独的登录路径.一旦我登录,我想在大多数视图中使用用户模型来检查显示内容的权限,在抽屉中显示用户信息等...

Firebase有一个await firebaseAuth.currentUser();最佳做法是在您可能需要用户的任何地方调用它吗?如果是这样,这个电话的最佳位置在哪里?

扑代码实验室展示一个很好的例子,允许写入之前认证用户.但是,如果页面需要检查auth以确定要构建的内容,则异步调用不能进入该build方法.

INITSTATE

我尝试过的一种方法是覆盖initState并启动调用以获取用户.当未来完成时,我呼叫setState并更新用户.

    FirebaseUser user;

    @override
    void initState() {
      super.initState();
      _getUserDetail();
    }

  Future<Null> _getUserDetail() async {
    User currentUser = await firebaseAuth.currentUser();
    setState(() => user = currentUser);
  }
Run Code Online (Sandbox Code Playgroud)

这很有效,但似乎需要它的每个小部件的很多仪式.屏幕在没有用户的情况下加载时也会闪烁,然后在未来完成时与用户进行更新.

通过构造函数传递用户

这也有效,但是有很多样板可以让用户通过可能需要访问它们的所有路由,视图和状态.此外,我们不能只popAndPushNamed在转换路由时这样做,因为我们无法将变量传递给它.我们必须更改类似于此的路线:

Navigator.push(context, new MaterialPageRoute(
    builder: (BuildContext context) => new MyPage(user),
));
Run Code Online (Sandbox Code Playgroud)

继承的小部件

https://medium.com/@mehmetf_71205/inheriting-widgets-b7ac56dbbeb1

这篇文章展示了一个很好的使用模式InheritedWidget.当我将继承的小部件放在MaterialApp级别时,当auth状态改变时,子节点不会更新(我确定我做错了)

  FirebaseUser user;

  Future<Null> didChangeDependency() async {
    super.didChangeDependencies();
    User currentUser = await firebaseAuth.currentUser();
    setState(() => user = currentUser);
  }

  @override
  Widget build(BuildContext context) {
    return new UserContext(
      user,
      child: new MaterialApp(
        title: 'TC Stream',
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: new LoginView(title: 'TC Stream Login', analytics: analytics),
        routes: routes,
      ),
    );
  }
Run Code Online (Sandbox Code Playgroud)

FutureBuilder

FutureBuilder似乎也是一个不错的选择,但似乎每条路线都有很多工作要做.在下面的部分示例中,_authenticateUser()在完成时获取用户和设置状态.

  @override
  Widget build(BuildContext context) {
    return new FutureBuilder<FirebaseUser>(
      future: _authenticateUser(),
      builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return _buildProgressIndicator();
        }
        if (snapshot.connectionState == ConnectionState.done) {
          return _buildPage();
        }
      },
    );
  }
Run Code Online (Sandbox Code Playgroud)

我很感激有关最佳实践模式的建议或用于示例的资源链接.

Mat*_* S. 16

我建议进一步调查继承的小部件; 下面的代码显示了如何使用它们异步更新数据:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(new MaterialApp(
      title: 'Inherited Widgets Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new Scaffold(
          appBar: new AppBar(
            title: new Text('Inherited Widget Example'),
          ),
          body: new NamePage())));
}

// Inherited widget for managing a name
class NameInheritedWidget extends InheritedWidget {
  const NameInheritedWidget({
    Key key,
    this.name,
    Widget child}) : super(key: key, child: child);

  final String name;

  @override
  bool updateShouldNotify(NameInheritedWidget old) {
    print('In updateShouldNotify');
    return name != old.name;
  }

  static NameInheritedWidget of(BuildContext context) {
    // You could also just directly return the name here
    // as there's only one field
    return context.inheritFromWidgetOfExactType(NameInheritedWidget);
  }
}

// Stateful widget for managing name data
class NamePage extends StatefulWidget {
  @override
  _NamePageState createState() => new _NamePageState();
}

// State for managing fetching name data over HTTP
class _NamePageState extends State<NamePage> {
  String name = 'Placeholder';

  // Fetch a name asynchonously over HTTP
  _get() async {
    var res = await http.get('https://jsonplaceholder.typicode.com/users');
    var name = JSON.decode(res.body)[0]['name'];
    setState(() => this.name = name); 
  }

  @override
  void initState() {
    super.initState();
    _get();
  }

  @override
  Widget build(BuildContext context) {
    return new NameInheritedWidget(
      name: name,
      child: const IntermediateWidget()
    );
  }
}

// Intermediate widget to show how inherited widgets
// can propagate changes down the widget tree
class IntermediateWidget extends StatelessWidget {
  // Using a const constructor makes the widget cacheable
  const IntermediateWidget();

  @override
  Widget build(BuildContext context) {
    return new Center(
      child: new Padding(
        padding: new EdgeInsets.all(10.0),
        child: const NameWidget()));
  }
}

class NameWidget extends StatelessWidget {
  const NameWidget();

  @override
  Widget build(BuildContext context) {
    final inheritedWidget = NameInheritedWidget.of(context);
    return new Text(
      inheritedWidget.name,
      style: Theme.of(context).textTheme.display1,
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


Mak*_*kah 7

我更喜欢使用带有定位器的服务,使用Flutter get_it

如果您愿意,可以创建一个带有缓存数据的 UserService:

class UserService {
  final Firestore _db = Firestore.instance;
  final String _collectionName = 'users';
  CollectionReference _ref;

  User _cachedUser; //<----- Cached Here

  UserService() {
    this._ref = _db.collection(_collectionName);
  }

  User getCachedUser() {
    return _cachedUser;
  }

  Future<User> getUser(String id) async {
    DocumentSnapshot doc = await _ref.document(id).get();

    if (!doc.exists) {
      log("UserService.getUser(): Empty companyID ($id)");
      return null;
    }

    _cachedUser = User.fromDocument(doc.data, doc.documentID);
    return _cachedUser;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后创建创建一个定位器

GetIt locator = GetIt.instance;

void setupLocator() {
  locator.registerLazySingleton(() => new UserService());
}
Run Code Online (Sandbox Code Playgroud)

并在 main() 中实例化

void main() {
  setupLocator();
  new Routes();
}
Run Code Online (Sandbox Code Playgroud)

就是这样!您可以使用以下方法在任何地方调用 Service + cachedData:

.....
UserService _userService = locator<UserService>();

@override
void initState() {
  super.initState();
  _user = _userService.getCachedUser();
}
Run Code Online (Sandbox Code Playgroud)