【问题标题】:Access to State Class field in another widget's build method in Flutter在 Flutter 中访问另一个小部件的构建方法中的 State Class 字段
【发布时间】:2021-12-07 22:44:57
【问题描述】:

有这样一个类

class ProgressBar extends StatefulWidget {
  final double size;
  final String text;
  final String textSize;
  ProgressBar({Key? key, required this.size, required this.text, required this.textSize}) : super(key: key);

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

class _ProgressBarState extends State<ProgressBar>  with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(
        seconds: 5,
      ),
    );

    animation = Tween<double>(
      begin: 0,
      end: widget.size,
    ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeInOut))
      ..addListener(() {
        setState(() {});
      });

    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    return Padding(
      padding: const EdgeInsets.only(left: 20, right: 20, top: 12, bottom: 12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(widget.text, style: theme.textTheme.bodyText1!.copyWith(fontSize: 14, color: theme.colorScheme.primary)),
          Padding(
            padding: const EdgeInsets.only(top: 15, bottom: 6),
            child: LinearProgressIndicator(
              value: _controller.value,
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
            Text('${animation.value.toStringAsFixed(2)} Мб из ${widget.textSize} Мб', style: theme.textTheme.bodyText2!.copyWith(color: Color(0xff8F92A1), fontSize: 12)),
            Text('Загрузка...', style: theme.textTheme.bodyText2!.copyWith(color: Color(0xff8F92A1), fontSize: 12)),
          ],)
        ],
      ),
    );
  }
}

我需要在另一个类中使用“动画”。

child: ListView.separated(
              padding: EdgeInsets.zero,
                shrinkWrap: true,
                  scrollDirection: Axis.vertical,
                  physics: NeverScrollableScrollPhysics(),
                  separatorBuilder: (BuildContext context, int index) => Divider(color: Color(0xffF3F6F8)),
                  itemCount: items.length + 1,
                  itemBuilder: (context, index) {
                    if (index == 0) {
                      return _rowAdd();
                    }
                    return animation.isCompleted ? ProgressBar(size: items[index - 1].sizeFile, text: items[index - 1].nameFile, textSize: items[index - 1].sizeFile.toStringAsFixed(2),) :
                      Padding(
                   ...
                    );

如何正确操作?这是一个临时的拐杖。一般来说,我的 file_picker 将数据添加到 Item 类,我需要一个空的 CallBack 来为每个文件提供一个空的回调,并暂时在其中设置动画超时,但我还不知道该怎么做......

【问题讨论】:

    标签: flutter dart navigation var


    【解决方案1】:

    我不明白你到底是什么意思,但我会尽力提供帮助:

    您想从另一个班级回电吗?使用这个:

    假设我想将回调数据作为字符串:

    import 'package:flutter/material.dart';
    
    typedef void StringCallback(String value);
    
    class Example extends StatefulWidget {
    
      final StringCallback callback;
      
      const Example({Key key, this.callback}) : super(key: key);
    
      @override
      _ExampleState createState() => _ExampleState();
    }
    
    class _ExampleState extends State<Example> {
      @override
      Widget build(BuildContext context) {
        return GestureDetector(
          onTap: (){
            getString();
          },
        );
      }
      
      getString(){
        // This is the Data i need from this class:
        String data = "Data I need";
       setState(() {
         widget.callback(data);
       }); 
      }
      
    }
    

    在另一个类中,您可以像这样使用它:

    Widget testTheCallbackInAnotherClass(){
        return Example(
          callback: (value){
            setState(() {
              final dataIgetFromAnotherClass = value;
              print(dataIgetFromAnotherClass);
            });
          },
        );
      }
    

    你甚至可以像这样调用另一个类中的所有函数:

    首先为类状态创建一个键

    GlobalKey<_ExampleState> _key = GlobalKey<_ExampleState>();
    

    然后调用函数:

    String dataIneedFromExampleClass = _key.currentState.getString();
    

    希望对你有所帮助

    【讨论】:

      猜你喜欢
      • 2021-07-01
      • 2019-07-25
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 2023-01-04
      • 1970-01-01
      • 2018-12-04
      相关资源
      最近更新 更多