我在类之间传递参数时遇到麻烦。当我想将电子邮件从MyScreen类传递到TabScreen时,它显示:
[State]对象的配置是相应的[StatefulWidget]实例。此属性由框架在调用[initState]之前初始化。如果父级使用与当前配置相同的[runtimeType]和[Widget.key]将树中的该位置更新为新的窗口小部件,则框架将更新此属性以引用新的窗口小部件,然后调用[didUpdateWidget],并传递旧配置作为参数。
不确定如何处理将这些变量传递给状态类。我可以使用“ $ {widget.email}”,但只能在小部件数组中使用。在“列表”选项卡中,我真的不知道如何。扑朔迷离的做事方式很新...我在某处做错了吗?
import 'package:flutter/material.dart';
import 'package:my_helper/tab_screen2.dart';
import 'package:my_helper/tab_screen3.dart';
import 'tab_screen.dart';
class MainScreen extends StatefulWidget {
final String email; //<-managed to get this variable from previous screen
MainScreen({Key key,this.email}) : super(key: key);
@override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
int currentTabIndex = 0;
List<Widget> tabs = [
TabScreen("Home", widget.email), //<- ERROR this widget.email shows error "only static member can be ...."
TabScreen2("Message"),
TabScreen3("Profile")
];
String $pagetitle = "Home";
onTapped(int index) {
setState(() {
currentTabIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text($pagetitle),
),
body: tabs[currentTabIndex],
bottomNavigationBar: BottomNavigationBar(
onTap: onTapped,
currentIndex: currentTabIndex,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text("Jobs"),
),
BottomNavigationBarItem(
icon: Icon(Icons.mail),
title: Text("Messages"),
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text("Profile"),
)
],
),
);
}
}
我的TabScreen
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class TabScreen extends StatelessWidget {
final String apptitle,email;
TabScreen(this.apptitle,this.email);
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Text(email)
],
);
}
}
答案 0 :(得分:2)
您需要使用tabs
方法初始化initState()
。更改您的_MainScreenState
类以使其与此匹配:
class _MainScreenState extends State<MainScreen> {
int currentTabIndex = 0;
List<Widget> tabs;
String $pagetitle = "Home";
onTapped(int index) {
setState(() {
currentTabIndex = index;
});
}
@override
void initState() {
super.initState();
tabs = [
TabScreen("Home", widget.email),
TabScreen2("Message"),
TabScreen3("Profile"),
];
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text($pagetitle),
),
body: tabs[currentTabIndex],
bottomNavigationBar: BottomNavigationBar(
onTap: onTapped,
currentIndex: currentTabIndex,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text("Jobs"),
),
BottomNavigationBarItem(
icon: Icon(Icons.mail),
title: Text("Messages"),
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text("Profile"),
)
],
),
);
}
}