无法从静态方法访问实例成员 颤振



知道为什么我得到这个错误吗?

class appBlocs with ChangeNotifier {
final geo = geolocation();
final services = placesCall();
static Position current;
static List<places> searchResponse;
appBlocs() {
setLocation();
}
setLocation() async {
current = await geo.showCurrentLocation();
notifyListeners();
}
// ignore: non_constant_identifier_names
searching(String term) async {
searchResponse = await services.autocomplete(term);
notifyListeners();
}
}

错误显示在这行onChanged: (value) =>appBlocs.searching。老实说,我有点迷路了

body: (appBlocs.current == null)
? Center(
child: CircularProgressIndicator(),
)
: ListView(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(
hintText: ' Search your Bakery ...',
suffix: Icon(Icons.search)),
onChanged: (value) => appBlocs.searching,
),
),

提前感谢您的帮助

您可以在这里阅读有关在Dart/Flutter中使用static的更多信息。

例如,如果你有一个appblocks类(你应该根据样式指南用UpperCamelCase命名它)

class AppBlocs with ChangeNotifier {
final geo = geolocation();
final services = placesCall();
static Position current;
static List<places> searchResponse;
appBlocs() {
...
}
// ignore: non_constant_identifier_names
searching(String term) async {
...
}
}

然后使用内部属性和方法,你需要像这样使用:

// For static variables and methods
var current = AppBlocs.current
var response = AppBlocs.searchResponse;
// For non-static ones
final bloc = AppBlocs(); // Need to instantiate the object before using them
var geo = bloc.geo
var services = bloc.services
var searching = bloc.searching()
在您的示例中,您可以看到这一行错误地使用了非静态方法searching():
...
TextField(
decoration: InputDecoration(
hintText: ' Search your Bakery ...',
suffix: Icon(Icons.search)),
onChanged: (value) => appBlocs.searching, <-----
),

您需要以非静态方式使用它,即:

...
TextField(
decoration: InputDecoration(
hintText: ' Search your Bakery ...',
suffix: Icon(Icons.search)),
onChanged: (value) => appBlocs().searching, <-----
),

应该可以了!

final geo = geolocation();
final services = placesCall();
//Remove static from this
static Position current;
static List<places> searchResponse;
//To this
Position current;
List<places> searchResponse;

相关内容

  • 没有找到相关文章

最新更新