我有一個用例,我需要使用 JSON 的鍵值更改應用欄高度。
我有這個腳手架,它顯示了一個普通的 appbar 和 appbar 的高度為 50px:
# app_base.dart
class AppBaseStack extends StatefulWidget {
const AppBaseStack({Key? key}) : super(key: key);
@override
_AppBaseStackState createState() => _AppBaseStackState();
}
class _AppBaseStackState extends State<AppBaseStack> {
double? heightAppBar;
@override
initState() {
loadAppbarHeight();
debugPrint(heightAppBar.toString());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(heightAppBar),
child: AppBar(),
),
);
}
loadAppbarHeight() async {
final String response = await rootBundle.loadString('[route]/file.json');
final data = json.decode(response);
setState(() {
heightAppBar = double.parse(data["app_bar"]["app_bar_height"]);
});
}
}
這是我要獲取的鍵值app_bar_height以更改應用欄高度的 JSON 檔案:
#app_style.json
{
"app_bar":
{
"app_bar_height": "50"
}
}
我想抓取 JSON,然后抓取密鑰app_bar_height并讀取該密鑰的值。然后我想用這個鍵值改變應用欄的高度。如果我想更改應用程式欄的高度,我想通過將app_bar_heightJSON 檔案本身中的鍵值從 50 更改為例如 60 來實作。
我不知道我怎么能做到這一點我嘗試了很多東西,但我想知道在顫振/飛鏢中是否有可接受的方式。
編輯
app_base.dart所以我對檔案進行了一些更改。我添加了加載 json 并抓取 json 并抓取 key 的方法app_bar_height。我還添加了一個initState初始化該方法的方法,但出現錯誤:Null check operator used on a null value
出于某種原因heightAppBar,null我該如何解決這個問題?
uj5u.com熱心網友回復:
在initState(加載視圖之前)呼叫執行此操作的方法:
final String response = await rootBundle.loadString('[route]/file.json');
final data = json.decode(response);
setState(() {
heightAppBar = double.parse(data["app_bar"]["app_bar_height"]);
});
該方法是異步的,因此您需要設定一個默認值heightAppBar然后更新。
uj5u.com熱心網友回復:
這就是我在我的專案中使用的。您可以在添加專案時傳遞高度引數。
class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
final List<Widget>? actions;
final String? text;
final TabBar? bottom;
final Widget? title;
final bool? disableLeading;
final Function? leadingAction;
CustomAppBar({
Key? key,
this.actions,
this.disableLeading,
this.text,
this.title,
this.bottom,
this.leadingAction,
}) : preferredSize = Size.fromHeight(bottom != null ? 120 : 60),
super(key: key);
@override
Widget build(BuildContext context) {
return AppBar(
backgroundColor: primaryColor,
elevation: 0,
iconTheme: IconThemeData(color: Colors.white),
centerTitle: Platform.isIOS ? true : false,
title: this.title??AutoSizeText(text??"",
minFontSize: 11,
maxFontSize: 18,
maxLines: 1,
overflow: TextOverflow.fade,
style: TextStyle(color: Colors.white, fontWeight: FontWeight.w700)),
leading: disableLeading!=null?Container():SizedBox(
child: IconButton(
icon: Icon(
FontAwesomeIcons.chevronLeft,
color: Colors.white,
),
onPressed: () {
Get.back();
if(leadingAction!= null)
leadingAction!();
})),
actions: this.actions,
bottom: this.bottom,
);
}
@override
Size preferredSize;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/435532.html
上一篇:Python字典串列-訪問鍵
