gpt4 book ai didi

flutter - 如何正确阅读 ModalRoute.of(context).settings.arguments?

转载 作者:行者123 更新时间:2023-12-04 13:01:25 28 4
gpt4 key购买 nike

我对 flutter 感到困惑,当我想从 statefulwidget (initstate) 读取参数并将其访问到小部件构建中时,该变量仍然为空。如何正确阅读?我的代码如下:

import 'package:flutter/material.dart';
import 'package:caritokoonline_v2/components/ResultForm.dart';
import 'package:caritokoonline_v2/podo/SearchBarangRequest.dart';

class ResultBarangActivity extends StatefulWidget {
SearchBarangRequest searchBarangRequest;

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

class _ResultBarangActivityState extends State<ResultBarangActivity> {
final _scaffoldKey = GlobalKey<ScaffoldState>();


@override
void initState(){


Future.delayed(Duration.zero,(){
setState(() {
widget.searchBarangRequest = ModalRoute.of(context).settings.arguments;
print(widget.searchBarangRequest.keyword);
});
});

super.initState();
}

@override
Widget build(BuildContext context) {
if (widget.searchBarangRequest == null) return Scaffold(); //this line is always executed

return ResultForm(
scaffoldKey: _scaffoldKey,
title: widget.searchBarangRequest.keyword,
subTitle: widget.searchBarangRequest.hargaRange.toString(),);
}
}

谢谢!

最佳答案

我知道什么错误,

因此,我创建了全局变量(标题、副标题)并从 searchBarangRequest 分配值,如下代码所示:

字符串标题 = "";
字符串副标题 = "";

class _ResultBarangActivityState extends State<ResultBarangActivity> {
final _scaffoldKey = GlobalKey<ScaffoldState>();


@override
void initState(){


Future.delayed(Duration.zero,(){
setState(() {
widget.searchBarangRequest = ModalRoute.of(context).settings.arguments;
title = widget.searchBarangRequest.keyword;

subtitle = "${Utils().kondisiToString(widget.searchBarangRequest.kondisiBarang)} | ${widget.searchBarangRequest.hargaRange.toString()}";


// print(widget.searchBarangRequest.keyword);

getProducts(widget.searchBarangRequest);
});
});

super.initState();
}
}

它完美无缺!谢谢。

关于flutter - 如何正确阅读 ModalRoute.of(context).settings.arguments?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56108384/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com