Flutter:如何将变量从statefulwidget传递到其他statefulwidget

时间:2019-12-26 03:24:50

标签: flutter

我无法使用_count类到DraggableWidget类中的TheWidget变量...从statefulWidget到statefulWidget ...如何使用{{ {1}}级到_count级...

DraggableWidget

1 个答案:

答案 0 :(得分:1)

检查以下代码

import 'package:flutter/material.dart';

class DraggableWidget extends StatefulWidget {
  String defaultText = "My Card";
  final Offset offset;

  DraggableWidget({Key key, this.offset}) : super(key: key);

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

class _DraggableWidgetState extends State<DraggableWidget> {
  Offset offset = Offset(0.0, 0.0);
  int _count = 1;

  @override
  void initState() {
    super.initState();
    offset = widget.offset;
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> _addWidget = new List.generate(_count, (int i) => TheWidget(_count));
    return Positioned(
      top: offset.dy,
      left: offset.dx,
      child: Draggable(
        child: Column(
          children: _addWidget,
        ),
        feedback: Container(
          width: 220.0,
          height: 100.0,
          color: Colors.blue.withOpacity(0.3),
        ),
        onDraggableCanceled: (v, o) {
          setState(() {
            offset = o;
          });
        },
      ),
    );
  }
}




class TheWidget extends StatefulWidget {

  int _count = 1;
  TheWidget(this._count);

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

class _TheWidgetState extends State<TheWidget> {
  String defaultText = "My Card";

  @override
  Widget build(BuildContext context) {
    return Card(
      color: Colors.orange[400],
      child: Center(
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 40),
          child: Row(
            children: <Widget>[
              Text(
                defaultText,
                style: TextStyle(
                  fontSize: 18.0,
                ),
              ),
              SizedBox(
                width: 15.0,
              ),
              IconButton(
                icon: Icon(
                  Icons.add,
                  size: 18.0,
                ),
                onPressed: _addNewCard,
                color: Colors.black87,
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _addNewCard() {
    setState(() {
      widget._count = widget._count + 1;
    });
  }
}