【发布时间】:2020-02-27 06:19:35
【问题描述】:
我有一个屏幕,我想将数据从该屏幕传递到抽屉。我的抽屉类如下所示:
class InitDrawer extends StatelessWidget {
final Auth auth;
InitDrawer({this.auth});
@override
Widget build(BuildContext context) {
final String _name = auth.name;
final String _email = auth.email;
final drawerHeader = UserAccountsDrawerHeader(
accountName: Text(_name),
accountEmail: Text(_email),
currentAccountPicture: CircleAvatar(
...
),
);
return ListView(
children: <Widget>[
...
],
);
}
}
这是我正在传递数据的屏幕类
class QRScannerScreen extends StatefulWidget {
static const routeName = '/qr';
final Auth auth;
const QRScannerScreen(this.auth);
@override
_QRScannerScreenState createState() => _QRScannerScreenState();
}
class _QRScannerScreenState extends State<QRScannerScreen> {
final auth = widget.auth;
...
drawer: InitDrawer(auth: auth,),
...
}
最后这是我的 Auth 类/通知侦听器
class Auth with ChangeNotifier {
String _token;
DateTime _expiryDate;
String _userId;
int _carId;
String _email;
String _name;
String get name {
return _name;
}
String get email {
return _email;
}
...
}
我认为整个问题来自auth 为空,当我尝试查看抽屉时,我收到一个错误消息,指出我的Text 类型的小部件不能包含null 的文本。因为我正在通过等待和异步获得身份验证,所以当屏幕加载时它可能没有及时到达那里的数据并且它导致空值。也许我必须使用setState,但我是 Flutter/Dart 的新手,我不知道在哪里使用它。
【问题讨论】:
-
使用未来肯定是导致问题的原因。您可能需要考虑使用 Provider 包,因为您已经在使用 ChangeNotifier。否则,您可以使 InitDrawer 成为 StatefulWidget 并使用 auth 对象的 addListener 方法在进行更改时设置状态。加载数据后,您需要使用内置的 notifyListeners() 方法。另一种选择是扩展 ValueNotifier,它会自动调用 notifyListeners()。或者使用 FutureBuilder。