首页 > 解决方案 > 我们如何从 Flutter 中的自定义小部件中获取价值

问题描述

我想将 TextBox 类中的文本值访问到其他 dart 文件,怎么做?

我已经给出了下面的代码

import 'package:flutter/material.dart';

class TextBox extends StatelessWidget {
  final String hint;
  final String text;
  TextBox({this.hint});
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 0.0,horizontal: 10.0),
      child: TextField(
        decoration: InputDecoration(
          hintText: hint,
          contentPadding: EdgeInsets.symmetric(vertical: 10.0,horizontal: 10.0),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(32.0),
          ),
        ),
        onChanged: (value){
          text=value;
          return text;
        },
      ),
    );
  }
}

标签: flutter

解决方案


你需要state management考虑到。目前您的TextBox小部件不保持任何状态。

有不同的方法可以做到这一点,您可以检查Flutter 中的状态管理以进行概述。

一般来说(实际实现很大程度上取决于您最终选择的内容),您想要“提升状态”。

引用文档中还说明的内容:

In Flutter, it makes sense to keep the state above the widgets that use it.

推荐阅读