将数据传递给 StatefulWidget 并在 Flutter 中访问它的状态

Passing data to StatefulWidget and accessing it in it's state in Flutter

我的 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

要在 _RecordPageState 中使用 recordObject,您只需像下面这样写 widget.objectname

class _RecordPageState extends State<RecordPage> {
  @override
  Widget build(BuildContext context) {
   .....
   widget.recordObject
   .....
  }
}
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
   //.....
  }
}

完整示例

您不需要使用它的构造函数将参数传递给 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")));

我必须导航回到列表页面中的任何一个屏幕,但是当我这样做时,我的 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;
            });
          },

示例如下:

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 
  }

    

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

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 这让我可以更精确地控制运行时状态更改时的重建。

配方可以在官方找到docs,这个概念叫做“提升状态”。