我有个问题我想显示一个欢迎屏幕,并在最后一个项目后,我想显示一个按钮,重定向用户到一个特定的页面。我得到了一个错误:The instance member 'context' can't be accessed in an initializer. (Documentation) Try replacing the reference to the instance member with a different expression
。
在_WelcomeScreenState
类中使用context
的最佳选择是什么?
import 'package:flutter/material.dart';
import '/items.dart';
import '/SecondRoute.dart';
class WelcomeScreen extends StatefulWidget {
@override
_WelcomeScreenState createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen> {
List<Widget> slides = items
.map((item) => Container(
padding: EdgeInsets.symmetric(horizontal: 18.0),
child: Column(
children: <Widget>[
Flexible(
flex: 1,
fit: FlexFit.tight,
child: Image.asset(
item['image'],
fit: BoxFit.fitWidth,
width: 220.0,
alignment: Alignment.bottomCenter,
),
),
Flexible(
flex: 1,
fit: FlexFit.tight,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 30.0),
child: Column(
children: <Widget>[
Text(item['header'],
style: TextStyle(
fontSize: 50.0,
fontWeight: FontWeight.w300,
color: Color(0XFF3F3D56),
height: 2.0)),
Text(
item['description'],
style: TextStyle(
color: Colors.grey,
letterSpacing: 1.2,
fontSize: 16.0,
height: 1.3),
textAlign: TextAlign.center,
),
if (item.containsKey('button') && item['button'] == 'true')
ElevatedButton(
child: const Text('Open route'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SecondRoute()),
);
},
),
],
),
),
)
],
)))
.toList();
List<Widget> indicator() => List<Widget>.generate(
slides.length,
(index) => Container(
margin: EdgeInsets.symmetric(horizontal: 3.0),
height: 10.0,
width: 10.0,
decoration: BoxDecoration(
color: currentPage.round() == index
? Color(0XFF256075)
: Color(0XFF256075).withOpacity(0.2),
borderRadius: BorderRadius.circular(10.0)),
));
double currentPage = 0.0;
final _pageViewController = new PageController();
@override
void initState() {
super.initState();
_pageViewController.addListener(() {
setState(() {
currentPage = _pageViewController.page!;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Stack(
children: <Widget>[
PageView.builder(
controller: _pageViewController,
itemCount: slides.length,
itemBuilder: (BuildContext context, int index) {
return slides[index];
},
),
Align(
alignment: Alignment.bottomCenter,
child: Container(
margin: EdgeInsets.only(top: 70.0),
padding: EdgeInsets.symmetric(vertical: 40.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: indicator(),
),
)
// ),
)
// )
],
),
),
);
}
}
1条答案
按热度按时间rkkpypqq1#
在initState中初始化你的幻灯片,或者(我认为这是一个更好的方法)从items数组在build方法中构建你的布局,或者(我认为这是最好的)创建一个新的Item小部件并在build方法中示例化。
示例1:
实施例2(更好):
例3最佳:
在WelcomeScreen中: