【问题标题】:Setstate from a FAB that updates Gridview.builder来自更新 Gridview.builder 的 FAB 的 Setstate
【发布时间】:2021-05-20 06:46:51
【问题描述】:

我仍在学习颤振,并且难以将 setstate 与多维度数组 (Map) 一起使用。

我正在尝试使用随机和 FAB 更新 Gridview.build 中简单容器的单个值(宽度、高度、颜色)。

如果我在网格视图之外只做一个随机元素,它工作正常。

这个类的最终输出是循环遍历每一个Curve。*有flutter并以gridview模式输出一个随机形状。每次按下 FAB 按钮都会改变。

当前的错误是我试图弄清楚如何向地图添加值...如果它们首先通过 setstate 正确添加:

帮帮我,欧比旺,你是我唯一的希望。

The method '[]' was called on null.
Receiver: null
Tried calling: []("width")

这是我的代码:

import 'dart:math';

import 'package:flutter/material.dart';

class AnimatedContainerPage extends StatefulWidget {
  @override
  _AnimatedContainerPageState createState() => _AnimatedContainerPageState();
}

class _AnimatedContainerPageState extends State<AnimatedContainerPage> {
  double _width = 200;
  double _height = 200;
  Color _color = Colors.red;
  BorderRadiusGeometry _borderRadius = BorderRadius.circular(16);

  final random = Random();

  //Once working add all the Curves
  var curves = [
    Curves.bounceIn,
    Curves.bounceInOut,
    Curves.bounceOut,
    Curves.decelerate,
    Curves.ease,
    Curves.easeIn,
    Curves.easeInBack
  ];

  Map curveList = {
    'curve': Curves.bounceIn,
    'width': 200,
    'height': 200,
    'color': Colors.red,
    'borderrad': BorderRadius.circular(16),
  };

  void _randomize() {
    setState(() {
  
      //loop through curve list and add random params to each curve
      for (int i = 0; i < curves.length; i++) {

        _width = random.nextInt(300).toDouble();
        _height = random.nextInt(300).toDouble();
        _color = Color.fromRGBO(
            random.nextInt(256), random.nextInt(256), random.nextInt(256), 1);
        _borderRadius = BorderRadius.circular(random.nextInt(100).toDouble());

  
        curveList.addAll({
          'curve': curves[i],
          'width': _width,
          'height': _height,
          'color': _color,
          'borderrad': _borderRadius,
        });
       // print(curveList);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AnimatedContainer'),
      ),
      body: Center(
        child: GridView.builder(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3),
          itemCount: curveList.length,
          itemBuilder: (BuildContext context, int index) {
            print('index is $index and curves i is ${curves[index]}');
            return AnimatedContainer(
              width: curveList[index]['width'],
              height: curveList[index]['height'],
              decoration: BoxDecoration(
                color: curveList[index]['color'],
                borderRadius: curveList[index]['borderradius'],
              ),
              duration: Duration(seconds: 1),
              curve: curves[index],
              padding: EdgeInsets.all(10),
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.play_arrow),
        onPressed: _randomize,
      ),
    );
  }
}

【问题讨论】:

    标签: flutter dart flutter-layout


    【解决方案1】:

    变量curveListMap 不是ListMaps,所以改成这个。

    return AnimatedContainer(
                  width: curveList['width'],
                  height: curveList['height'],
                  decoration: BoxDecoration(
                    color: curveList['color'],
                    borderRadius: curveList['borderradius'],
                  ),
                  duration: Duration(seconds: 1),
                  curve: curves[index],
                  padding: EdgeInsets.all(10),
                );
    

    编辑:

    实际上,您需要 curveList 成为您的用例的 List&lt;Map&gt;(地图列表)。所以你需要像这样进行更改。

    List<Map> curveList = [
            {
              'curve': Curves.bounceIn,
              'width': 200.0,
              'height': 200.0,
              'color': Colors.red,
              'borderrad': BorderRadius.circular(16),
            }
          ];
        
          void _randomize() {
            setState(() {
        
              //loop through curve list and add random params to each curve
              curveList.clear();
              for (int i = 0; i < curves.length; i++) {
        
                _width = random.nextInt(300).toDouble();
                _height = random.nextInt(300).toDouble();
                _color = Color.fromRGBO(
                    random.nextInt(256), random.nextInt(256), random.nextInt(256), 1);
                _borderRadius = BorderRadius.circular(random.nextInt(100).toDouble());
        
                curveList.add({
        
                  'curve': curves[i],
                  'width': _width,
                  'height': _height,
                  'color': _color,
                  'borderrad': _borderRadius,
                });
                // print(curveList);
              }
            });
          }
    

    并保持这部分原样

    width: curveList[index]['width'],
                  height: curveList[index]['height'],
                  decoration: BoxDecoration(
                    color: curveList[index]['color'],
                    borderRadius: curveList[index]['borderradius'],
                  ),
    

    【讨论】:

      【解决方案2】:

      非常感谢@Jigar Patel!错误是列表,添加 clear() 是明智之举。下面是最终的用例代码。如果你想在任何事情上使用它,请确保首先检查边界半径的高度,因为有时动画会有一个负高度。

      mport 'dart:math';
      
      import 'package:flutter/material.dart';
      
      class AnimatedContainerPage extends StatefulWidget {
        @override
        _AnimatedContainerPageState createState() => _AnimatedContainerPageState();
      }
      
      class _AnimatedContainerPageState extends State<AnimatedContainerPage> {
        double _width = 200;
        double _height = 200;
        Color _color = Colors.red;
        BorderRadiusGeometry _borderRadius = BorderRadius.circular(16);
      
        final random = Random();
      
        var curves = [
          Curves.bounceIn,
          Curves.bounceInOut,
          Curves.bounceOut,
          Curves.decelerate,
          Curves.ease,
          Curves.easeIn,
          Curves.easeInBack,
          Curves.easeInCirc,
          Curves.easeInCubic,
          Curves.easeInExpo,
          Curves.easeInOut,
          Curves.easeInOutBack,
          Curves.easeInOutCirc,
          Curves.easeInOutCubic,
          Curves.easeInOutCubicEmphasized,
          Curves.easeInOutExpo,
          Curves.easeInOutQuad,
          Curves.easeInOutQuart,
          Curves.easeInOutQuint,
          Curves.easeInOutSine,
          Curves.easeInQuad,
          Curves.easeInQuart,
          Curves.easeOutSine,
          Curves.elasticIn,
          Curves.elasticInOut,
          Curves.elasticOut,
          Curves.fastLinearToSlowEaseIn,
          Curves.fastOutSlowIn,
          Curves.linear,
          Curves.linearToEaseOut,
          Curves.slowMiddle
        ];
      
        List<Map> curveList = [
          {
            'curve': Curves.bounceIn,
            'width': 200.0,
            'height': 200.0,
            'color': Colors.red,
            'borderrad': BorderRadius.circular(16),
          }
        ];
      
        void _randomize() {
          setState(() {
            //loop through curve list and add random params to each curve
            curveList.clear();
            for (int i = 0; i < curves.length; i++) {
              _width = random.nextInt(300).toDouble();
              _height = random.nextInt(300).toDouble();
              _color = Color.fromRGBO(
                  random.nextInt(256), random.nextInt(256), random.nextInt(256), 1);
              _borderRadius = BorderRadius.circular(random.nextInt(100).toDouble());
      
              curveList.add({
                'curve': curves[i],
                'width': _width,
                'height': _height,
                'color': _color,
                'borderrad': _borderRadius,
              });
              // print(curveList);
            }
          });
        }
      
        @override
        Widget build(BuildContext context) {
          return Scaffold(
            appBar: AppBar(
              title: Text('AnimatedContainer'),
            ),
            body: Center(
              child: GridView.builder(
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3),
                itemCount: curveList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Stack(
                    alignment: Alignment.center,
                    children: [
                      AnimatedContainer(
                        width: curveList[index]['width'],
                        height: curveList[index]['height'],
                        decoration: BoxDecoration(
                          color: curveList[index]['color'],
                          borderRadius: curveList[index]['borderrad'],
                        ),
                        duration: Duration(seconds: 4),
                        curve: curves[index],
                        padding: EdgeInsets.all(10),
                      ),
                      Container(
                        width: 100,
                        child: Text(
                          curves[index].toString(),
                          style: TextStyle(
                            color: Colors.white,
                            backgroundColor: Colors.black,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
            floatingActionButton: FloatingActionButton(
              child: Icon(Icons.play_arrow),
              onPressed: _randomize,
            ),
          );
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-31
        • 2023-03-03
        • 2022-08-22
        • 2022-07-24
        • 1970-01-01
        • 2015-12-26
        相关资源
        最近更新 更多