dart - 按下按钮时如何添加小部件

标签 dart flutter

对于我的 flutter 应用程序,我需要一个可以在我按下添加按钮时添加的容器。因此,我随后查看了其他 Stack Overflow 问题,例如:Flutter - Render new Widgets on clickFlutter - Add new Widget on click .之后,这就是我想出的。

class Body extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    var tPadding= MediaQuery.of(context).size.width  * 0.08; 
    var bPadding= MediaQuery.of(context).size.width  * 0.15; 
    var vPadding = MediaQuery.of(context).size.height  * 0.015;

    return Expanded (
      child: Container (
        child: NotificationListener<OverscrollIndicatorNotification> (
          onNotification: (OverscrollIndicatorNotification overscroll) {
            overscroll.disallowGlow();
          },
          child: PageView.builder(
            pageSnapping: false,
            controller: PageController(viewportFraction: 0.85),
            itemCount: container.length,
            itemBuilder: (context, i) {
              return Padding (
                padding: EdgeInsets.only(
                  left: vPadding,
                  right: vPadding,
                  top: tPadding,
                  bottom: bPadding
                ),
                child: container[i]
              );
            },
          )
        )
      )
    );
  }

}

 int _count = 1;

List container = [
  List.generate(_count, (int i) => ContainerCard),
  AddContainer()
];

class ContainerCard extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Material (
      borderRadius: BorderRadius.circular(50.0),
      color: Colors.white,
      elevation: 8.0,
    );
  }

}

class AddContainer extends StatefulWidget {

  @override
  AddContainerState createState() => AddContainerState();

}

class AddContainerState extends State<AddContainer> {

  @override
  Widget build(BuildContext context) {
    return Material(
      borderRadius: BorderRadius.circular(50.0),
      color: Colors.white,
      elevation: 8.0,
      child: InkWell (
        onTap: _addContainer,
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
        child: Column (
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Icon (
              Icons.add,
              size: 50.0,
            )
          ]
        ),
      )
    );
  }
  void _addContainer() {
    setState(() {
      _count = _count + 1;
    });
  }

}

但出于某种原因,这不起作用。出了什么问题,我该如何解决?

完整代码:

import 'package:flutter/material.dart';

class MainPage extends StatelessWidget {

  @override
    Widget build(BuildContext context) {

      return MaterialApp (
        debugShowCheckedModeBanner: false,
        home: Scaffold (
          backgroundColor: Colors.white,
          body: Column (
            children: <Widget> [
              AppBar(),
              Body(),
            ]
          )
        )
      );
    }

}

class AppBar extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    var abHeight = MediaQuery.of(context).size.height  * 0.2;

    var vPadding = MediaQuery.of(context).size.height  * 0.07;

    return Container (
      height: abHeight,
      child:  Column (
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget> [
          Row (
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(left: vPadding),
                child: PoppinsText (
                  text: "App",
                  fontSize: 40.0,
                  fontWeight: FontWeight.bold,
                  color: Colors.black,
                ),
              )
            ]
          )
        ]
      )
    );
  }

}

class Body extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    var tPadding= MediaQuery.of(context).size.width  * 0.08; 
    var bPadding= MediaQuery.of(context).size.width  * 0.15; 
    var vPadding = MediaQuery.of(context).size.height  * 0.015;

    return Expanded (
      child: Container (
        child: NotificationListener<OverscrollIndicatorNotification> (
          onNotification: (OverscrollIndicatorNotification overscroll) {
            overscroll.disallowGlow();
          },
          child: PageView.builder(
            pageSnapping: false,
            controller: PageController(viewportFraction: 0.85),
            itemCount: container.length,
            itemBuilder: (context, i) {
              return Padding (
                padding: EdgeInsets.only(
                  left: vPadding,
                  right: vPadding,
                  top: tPadding,
                  bottom: bPadding
                ),
                child: container[i]
              );
            },
          )
        )
      )
    );
  }

}

 int _count = 1;

List container = [
  List.generate(_count, (int i) => ContainerCard),
  AddContainer()
];

class ContainerCard extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Material (
      borderRadius: BorderRadius.circular(50.0),
      color: Colors.white,
      elevation: 8.0,
    );
  }

}

class AddContainer extends StatefulWidget {

  @override
  AddContainerState createState() => AddContainerState();

}

class AddContainerState extends State<AddContainer> {

  @override
  Widget build(BuildContext context) {
    return Material(
      borderRadius: BorderRadius.circular(50.0),
      color: Colors.white,
      elevation: 8.0,
      child: InkWell (
        onTap: _addContainer,
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
        child: Column (
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Icon (
              Icons.add,
              size: 50.0,
            )
          ]
        ),
      )
    );
  }
  void _addContainer() {
    setState(() {
      _count = _count + 1;
    });
  }

}

class PoppinsText extends StatelessWidget {

  PoppinsText ({Key key, 
    this.text, 
    this.fontSize, 
    this.fontWeight,
    this.color}) : super(key: key);

  final String text;
  final double fontSize;
  final FontWeight fontWeight;
  final Color color;

  @override
  Widget build(BuildContext context) {
    return Text (
      text,
      style: TextStyle (
        fontFamily: 'Poppins',
        fontWeight: fontWeight,
        fontSize: fontSize,
        color: color
      ),
    );
  }

}

最佳答案

您正在使用无状态小部件。切换到有状态小部件

编辑

根据要求更新。 这里的技巧是使用网页浏览的 reverse 属性。

class Body extends StatefulWidget {
  @override
  _BodyState createState() => _BodyState();
}

class _BodyState extends State<Body> {
  int count = 1;
  @override
  Widget build(BuildContext context) {
    return Expanded(
        child: Container(
            child: NotificationListener<OverscrollIndicatorNotification>(
                onNotification: (OverscrollIndicatorNotification overscroll) {
                  overscroll.disallowGlow();
                },
                child: PageView.builder(
                    reverse: true,
                    pageSnapping: false,
                    controller: PageController(viewportFraction: 0.85),
                    itemCount: count,
                    itemBuilder: (context, i) {
                      print(i);
                      if (i == 0) {
                        return Padding(
                            padding: EdgeInsets.only(
                                left:
                                    MediaQuery.of(context).size.height * 0.015,
                                right:
                                    MediaQuery.of(context).size.height * 0.015,
                                top: MediaQuery.of(context).size.width * 0.08,
                                bottom:
                                    MediaQuery.of(context).size.width * 0.15),
                            child: Material(
                                borderRadius: BorderRadius.circular(50.0),
                                color: Colors.white,
                                elevation: 8.0,
                                child: InkWell(
                                  onTap: () {
                                    setState(() {
                                      count++;
                                    });
                                  },
                                  splashColor: Colors.transparent,
                                  highlightColor: Colors.transparent,
                                  child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: <Widget>[
                                        Icon(
                                          Icons.add,
                                          size: 50.0,
                                        )
                                      ]),
                                )));
                      } else {
                        return Padding(
                            padding: EdgeInsets.only(
                                left:
                                    MediaQuery.of(context).size.height * 0.015,
                                right:
                                    MediaQuery.of(context).size.height * 0.015,
                                top: MediaQuery.of(context).size.width * 0.08,
                                bottom:
                                    MediaQuery.of(context).size.width * 0.15),
                            child: Material(
                              borderRadius: BorderRadius.circular(50.0),
                              color: Colors.white,
                              elevation: 8.0,
                            ));
                      }
                    }))));
  }

关于dart - 按下按钮时如何添加小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54509688/

相关文章:

flutter - 在flutter中使用Provider在路由之间传递数据的最佳方法是什么?

dart - 枚举可以在 AngularDart 模板中使用吗?如何?

dart - itemcount 中的 snapshot.data.length 不起作用 : "The getter ' length' was called on null"

flutter - 带有 Scaffold 的 InheritedWidget 似乎无法正常工作

android - 抖动错误: VM snapshot invalid and could not be inferred from settings

flutter - 使“列强制容器”与其他小部件的大小相同

android - 找不到脚手架小部件 : Getting exception while opening Bottom Dialog sheet

flutter - 如何在flutter中删除pubspec.yaml中指定的 Assets ?

dart - 对齐 Flutter scrollview 的第一个小部件最初居中,但所有后续选定的小部件也在中心

java - 如何为 Android 应用程序中的所有线程设置 uncaughtExceptionHandler?崩溃仅在某些情况下发生