J'essaye de résoudre un code qui n'a pas été écrit par moi, je suis nouveau dans le flotter et j'ai du mal à le comprendre.
Je dois appeler le widget MyHomePage et passer la page no. et une extension qui ajoutera le webUrl.But tout en ajoutant le webUrl, j'obtiens "Seuls les membres statiques peuvent être initialisés erreur"
J'ai essayé d'utiliser this.variable_name widget.variable_name, this.widget.variable_name. J'ai essayé beaucoup de choses et essayé de comprendre aussi les initialiseurs, mais tout semble me passer par-dessus la tête. Je vais mettre le code ci-dessous, s'il vous plaît jeter un oeil
Voici le code dans le fichier principal:
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,
),
),
],
),
),
);
}
}
Ces champs page: 0, extension: "name", j'ai implémenté
La page d'accueil est comme:
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;
J'ai essayé beaucoup de choses comme l'initialisation du constructeur dans la méthode state et tout sauf je ne peux pas comprendre quoi faire
>>>>> >
après l'avoir mise en état init
route = MaterialPageRoute(builder: (context) => MyHomePage(page: 0,extension: "name",));
3 Réponses :
Vous devez initialiser les pages dans 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
}
Merci Cela a aidé, mais lorsque j'ai exécuté le code, l'application lance une erreur indiquant des arguments non valides @Jigar Patel
@ chethanv777333 Cela ressemble à une erreur complètement différente de l'erreur dans la question actuelle. Vous devriez le publier comme une question distincte en soi.
Le problème est que vous ne pouvez pas accéder aux champs de la propriété widget lors de l'initialisation d'une propriété membre de votre état.
Une solution simple est: Déplacez tout votre code pour l'initialisation de vos membres d'état vers votre méthode initState () .
Cela ressemblerait à:
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(),
'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***
};
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',
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;
}
Merci Cela a aidé, mais lorsque j'ai exécuté le code, l'application lance une erreur indiquant des arguments non valides
Où est exactement l'argument invalide?
J'ai inclus la capture d'écran de l'erreur dans l'édition de la question
Merci, mais cela n'aide pas car je ne vois pas ce qu'il y a dans quelle ligne de votre code. Vous devez me dire quelle ligne produit cette erreur.
Merci d'être resté autant dans les parages.Dans l'édition 2 de la question, j'ai inclus le fichier principal et j'ai même inclus la ligne vers laquelle il pointe.Merci encore
Génial, mais votre erreur n'est pas là où vous l'avez marquée. Votre erreur se trouve à la ligne 66 de votre classe _MyHomePageState . À partir de la pile d'appels, je suppose que c'est la ligne où vous concaténez vos chaînes. Veuillez essayer de remplacer 'https: //www.sample.com'+widget.extension par ' https: //www.sample.com$ {widget.extension} ' code>
Parce que vous n'injectez jamais d'extension dans le constructeur de MyHomePage . Au lieu de MyHomePage () . Appelez MyHomePage (extension: '/ url / extension / path') ou quelle que soit l'extension que vous souhaitez avoir
Merci pour vos efforts], tout ce que vous avez dit a fonctionné, mais à cause de cela, je n'obtiens pas la sortie requise que je veux, mais ce n'est toujours pas votre faute. Vous avez effacé cette partie qui était nécessaire pour moi. Donc, je marque cette réponse comme correct
Si le projet n'est pas un secret, n'hésitez pas à créer un référentiel GitHub, donnez-moi des autorisations et créez un problème là-bas où vous expliquez ce que vous voulez et j'essaierai de vous aider. Mon nom GitHub est aussi NiklasLehnfeld
merci pour la gratitude, je verrai si je peux réellement le faire après avoir consulté mes coéquipiers
L'erreur est causée par la variable "Extension de chaîne". Vous ne pouvez pas initialiser une variable non finale. Vous devez rendre la variable définitive. Cependant, si la variable n'est pas définitive, vous pouvez la déclarer dans la classe state.
L'erreur est-elle affichée dans la ligne du fichier principal que vous avez fourni? L'erreur est liée à l'endroit où vous initialisez votre champ d'itinéraire, je pense. Pouvez-vous fournir plus de code de votre fichier principal?
Non, l'erreur se produit lorsque je survole le lien: ' sample.com' + widget.extension ligne..