如何解决Flutter中只有静态成员可以初始化错误
我正在尝试解决不是由我编写的代码。我是新手,并且很难理解它。
我必须调用MyHomePage小部件并传递页面号。还有一个扩展名将附加到webUrl。但是在附加webUrl时,我收到“只有静态成员才能初始化错误”
我尝试使用this.variable_name小部件.variable_name,this.widget.variable_name。我尝试了很多事情,也试图了解有关初始化程序的信息,但一切似乎都变得令人头疼。我将代码放在下面,请看
这是主文件中的代码:
route = MaterialPageRoute(builder: (context) => MyHomePage(page: 0,extension: "name",));
这些字段页面:0,扩展名:“名称”,我已经实现
主页类似于:
class MyHomePage extends StatefulWidget {
MyHomePage({Key key,this.page,this.extension}) : super(key: key);
final int page;
String extension;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with AutomaticKeepAliveClientMixin<MyHomePage> {
var bottomNavigationBarColor = Colors.white;
PageController controller = PageController();
var currentPageValue = 0.0;
int bottomSelectedIndex = 0;
bool loadFail = false;
// InterstitialAd _exitInterstitialAd;
var pages = {
'0': DownloadRoute(),'1': HistoryRoute(),'2': WebviewRoute(
title: 'Sample',link: 'https://www.sample.com'+widget.extension)//*****here is the error......I tried
//this.extension and the variable name
//extension itself,it didnt help,before on
//www.sample.com was there***
};
void pageChanged(int index) {
setState(() {
bottomSelectedIndex = index;
});
}
void bottomTapped(int index) {
setState(() {
bottomSelectedIndex = index;
controller.jumpToPage(index);
});
}
Future<bool> _onBackPressed() {
return showDialog(
context: context,builder: (BuildContext context) {
return AlertDialog(
content: Text('Are you sure want to exit?'),actions: <Widget>[
FlatButton(
child: Text('No',style: TextStyle(color: Color.fromRGBO(179,80,205,1)),),onPressed: () {
Navigator.of(context).pop(false);
},FlatButton(
child: Text('Yes',onPressed: () {
Navigator.of(context).pop(true);
SystemNavigator.pop();
},],);
});
}
@override
Widget build(BuildContext context) {
controller.addListener(() {
setState(() {
currentPageValue = controller.page;
});
});
return WillPopScope(
onWillPop: () async {
if(isLoaded){
}else{
_onBackPressed();
}
},child: Scaffold(
//primary: false,bottomNavigationBar: Theme(
data: Theme.of(context).copyWith(
textTheme: Theme.of(context).textTheme.copyWith(
caption: TextStyle(color: Colors.white54),)),child: BottomNavigationBar(
type: BottomNavigationBarType.fixed,backgroundColor: bottomNavigationBarColor,// selectedItemColor: Colors.white,// unselectedItemColor: Colors.grey,//fixedColor: backgroundColor,onTap: (index) {
bottomTapped(index);
},currentIndex:
bottomSelectedIndex,// this will be set when a new tab is tapped
items: [
BottomNavigationBarItem(
icon: (currentPageValue == 0)
? SizedBox(
child: Image.asset('assets/images/download.png'),height: 30,width: 30,)
: SizedBox(
child:
Image.asset('assets/images/downloadunselected.png'),title: (currentPageValue == 0)
? Text(
'DOWNLOAD',style:
TextStyle(color: Color.fromRGBO(179,)
: Text(
'DOWNLOAD',style:
TextStyle(color: Color.fromRGBO(78,78,0.6)),BottomNavigationBarItem(
icon: (currentPageValue == 1)
? SizedBox(
child: Image.asset('assets/images/history.png'),)
: SizedBox(
child:
Image.asset('assets/images/historyunselected.png'),title: (currentPageValue == 1)
? Text(
'HISTORY',)
: Text(
'HISTORY',BottomNavigationBarItem(
icon: (currentPageValue == 2)
? SizedBox(
child: Image.asset('assets/images/tiktokselected.png'),)
: SizedBox(
child:
Image.asset('assets/images/tiktokunselected.png'),title: (currentPageValue == 2)
? Text(
'SAMPLE',)
: Text(
'SAMPLE',body: PageView.builder(
physics: new NeverScrollableScrollPhysics(),onPageChanged: (index) {
pageChanged(index);
},controller: controller,itemBuilder: (context,position) {
return Container(
child: pages['$position'],);
},itemCount: 3,);
}
@override
bool get wantKeepAlive => true;
我尝试了很多事情,例如在state方法中初始化构造函数,但全部都无法理解
>>>>> >
error after putting it in init state
void main() {
WidgetsFlutterBinding.ensureInitialized();
var appId ="";
if (Platform.isIOS) {
appId= '';
} else if (Platform.isAndroid) {
appId= '';
}
Admob.initialize(appId);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
SystemChrome.restoreSystemUIOverlays();
SystemChrome.setEnabledSystemUIOverlays(
[SystemUiOverlay.top,SystemUiOverlay.bottom]);
return GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},**///////this is the line it is point to as line 42/////////////////**
child: MaterialApp(
debugShowCheckedModeBanner: false,title: 'SampleApp',theme: ThemeData(
primarySwatch: Colors.blue,home: MySplashPage(),);
}
}
class MySplashPage extends StatefulWidget {
MySplashPage({Key key}) : super(key: key);
@override
_MySplashPageState createState() => _MySplashPageState();
}
class _MySplashPageState extends State<MySplashPage> {
bool internet = true;
Route route;
FirebaseMessaging firebaseMessaging = FirebaseMessaging();
@override
void initState() {
// oneSignalInitialise();
//FirebaseAdMob.instance.initialize(appId: FirebaseAdMob.testAppId);
//Admob.initialize(getAppId());
route = MaterialPageRoute(builder: (context) => MyHomePage(page: 0,extension: "",));
super.initState();
firebaseMessaging.configure(
onMessage: (message) async{
print('${message["notification"]["title"]}');
},onResume: (message) async{
print('${message["data"]["title"]}');
}
);
myInterstitial = AdmobInterstitial(
adUnitId: getInterstitialAdUnitId(),listener: (AdmobAdEvent event,Map<String,dynamic> args) {
//if (event == AdmobAdEvent.closed) myInterstitial.load();
handleEvent(event,args,'Interstitial');
},);
showAd();
}
void handleEvent(
AdmobAdEvent event,dynamic> args,String adType) {
switch (event) {
case AdmobAdEvent.loaded:
print('New Admob $adType Ad loaded!');
break;
case AdmobAdEvent.opened:
print('New Admob $adType Ad opened!');
break;
case AdmobAdEvent.closed:
print('New Admob $adType Ad closed!');
break;
case AdmobAdEvent.failedToLoad:
print('New Admob $adType failed to load. :(');
break;
case AdmobAdEvent.rewarded:
print('rewarded');
break;
default:
}
}
void showSnackBar(String content) {
scaffoldState.currentState.showSnackBar(SnackBar(
content: Text(content),duration: Duration(milliseconds: 1500),));
}
AdmobInterstitial myInterstitial;
String getAppId() {
if (Platform.isIOS) {
return '';
} else if (Platform.isAndroid) {
return '';
}
return null;
}
String getBannerAdUnitId() {
if (Platform.isIOS) {
return '';
} else if (Platform.isAndroid) {
return '';
}
return null;
}
String getInterstitialAdUnitId() {
if (Platform.isIOS) {
return '';
} else if (Platform.isAndroid) {
return '';
}
return null;
}
String getRewardBasedVideoAdUnitId() {
if (Platform.isIOS) {
return '';
} else if (Platform.isAndroid) {
return '';
}
return null;
}
showAd() async {
myInterstitial.load();
int time;
try {
final RemoteConfig remoteConfig = await RemoteConfig.instance;
final defaults = <String,dynamic>{'time': 1500};
await remoteConfig.setDefaults(defaults);
await remoteConfig.fetch(expiration: const Duration(hours: 1));
await remoteConfig.activateFetched();
time = remoteConfig.getInt('time');
//print(time);
} catch (e) {
//print(e);
time = 2000;
}
Future.delayed(Duration(milliseconds: time),() async {
var isLoaded = await myInterstitial.isLoaded;
if(isLoaded){
print('loaded');
myInterstitial.show();
Navigator.pushReplacement(
context,MaterialPageRoute(builder: (context) => MyHomePage()));
}else{
print('loaded not');
Navigator.pushReplacement(
context,MaterialPageRoute(builder: (context) => MyHomePage()));
}
});
}
GlobalKey<ScaffoldState> scaffoldState = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldState,body: Container(
child: Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color.fromRGBO(218,84,186,1),Color.fromRGBO(106,72,241,1)
],begin: Alignment.bottomLeft,end: Alignment.topRight,Center(
child: Container(
child: Image.asset('assets/images/logo.png'),width: MediaQuery.of(context).size.width/4,);
}
}
解决方法
您需要在pages
内部初始化initState()
。
class _MyHomePageState extends State<MyHomePage> with AutomaticKeepAliveClientMixin<MyHomePage> {
var bottomNavigationBarColor = Colors.white;
PageController controller = PageController();
var currentPageValue = 0.0;
int bottomSelectedIndex = 0;
bool loadFail = false;
// InterstitialAd _exitInterstitialAd;
var pages;
@override
void initState() {
pages = {
'0': DownloadRoute(),'1': HistoryRoute(),'2': WebviewRoute(
title: 'Sample',link: 'https://www.sample.com'+widget.extension)
};
super.initState();
}
//rest of the existing code
}
,
问题在于,初始化状态的成员属性时,您无法从widget
属性访问字段。
一个简单的解决方案是:将用于初始化状态成员的所有代码移到initState()
方法中。
这看起来像:
class MyHomePage extends StatefulWidget {
MyHomePage({Key key,this.page,this.extension}) : super(key: key);
final int page;
String extension;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with AutomaticKeepAliveClientMixin<MyHomePage> {
var bottomNavigationBarColor = Colors.white;
PageController controller = PageController();
var currentPageValue = 0.0;
int bottomSelectedIndex = 0;
bool loadFail = false;
// InterstitialAd _exitInterstitialAd;
var pages;
@override
void initState() {
pages = {
'0': DownloadRoute(),link: 'https://www.sample.com'+widget.extension)//*****here is the error......I tried
//this.extension and the variable name
//extension itself,it didnt help,before on
//www.sample.com was there***
};
super.initState();
}
void pageChanged(int index) {
setState(() {
bottomSelectedIndex = index;
});
}
void bottomTapped(int index) {
setState(() {
bottomSelectedIndex = index;
controller.jumpToPage(index);
});
}
Future<bool> _onBackPressed() {
return showDialog(
context: context,builder: (BuildContext context) {
return AlertDialog(
content: Text('Are you sure want to exit?'),actions: <Widget>[
FlatButton(
child: Text('No',style: TextStyle(color: Color.fromRGBO(179,80,205,1)),),onPressed: () {
Navigator.of(context).pop(false);
},FlatButton(
child: Text('Yes',onPressed: () {
Navigator.of(context).pop(true);
SystemNavigator.pop();
},],);
});
}
@override
Widget build(BuildContext context) {
controller.addListener(() {
setState(() {
currentPageValue = controller.page;
});
});
return WillPopScope(
onWillPop: () async {
if(isLoaded){
}else{
_onBackPressed();
}
},child: Scaffold(
//primary: false,bottomNavigationBar: Theme(
data: Theme.of(context).copyWith(
textTheme: Theme.of(context).textTheme.copyWith(
caption: TextStyle(color: Colors.white54),)),child: BottomNavigationBar(
type: BottomNavigationBarType.fixed,backgroundColor: bottomNavigationBarColor,// selectedItemColor: Colors.white,// unselectedItemColor: Colors.grey,//fixedColor: backgroundColor,onTap: (index) {
bottomTapped(index);
},currentIndex:
bottomSelectedIndex,// this will be set when a new tab is tapped
items: [
BottomNavigationBarItem(
icon: (currentPageValue == 0)
? SizedBox(
child: Image.asset('assets/images/download.png'),height: 30,width: 30,)
: SizedBox(
child:
Image.asset('assets/images/downloadunselected.png'),title: (currentPageValue == 0)
? Text(
'DOWNLOAD',style:
TextStyle(color: Color.fromRGBO(179,)
: Text(
'DOWNLOAD',style:
TextStyle(color: Color.fromRGBO(78,78,0.6)),BottomNavigationBarItem(
icon: (currentPageValue == 1)
? SizedBox(
child: Image.asset('assets/images/history.png'),)
: SizedBox(
child:
Image.asset('assets/images/historyunselected.png'),title: (currentPageValue == 1)
? Text(
'HISTORY',)
: Text(
'HISTORY',BottomNavigationBarItem(
icon: (currentPageValue == 2)
? SizedBox(
child: Image.asset('assets/images/tiktokselected.png'),)
: SizedBox(
child:
Image.asset('assets/images/tiktokunselected.png'),title: (currentPageValue == 2)
? Text(
'SAMPLE',)
: Text(
'SAMPLE',body: PageView.builder(
physics: new NeverScrollableScrollPhysics(),onPageChanged: (index) {
pageChanged(index);
},controller: controller,itemBuilder: (context,position) {
return Container(
child: pages['$position'],);
},itemCount: 3,);
}
@override
bool get wantKeepAlive => true;
}
,
该错误是由变量“字符串扩展”引起的。 您不能初始化非最终变量。您必须将变量设为final。但是,如果变量不是最终变量,则可以在状态类中声明它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。