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

kkbh8khc  于 2023-04-03  发布在  Flutter
关注(0)|答案(8)|浏览(167)

我的Flutter应用程序中有两个屏幕:记录列表和用于创建和编辑记录的屏幕。
如果我传递一个对象到第二个屏幕,这意味着我要编辑它,如果我传递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**?

hwazgwia

hwazgwia1#

要在_RecordPageState中使用recordObject,您必须像下面这样编写widget.objectname

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

lstz6jyr2#

完整示例

您不需要使用State的构造函数向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")));
af7jpaap

af7jpaap3#

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
   //.....
  }
}
rur96b6h

rur96b6h4#

示例如下:

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 
  }
x3naxklr

x3naxklr5#

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

hmtdttj46#

你不必为此在状态类中创建任何新的对象或变量,你只需要在有状态类中为你的对象定义一个finalnullable变量。你可以像widget.recordObject一样通过widget.访问这个变量

class RecordPage extends StatefulWidget {
   final Record? recordObject;
   RecordPage({required this.recordObject});
   @override
   _RecordPageState createState() => new _RecordPageState();
}

class _RecordPageState extends State<RecordPage> {
   @override
   Widget build(BuildContext context) {
      return Text(
         widget.recordObject == null? "the object is null" : "the object isn't null",
   );
 }
}
zwghvu4y

zwghvu4y7#

你应该使用一个发布/订阅机制。我更喜欢在许多情况下和语言中使用Rx。对于 dart /Flutter,这是一个包:https://pub.dev/packages/rxdart
例如,您可以使用BehaviorSubjectwidget A发出数据,将流传递给widget B,后者监听更改并在setState中应用更改。
小部件A:

// initialize subject and put it into the Widget B
BehaviorSubject<LiveOutput> subject = BehaviorSubject();
late WidgetB widgetB = WidgetB(deviceOutput: subject);

// when you have to emit new data
subject.add(deviceOutput);

小部件B:

// add stream at class level
class WidgetB extends StatefulWidget {
   final ValueStream<LiveOutput> deviceOutput;
   const WidgetB({Key? key, required this.deviceOutput}) : super(key: key);

   @override
   State<WidgetB> createState() => _WidgetBState();
}

// listen for changes
@override
void initState() {
   super.initState();

   widget.deviceOutput.listen((event) {
      print("new live output");
      setState(() {
         // do whatever you want
      });
   });
}
9bfwbjaz

9bfwbjaz8#

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

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中找到,这个概念被称为“提升状态”。

相关问题