使用将来的称为“ postSocialData”的方法将用户名保存到mysql / php数据库后,我想将该用户名保存为共享首选项,并提供给提供者。我已经有了ChangeNotifierProvider包装了我的材质应用程序。我已经创建了一个名为“ UserProvider”的提供程序类,该类具有一种名为“ setCurrentName”的方法,该方法会将名称保存到共享的首选项文件中并调用侦听器。但是我似乎无法从“ postSocialData”内部访问“ setCurrentName”方法。如何使“ postSocialData”成为“ UserProvider”的使用者?
这是我的提供者类;
class UserProvider with ChangeNotifier{
String _currentname;
UserProvider(){
_currentname='Anonymous';
loadPreferences();
}
String get currentname => _currentname;
void setCurrentName(String currentname){
_currentname = currentname;
notifyListeners();
savePreferences();
}
savePreferences() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('currentname', _currentname);
}
loadPreferences() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String currentname = prefs.getString('currentname');
}
}
这就是我将来希望使用的方法;
Future<void> postSocialData(String name) async {
final url = "http://example.com/postsocial.php?currentname=$name";
final response = await http.get(url);
if (response.statusCode == 200) {
setCurrentName(
currentname: name,
);
}
}
如何使“ postSocialData”方法成为使用者?有没有办法使提供者类的方法可用?还是我完全以错误的方式去做?这是小部件树;