flutter 在扩展状态的类中使用上下文

6ljaweal  于 2023-06-07  发布在  Flutter
关注(0)|答案(1)|浏览(527)

我有个问题我想显示一个欢迎屏幕,并在最后一个项目后,我想显示一个按钮,重定向用户到一个特定的页面。我得到了一个错误:
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(),
                  ),
                )
              //  ),
            )
            // )
          ],
        ),
      ),
    );
  }
}
rkkpypqq

rkkpypqq1#

initState中初始化你的幻灯片,或者(我认为这是一个更好的方法)从items数组在build方法中构建你的布局,或者(我认为这是最好的)创建一个新的Item小部件并在build方法中示例化。

示例1:

@override
void initState() {

  super.initState();

  slides = items.map((item) => Container(
    ...
  ).toList();

  _pageViewController.addListener(() {
    setState(() {
    currentPage = _pageViewController.page!;
  });
}

实施例2(更好):

Widget build(BuildContext context) {
return Scaffold(
  body: Container(
    child: Stack(
      children: <Widget>[
        PageView.builder(
          controller: _pageViewController,
          itemCount: items.length,
          itemBuilder: (BuildContext context, int index) {
            return Container(...use  items[index] to access the current item, or you can write a builder method and call it here to keep this part simple...);
          },
        ),
        ...
      ]
    )
  )
);

例3最佳:

class SlideWidget extends StatelessWidget {

  final ItemClass item;

  const SlideWidget({Key? key,required this.item}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(...);
  }
}

在WelcomeScreen中:

Widget build(BuildContext context) {
  return Scaffold(
    body: Container(
    child: Stack(
      children: <Widget>[
        PageView.builder(
          controller: _pageViewController,
          itemCount: items.length,
          itemBuilder: (BuildContext context, int index) {
            return SlideWidget(item: items[index]);
          },
        ),
        ...
      ]
    )
  )
);

相关问题