首页 > 解决方案 > ListView 兼容 StatefulWidget

问题描述

我正在尝试使用颤振对我的第一个应用程序进行编程,但我在 ListView 中遇到问题,自从我更新到StatefulWidgetreturn _Singlerow(zeilen[i]); (来自 StatelessWidget)后它就不再工作了,我不知道为什么。有人可以帮我吗?这对我有很大帮助,因为我不擅长它。_Singlerow

这是代码:

import 'dart:math';
import 'package:flutter/material.dart';
import 'dart:async';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Reaktionstest',
      theme: ThemeData(
        primarySwatch: Colors.yellow,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Reaktionsspiel'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final List<String> zeilen = ['1', '2','3','4','5','6','7','8','9','10'];
  int _counter = 10;
  var startcolor = Colors.red;
  Timer _timer;
  var hintergrundFarbe = Colors.transparent;
  var wert = 0;
  var zufallsButtonFarbe = Colors.blue;
  int _zufallsButton = 0;
  int _treffer = -1;
  bool gestartet = false;
  bool ende = true;
  bool vorbei = false;
  double bildschirmbreite = 0;
  double bildschirmhoehe = 0;
  double dotDurchmesser = 0;
  int dotZeilen = 0;

  int buttongedrueckt(int welcherbutton) {
    if (ende == false) {
      _treffer = -1;
    }
    ende = true;
    if (gestartet == false) {
      gestartet = true;
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        setState(() {
          _counter--;
          startcolor = Colors.green;
          if (_counter < 1) {
            _timer.cancel();
            _counter = 10;
            _zufallsButton = 0;
            startcolor = Colors.red;
            vorbei = true;
            Future.delayed(Duration(milliseconds: 1500), () {
              gestartet = false;
              ende = false;
              vorbei = false;
            });
          }
        });
      });
    }
    if (vorbei == false) {
      if (_zufallsButton == 0 || welcherbutton == _zufallsButton) {
        if (_counter < 1) {
        } else {
          _treffer = _treffer + 1;
        }
        Random random = new Random();
        _zufallsButton = random.nextInt(70) + 1;
        setState(() {
          return _Singlerow(_zufallsButton.toString());
        });
      }
    }
  }

  int dotZeilenBerechnen() {
    bildschirmbreite = MediaQuery.of(context).size.width;
    var padding = MediaQuery.of(context).padding;
    bildschirmhoehe =
        MediaQuery.of(context).size.height - padding.top - padding.bottom;
    dotDurchmesser = bildschirmbreite / 7;
    dotZeilen = ((bildschirmhoehe - 88) / dotDurchmesser).toInt();
    return dotZeilen;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
            child: Container(
      child: Column(
        children: <Widget>[
          Container(
            width: double.infinity,
            alignment: Alignment.centerRight,
            color: startcolor,
            padding: EdgeInsets.symmetric(vertical: 24.0, horizontal: 12.0),                           
            child: Text('$_counter' "                  /" '$_treffer',
                style: TextStyle(fontSize: 40.0, fontWeight: FontWeight.bold)),
          ),
          Expanded(
            child: SizedBox(
              child:
                ListView.builder(
                  itemCount: zeilen.length,
                  itemBuilder: (context, i) {
                    //zeilen is rows in english
                    return _Singlerow(zeilen[i]);
                    
                  },
                )
            )
          ),
        ],
      ),
    )));
  }
}

class Singlerow extends StatefulWidget {
  Singlerow({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _Singlerow createState() => _Singlerow('');
}


class _Singlerow extends State<Singlerow> {
  final String title;
  _Singlerow(this.title);
  final Color hintergrundFarbe = Colors.transparent;
  final Color zufallsButtonFarbe = Colors.blue;
  int _zufallsButton = 14;
  @override
  Widget build(BuildContext context) {
    return Container(child: 

        Row(children: <Widget>[
        
         Expanded(
            child: FloatingActionButton(
          onPressed: () =>
              _MyHomePageState().buttongedrueckt(int.parse(title) * 7 - 6),
          backgroundColor: _zufallsButton.toInt() == int.parse(title) * 7 - 6
              ? zufallsButtonFarbe
              : hintergrundFarbe,
        )),
         Expanded(
            child: FloatingActionButton(
          onPressed: () =>
              _MyHomePageState().buttongedrueckt(int.parse(title) * 7 - 5),
          backgroundColor: _zufallsButton.toInt() == int.parse(title) * 7 - 5
              ? zufallsButtonFarbe
              : hintergrundFarbe,
        )),
        Expanded(
            child: FloatingActionButton(
          onPressed: () =>
              _MyHomePageState().buttongedrueckt(int.parse(title) * 7 - 4),
          backgroundColor: _zufallsButton.toInt() == int.parse(title) * 7 - 4
              ? zufallsButtonFarbe
              : hintergrundFarbe,
        )),
        Expanded(
            child: FloatingActionButton(
          onPressed: () =>
              _MyHomePageState().buttongedrueckt(int.parse(title) * 7 - 3),
          backgroundColor: _zufallsButton.toInt() == int.parse(title) * 7 - 3
              ? zufallsButtonFarbe
              : hintergrundFarbe,
        )),
        Expanded(
            child: FloatingActionButton(
          onPressed: () =>
              _MyHomePageState().buttongedrueckt(int.parse(title) * 7 - 2),
          backgroundColor: _zufallsButton.toInt() == int.parse(title) * 7 - 2
              ? zufallsButtonFarbe
              : hintergrundFarbe,
    )),
    


        Expanded(
            child: FloatingActionButton(
          onPressed: () =>
              _MyHomePageState().buttongedrueckt(int.parse(title) * 7 - 1),
          backgroundColor: _zufallsButton.toInt() == int.parse(title) * 7 - 1
              ? zufallsButtonFarbe
              : hintergrundFarbe,
        )),
        Expanded(
            child: FloatingActionButton(
          onPressed: () =>
              _MyHomePageState().buttongedrueckt(int.parse(title) * 7),
          backgroundColor: _zufallsButton.toInt() == int.parse(title) * 7
              ? zufallsButtonFarbe
              : hintergrundFarbe,
        )), 
      ]),
        );
  }
}

标签: flutterdart

解决方案


问题是,您错误地构建了 StatefulWidget 类。

您的以下代码不正确(请参阅代码中的注释):

class Singlerow extends StatefulWidget {
  Singlerow({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _Singlerow createState() => _Singlerow(''); // This is incorrect
}


class _Singlerow extends State<Singlerow> {
  final String title;       // This is incorrect, should use widget.title 
  _Singlerow(this.title);   // This is incorrect, should use widget.title

   ...
}

您需要将上面的代码更改为以下代码:

class Singlerow extends StatefulWidget {
  Singlerow({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _Singlerow createState() => _Singlerow();
}


class _Singlerow extends State<Singlerow> {
  // Use getter to get the title
  String get title => widget.title;

  // Or get the title value from initState
          
  // uncomment the below code to use.
  // String title;

  @override
  void initState() {
    super.initState();
    // uncomment the below code to use.
    // title = widget.title;
  }

  ...
}

有关更多详细信息,请参阅https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html


推荐阅读