243

我的 Flutter 应用中有 2 个屏幕:一个记录列表和一个用于创建和编辑记录的屏幕。

如果我将一个对象传递到第二个屏幕,这意味着我要编辑它,如果我传递 null,则意味着我正在创建一个新项目。编辑屏幕是一个有状态的小部件,对于我的情况,我不确定如何使用这种方法https://flutter.io/cookbook/navigation/passing-data/

class RecordPage extends StatefulWidget {
  final Record recordObject;

  RecordPage({Key key, @required this.recordObject}) : super(key: key);

  @override
  _RecordPageState createState() => new _RecordPageState();
}

class _RecordPageState extends State<RecordPage> {
  @override
  Widget build(BuildContext context) {
   //.....
  }
}

如何访问_RecordPageState的 recordObject

4

7 回答 7

381

要在 _RecordPageState 中使用 recordObject,您只需编写 widget.objectname,如下所示

class _RecordPageState extends State<RecordPage> {
  @override
  Widget build(BuildContext context) {
   .....
   widget.recordObject
   .....
  }
}
于 2018-05-11T09:18:34.780 回答
69

完整示例

您不需要使用它的构造函数将参数传递给 State。您可以使用widget.myField轻松访问这些。

class MyRecord extends StatefulWidget {
  final String recordName;
  const MyRecord(this.recordName);

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

class MyRecordState extends State<MyRecord> {
  @override
  Widget build(BuildContext context) {
    return Text(widget.recordName); // Here you direct access using widget
  }
}

导航屏幕时传递您的数据:

 Navigator.of(context).push(MaterialPageRoute(builder: (context) => MyRecord("WonderWorld")));
于 2019-11-08T13:47:47.263 回答
47
class RecordPage extends StatefulWidget {
  final Record recordObject;

  RecordPage({Key key, @required this.recordObject}) : super(key: key);

  @override
  _RecordPageState createState() => new _RecordPageState(recordObject);
}

class _RecordPageState extends State<RecordPage> {
  Record  recordObject
 _RecordPageState(this. recordObject);  //constructor
  @override
  Widget build(BuildContext context) {.    //closure has access
   //.....
  }
}
于 2019-02-04T00:01:28.303 回答
8

通常,您不仅要导航到新屏幕,还要将数据传递到屏幕。例如,您可能想要传递有关已点击项目的信息。

在此示例中,创建一个待办事项列表。点击待办事项时,导航到显示有关记录的信息的新屏幕(小部件)。此配方使用以下步骤:

  • 定义一个 RecordObject 类。
  • 创建一个StatefulWidget. 我们称之为 RecordsScreen(用于:显示记录列表)。
  • 创建可以显示有关记录的信息的详细信息屏幕。
  • 导航并将数据传递到详细信息屏幕。

定义一个 RecordObject 类

class RecordsScreen extends StatefulWidget {
  List<RecordObject> records;
  RecordsScreen({Key key, @required this.records}) : super(key: key);
  @override
  _RecordsScreenState createState() => _RecordsScreenState();
}

class _RecordsScreenState extends State<RecordsScreen> {
  
  @override
  Widget build(BuildContext context) {
    widget.records = List<RecordObject>.generate(20,
          (i) => RecordObject(
        'Record $i',
        'A description of what needs to be done for Record $i',
      ),
    );
    return Scaffold(
      appBar: AppBar(
        title: Text('Records'),
      ),
      body: ListView.builder(
        itemCount:  widget.records.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text( widget.records[index].title),
            // When a user taps the ListTile, navigate to the DetailScreen.
            // Notice that you're not only creating a DetailScreen, you're
            // also passing the current todo through to it.
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => DetailScreen(recordObject:  widget.records[index]),
                ),
              );
            },
          );
        },
      ),
    );
  }
    

创建详细信息屏幕- 屏幕标题包含记录的标题,屏幕主体显示描述。

class DetailScreen extends StatefulWidget {
  // Declare a field that holds the RecordObject.
  final RecordObject recordObject;

  // In the constructor, require a RecordObject.
  DetailScreen({Key key, @required this.recordObject}) : super(key: key);

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

class _DetailScreenState extends State<DetailScreen> {
  @override
  Widget build(BuildContext context) {
    // Use the RecordObject to create the UI.
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.recordObject.title),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Text(widget.recordObject.description),
      ),
    );
  }
}

在此处输入图像描述

于 2020-08-29T04:45:39.837 回答
5

示例如下:

class nhaphangle extends StatefulWidget {
  final String username;
  final List<String> dshangle;// = ["1","2"];
  const nhaphangle({ Key key, @required this.username,@required this.dshangle }) : super(key: key);


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

class _nhaphangleState extends State<nhaphangle> {
  TextEditingController mspController = TextEditingController();
  TextEditingController soluongController = TextEditingController();
  final scrollDirection = Axis.vertical;
  DateTime Ngaysx  = DateTime.now();
  ScrollController _scrollController = new ScrollController();

  ApiService _apiService;
  List<String> titles = [];

  @override
  void initState() {
    super.initState();
    _apiService = ApiService();
    titles = widget.dshangle;  //here var is call and set to 
  }

    
于 2021-04-20T06:32:13.393 回答
3

我必须导航回列表页面中的任何一个屏幕,但是当我这样做时,我的 onTap 功能停止工作并且导航停止。

class MyBar extends StatefulWidget {
  MyBar({this.pageNumber});
  final pageNumber;
  static const String id = 'mybar_screen';
  @override
  _MyBarState createState() => _MyBarState();
}

class _MyBarState extends State<MyBar> {
  final List pages = [
    NotificationScreen(),
    AppointmentScreen(),
    RequestBloodScreen(),
    ProfileScreen(),
  ];
  @override
  Widget build(BuildContext context) {
    var _selectedItemIndex = widget.pageNumber;
    return Scaffold(
        bottomNavigationBar: BottomNavigationBar(
          elevation: 0,
          backgroundColor: Colors.white,
          unselectedItemColor: Colors.grey.shade700,
          selectedItemColor: Color(kAppColor),
          selectedIconTheme: IconThemeData(color: Color(kAppColor)),
          currentIndex: _selectedItemIndex,
          type: BottomNavigationBarType.fixed,
          onTap: (int index) {
            setState(() {
              _selectedItemIndex = index;
            });
          },
于 2020-11-07T03:48:27.723 回答
0

在我的应用程序中,通常不是使用有状态的小部件,而是主要ChangeNotifierProvider<T>在 main.dart 中使用,一些模型类

class FooModel extends ChangeNotifier {

var _foo = false;

void changeFooState() {
   _foo = true;
   notifyListeners();
}

bool getFoo () => _foo;

}

var foo = context.read<FooModel>();
# or
var foo = context.watch<FooModel>();

在我的无状态小部件中。与有状态的小部件相比,IMO 这让我可以更精确地控制运行时状态更改时的重建。

配方可以在官方文档中找到,这个概念被称为“提升状态”。

于 2021-08-02T13:29:47.093 回答