Flutter中传入的username参数无法识别的解决方法咨询
解决StatefulWidget传入参数在State类中未定义的问题
当你把HomePage改为StatefulWidget后,State类(_HomePageState)无法直接访问外层HomePage的username属性,必须通过widget关键字来引用。
修改方式
在State类的build方法中,将直接使用$username改为${widget.username}即可。比如你可以在界面上添加展示用户名的文本组件:
Text("欢迎回来,${widget.username}"),
完整修改后的代码
import 'package:flutter/material.dart'; import 'package:geolocator/geolocator.dart'; class HomePage extends StatefulWidget { String username; HomePage({super.key, required this.username}); @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { Position? _currentPosition; void _getUserPosition() async { await Geolocator.checkPermission(); await Geolocator.requestPermission(); Position userLocation = await Geolocator .getCurrentPosition(desiredAccuracy: LocationAccuracy.best, forceAndroidLocationManager: true); setState(() { _currentPosition = userLocation; }); } @override void initState() { super.initState(); _getUserPosition(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Location"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ // 展示传入的用户名 Text("欢迎回来,${widget.username}"), const SizedBox(height: 20), if (_currentPosition != null) Text( "Your Position is: LAT: ${_currentPosition?.latitude}, LNG: ${_currentPosition?.longitude}" ), ElevatedButton( child: const Text("Get location"), onPressed: () { _getUserPosition(); }, ), ], ), ), ); } }
原理说明
StatefulWidget的State类与外层Widget是分离的,State类持有一个widget属性,指向对应的StatefulWidget实例,因此必须通过widget.xxx来访问外层Widget的成员变量。而之前无State的实现(应为StatelessWidget)中,组件属性属于自身,所以可以直接访问。
内容的提问来源于stack exchange,提问作者Shawn Mulligan
相关产品推荐
相关产品推荐

