flutter - Flutter中只有静态成员可以初始化错误
问题描述
我正在尝试解决不是我编写的代码。我是新手,很难理解它。
我必须调用 MyHomePage 小部件并传递页面编号。和一个将附加 webUrl 的扩展。但是在附加 webUrl 时,我得到“只有静态成员可以被初始化错误”
我尝试使用 this.variable_name widget.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',
style: TextStyle(color: Color.fromRGBO(179, 80, 205, 1)),),
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'),
height: 30,
width: 30,
),
title: (currentPageValue == 0)
? Text(
'DOWNLOAD',
style:
TextStyle(color: Color.fromRGBO(179, 80, 205, 1)),
)
: Text(
'DOWNLOAD',
style:
TextStyle(color: Color.fromRGBO(78, 78, 78, 0.6)),
),
),
BottomNavigationBarItem(
icon: (currentPageValue == 1)
? SizedBox(
child: Image.asset('assets/images/history.png'),
height: 30,
width: 30,
)
: SizedBox(
child:
Image.asset('assets/images/historyunselected.png'),
height: 30,
width: 30,
),
title: (currentPageValue == 1)
? Text(
'HISTORY',
style:
TextStyle(color: Color.fromRGBO(179, 80, 205, 1)),
)
: Text(
'HISTORY',
style:
TextStyle(color: Color.fromRGBO(78, 78, 78, 0.6)),
),
),
BottomNavigationBarItem(
icon: (currentPageValue == 2)
? SizedBox(
child: Image.asset('assets/images/tiktokselected.png'),
height: 30,
width: 30,
)
: SizedBox(
child:
Image.asset('assets/images/tiktokunselected.png'),
height: 30,
width: 30,
),
title: (currentPageValue == 2)
? Text(
'SAMPLE',
style:
TextStyle(color: Color.fromRGBO(179, 80, 205, 1)),
)
: Text(
'SAMPLE',
style:
TextStyle(color: Color.fromRGBO(78, 78, 78, 0.6)),
),
),
],
),
),
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 方法中初始化构造函数,但我不明白该怎么做
<<<<<<---EDIT-1----- >>>>>>>
<<<<<<<<-----编辑2------------>
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, Map<String, 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
}
推荐阅读
- swiftui - SwiftUI 自动刷新 Coudkit 数据
- pandas - 在列中查找日期,将相邻列值附加到新列 - 全部在一个 df 中?
- .htaccess - 避免 .htaccess 继承
- r - 插入符号分类阈值
- flutter - Flutter where 和 firstwhere 方法使用来自提供者的数据调用 null
- keycloak - 鳄梨酱注销功能不会注销网络浏览器
- python - 隐藏二叉树到双向链表(微软采访)
- c - 使用 fork 和 exec 启动 bin 程序
- unity3d - Raycast2D 仅命中 Collider 的一侧
- python - 如何在 python vtk 中连接两个单独的设置位置值?